Unity:向上和向下移动精灵

时间:2017-01-23 20:05:24

标签: c# unity5 game-physics unity3d-2dtools

虽然我知道围绕C#的方式,但我很擅长在游戏开发和Unity中使用它。我想让球上下跳动。我可以轻松地让球左右移动,但是当我将代码从'滚动'改为'反弹'时,我得到以下结果:(球对角线不上下)enter image description here

但我想要的是:

enter image description here

// Update is called once per frame
    void Update () {

        if (moveDown) {
            transform.localScale = new Vector3 (-1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.x);
        } else {
            transform.localScale = new Vector3 (1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity = new Vector2 (-speed, GetComponent<Rigidbody2D> ().velocity.x);
        }
    }

我确信答案一定很简单,但经过漫长的一天,我的大脑已经糊里糊涂了。任何人都可以建议吗?

从左到右工作的代码是这样的:

transform.localScale = new Vector3 (-1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.y);

2 个答案:

答案 0 :(得分:0)

Vector2有两个组成部分; X和Y.速度的“X”分量表示物体的水平速度(左/右)。速度的“Y”分量表示物体的垂直速度(上/下)。

要向上和向下移动 ,速度的“X”分量必须为“零”(0),否则对象将继续水平和垂直移动,从而产生对角线。

调用Vector2的构造函数时,传入两个参数;第一个参数是“X”值,第二个分量是“Y”值。在示例代码中,您在第一个(X)参数中传递非零值,从而导致对角线移动。

答案 1 :(得分:-1)

如果有帮助,您可以冻结x位置。

enter image description here