我很抱歉,因為我是 Unity 庫和 Unity 本身的純菜鳥。
我正在創建一個簡單的 2d 游戲,其中一個 2d 物件需要不斷地朝著一個方向移動,但是當應用水平輸入(例如 A、D)時,它需要改變運動矢量而不是改變速度。
該物件有一個屬性 Rididbody2d
這是我到目前為止想到的:
{
[SerializeField]
private float speed;
[SerializeField]
private float rotationSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update ()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector2 movementDirection = new Vector2(horizontalInput, verticalInput);
float inputMagnitude = Mathf.Clamp01(movementDirection.magnitude);
movementDirection.Normalize();
transform.Translate(movementDirection * speed * inputMagnitude * Time.deltaTime, Space.World);
if (movementDirection != Vector2.zero) {
Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, movementDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
}
我的想法是,在更新期間,我們應該了解輸入是否已注冊,如果是,則當前向量乘以 (?) 已接收的角度(如果按下 0.1 秒 -> 0deg 1deg 如果按下2 秒 -> 0deg 例如 90 度)。
然而!按照教程,我設法讓這個東西只有在按下鍵時才能移動。我用谷歌搜索了一下,發現實際上沒有任何幫助。手冊重讀了很多次。請幫我!
PS 英語不是我的母語,如有錯誤請見諒!
uj5u.com熱心網友回復:
只要物理參與你不要想通過做任何事情transform都而是通過剛體部件,也沒有在Update,但在FixedUpdate..否則,你都挺奇怪的行為,并打破他的物理/沖突檢測!
在我看來,您想要做的是:
[SerializeField] private float speed;
[SerializeField] private float rotationSpeed;
// reference this in the Inspector if possible
[SerializeField] private Rigidbody2D rigidbody;
// keep track of the target rotation
// for Rigidbody2D this is a simple float for the rotation angle
private float angle = 0;
private void Awake()
{
// as fallback get the Rigidboy2D on runtime
if(!rigidbody) rigidbody = GetComponent<Rigidbody2D>();
}
private void Update ()
{
// Still get user input in Update to not miss a frame
// evtl you would need to swap the sign according to your needs
angle = Time.deltaTime * rotationSpeed * Input.GetAxis("Horizontal");
}
private void FixedUpdate()
{
// rotate the Rigidbody applying the configured interpolation
rb.MoveRotation(angle);
// assuming if the object is not rotated you want to go right
// otherwise simply change this vector
rb.velocity = rb.GetRelativeVector(Vector3.right).normalized * speed;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340359.html
