簡體   English   中英

我如何將左右移動分配給我的 2d 游戲

[英]How do i assign left and right movement to my 2d game

所以我是 Csharp 的新手,我正在為游戲編寫這個腳本。 這是一個2D游戲。 我已經為游戲分配了跳躍運動,但是,我堅持固定沿 x 軸的運動。 我真的很感謝你的幫助。

    using UnityEngine;
    // this code uses physics to make player jump

    public class Movement2d : MonoBehaviour
    {
        private bool jumpKeyWasPressed;
        private bool movementRight;
        private CharacterController characterController;
        private Rigidbody2D rigidbodyComponent;
        private Vector3 moveSpeed;

        // Start is called before the first frame update
        void Start()
        {
            rigidbodyComponent = GetComponent<Rigidbody2D>();
            characterController = GetComponent<CharacterController>();
        }

        // Update is called once per frame
        void Update()
        {
            //Check if space key is pressed down
            if (Input.GetKeyDown(KeyCode.Space))
            {
                jumpKeyWasPressed = true;
            }
            if (Input.GetKeyDown(KeyCode.RightArrow))
            {
                movementRight = true;
            }
        }

        private void FixedUpdate()
        {
            if (jumpKeyWasPressed)
            {
                //jump action assigned to space key
                rigidbodyComponent.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
                jumpKeyWasPressed = false;
            }
            if (movementRight)
            { 
                //moving right assigned to right arrow
                Rigidbody.MovePosition();
            }
        }
    }

如果您使用RigidBody.MovePosition ,您需要根據您的速度和自上一幀以來經過的時間移動播放器(以考慮幀卡頓)。

假設您的水平速度存儲在速度矢量的 x 坐標中,您需要編寫:

rigidBodyComponent.MovePosition(new Vector2(moveSpeed.x * Time.deltaTime, 0));

要執行左移,請使用相同的代碼,但使用-moveSpeed.x代替。 在這兩種情況下,不要忘記之后將移動布爾設置為 false。

但是請記住,使用RigidBody.MovePosition可能會導致您的角色高速穿過牆壁。 如果您想避免這種情況,請考慮使用RigidBody.AddForce()就像您在跳躍時所做的那樣。

來源: https ://docs.unity3d.com/ScriptReference/Rigidbody2D.MovePosition.html https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html

暫無
暫無

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

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