Di chuyển một object từ A đến B theo đường cong trong Unity

public class MyObject : MonoBehaviour
{
    private Vector3 startPosition;
    private Vector3 targetPosition;
    private float height = 0.5f; // Chiều cao tối đa khi di chuyển
    private float duration = 0.3f; // Thời gian để di chuyển từ A tới B
    private float timeElapsed;
    private bool isMoving = false;

    void Update()
    {
        if (isMoving)
        {
            timeElapsed += Time.deltaTime;
            float normalizedTime = timeElapsed / duration;
            if (normalizedTime > 1f)
            {
                normalizedTime = 1f;
                isMoving = false;
            }
            Vector3 newPos = CalculateParabolicPosition(startPosition, targetPosition, height, normalizedTime);
            transform.position = newPos;
        }
    }

    Vector3 CalculateParabolicPosition(Vector3 start, Vector3 end, float height, float t)
    {
        Vector3 position = Vector3.Lerp(start, end, t);
        position.y += height * (1 - Mathf.Pow(2 * t - 1, 2));
        return position;
    }

    public void MoveTo(Vector3 newTargetPosition)
    {
        startPosition = transform.position;
        targetPosition = newTargetPosition;
        timeElapsed = 0f;
        isMoving = true;
    }
}
C#

Khi cần di chuyển, gọi hàm MoveTo(<vector3>) và truyền vào một Vector3 là xong.

Lưu ý: Code này có tham khảo từ ChatGPT.

Content Protection by DMCA.com

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *