代码之家  ›  专栏  ›  技术社区  ›  ODOG

Unity 2d动作脚本问题

  •  2
  • ODOG  · 技术社区  · 8 年前

    所以我在Unity中制作了一个2d平台(对c#和Unity来说还是新的),我正在尝试为一个简单的方块制作一个运动脚本,方块将随机停止移动,我必须跳转才能再次开始移动,只会再次发生。

    public class PlayerMovement : MonoBehaviour
    {
        public float moveSpeed;
        public float jumpHeight;
    
        void Start()
        {
        }
    
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
            }
    
            if (Input.GetKey(KeyCode.D))
            {
                GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, 0);
            }
    
            if (Input.GetKey(KeyCode.A))
            {
                GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, 0);
            }
        }
    }
    
    2 回复  |  直到 8 年前
        1
  •  0
  •   Fredrik Schön    8 年前

    1. 不要使用GetComponent<&燃气轮机;()每次要读取值时。创建游戏对象时,将其保存在变量中!(检查下面代码中的Start()-方法)
    2. 如果玩家正在移动,将Y-velocity设置为0。如果你想同时跳跃和移动,这将不起作用。如果你跳跃(将Y-velocity设置为jumpHeight),然后移动(将Y-velocity设置为0),你的角色将漂浮在空中,因为我们每帧都将Y-velocity设置为0。将其设置为当前Y速度!(检查 new Vector2 移动时)

    public class PlayerMovement : MonoBehaviour
    {
        public float moveSpeed;
        public float jumpHeight;
        Rigidbody2D rb;
    
        void Start()
        {
            rb = GetComponent<Rigidbody2D>();
        }
    
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
            }
    
            if (Input.GetKey(KeyCode.D))
            {
                rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
            }
    
            if (Input.GetKey(KeyCode.A))
            {
                rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
            }
        }
    }
    

    对于这个简单的运动脚本,您还可以通过执行以下操作来简化运动代码:

    (前提是您在Unitys输入设置(编辑->项目设置->输入)中使用标准输入设置)

    -1 如果 A left arrow left on a gamepad joystick 按下并 1 如果 D , right arrow right on a gamepad joystick

    void Update() {
        float moveDir = Input.GetAxis("Horizontal") * moveSpeed;
        rb.velocity = new Vector2(moveDir, rb.velocity.y);
    
        // Your jump code:
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
        }
    }
    

    如果您有任何问题或这是否有帮助,请告诉我。

        2
  •  0
  •   Kevin Smith    8 年前

    我实现这一点的唯一方法是在时间管理器中将固定时间步长更改为0.0166。物理引擎和更新似乎与结果不同步。