簡體   English   中英

如何使二維對象不斷朝一個方向移動,但在給定水平輸入時改變方向但不改變速度?

[英]How can I make 2d object constantly moving in one direction, but when given horizontal input change direction but not change speed?

我很抱歉,因為我是 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 英語不是我的母語,如有錯誤請見諒!

只要物理參與你不想做任何通過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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM