C#Player在Unity中移动

时间:2014-12-09 18:18:20

标签: c# unity3d game-engine unityscript

代码非常适合移动带有右箭头和左箭头的刚体,但我无法理解使用maxVelocity和absVelX有什么意义,我不知道他们在代码中的工作。当我删除它时它的效果非常好,但似乎我需要在高级游戏级别。这是一个叫做" Unity 2d由jesse freeman提供必要的培训"

using UnityEngine;

using System.Collections;

public class Player : MonoBehaviour {

public float speed=10f;
public Vector2 maxVelocity=new Vector2(3,5);
public bool standing;
public float jetSpeed=15f;

// Update is called once per frame
void Update () {
            //Force resetted each frame
            var forceX = 0f;
            var forceY = 0f;
            var absVelX = Mathf.Abs (rigidbody2D.velocity.x);
            var absVelY = Mathf.Abs (rigidbody2D.velocity.y);

            if (Input.GetKey ("right")) {
                    if (absVelX < maxVelocity.x)
                            forceX = speed;

            transform.localScale=new Vector3(1,1,1);//Sprite orignal pose

            } else if (Input.GetKey ("left")) {
                    if (absVelX < maxVelocity.x)
                            forceX = -speed;

            transform.localScale=new Vector3(-1,1,1);//Sprite reversal pose

            }
    rigidbody2D.AddForce(new Vector2(forceX,forceY));
}
}

1 个答案:

答案 0 :(得分:0)

从提供的代码看起来,这些变量定义了速度限制,分配给rigidbody2D.velocity.x(对abs的调用是比较绝对矢量幅度而不仅仅是坐标)。

不清楚rigidbody2D.velocity.x是否已设置,但代码假定它可能比3更大,并且程序在最大值上中断。