我正在尝试制作一米之类的东西,其中有一个球图像,它是矩形图像的子图像,我希望它来回弹跳。这就是统一 UI 的全部内容。父矩形的宽度可以是任何宽度,并且它应该适应。
这个想法是球来回弹跳,如果当您单击时球完全位于红色区域内,则表示成功并且会触发事件。
ChatGPT 给出了以下代码,但它不起作用。球出界了。
using UnityEngine;
public class BallMovement : MonoBehaviour
{
public float speed = 5f;
private RectTransform parentRect;
int direction = 1;
void Start()
{
// Get the parent rectangle's RectTransform
parentRect = transform.parent.GetComponent<RectTransform>();
// Ensure the parentRect is not null
if (parentRect == null)
{
Debug.LogError("Parent rectangle's RectTransform not found!");
}
}
void Update()
{
// Calculate the movement limits based on the aspect ratio and parent position
float aspectRatio = Screen.width / (float)Screen.height;
float canvasWidth = parentRect.rect.width * aspectRatio;
float leftLimit = parentRect.position.x - canvasWidth / 2f;
float rightLimit = parentRect.position.x + canvasWidth / 2f;
// Move the ball automatically left and right within the calculated limits
transform.Translate(Vector3.right * direction * speed * Time.deltaTime);
// Change direction when reaching the limits
if (transform.position.x < leftLimit || transform.position.x > rightLimit)
{
direction *= -1;
}
}
}
[编辑] 实际上有没有办法用动画来做到这一点?这样我就可以更好地控制球。
你真的不需要经历
Screen
也不是 aspectRatio
...你只关心父矩形的宽度和球矩形的宽度...从这两个你已经可以计算出你需要的任何东西:
public class BallMovement : MonoBehaviour
{
public float speed = 5f;
private RectTransform parentRect;
private RectTransform ownRect;
private int direction = 1;
void Start()
{
// Get the parent rectangle's RectTransform
if(!transform.parent.TryGetComponent<RectTransform>(out parentRect))
{
Debug.LogError("Parent rectangle's RectTransform not found!");
}
if(!TryGetComponent<RectTransform>(out ownRect))
{
Debug.LogError("Own RectTransform not found!");
}
}
void Update()
{
var parentWidth = parentRect.rect.width;
var ownWidth = ownRect.rect.width;
var maxOffset = (parentWidth - ownWidth) / 2f;
var position = ownRect.anchoredPosition;
position.x = Mathf.Clamp(position.x + direction * speed * Time.deltaTime, -maxOffset, maxOffset);
ownRect.anchoredPosition = position;
if(Mathf.Approximately(Mathf.Abs(position.x), maxOffset))
{
direction *= -1;
}
}
}
剩下的就是确保您的球对象锚定到检查器中父对象的center:
Anchors
Min X 0.5 Y 0.5
Max X 0.5 Y 0.5
Pivot X 0.5 Y 0.5