一、Transform.Translate移动,也是最基本的移动方式
public float speed = 5;//定义一个公有有的速度(后面的数值可以不填,随后在unity中调整,默认为0)
void Update()
{
Move();//引用Move代码
}
void Move()
{
if (Input.GetKey(KeyCode.W)|Input.GetKey(KeyCode.UpArrow))//如果按下W或上箭头
{
this.transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S) | Input.GetKey(KeyCode.DownArrow))//如果按下S或下箭头
{
this.transform.Translate(Vector3.back * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.LeftArrow))//如果按下A或左箭头
{
this.transform.Translate(Vector3.left * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D) | Input.GetKey(KeyCode.RightArrow))//如果按下D或右箭头
{
this.transform.Translate(Vector3.right * speed * Time.deltaTime);
}
}
二、Rigidbody(刚体)
public Rigidbody rigid;
public float speed;
/*如果你选择在Unity里面赋值刚体那以下可以不用做
void start()
{
rigid = GetComponent<Rigidbody>();
}
*/
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");//左右
float vertical = Input.GetAxis("Vertical");//前后
if (Input.GetKey(KeyCode.W)|Input.GetKey(KeyCode.S))
{
rigid.velocity = Vector3.forward * vertical * speed;
}
if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.D))
{
rigid.velocity = Vector3.right * horizontal * speed;
}
}
总结
以上的forward,back , left,right可以在unity的官方文档中查找到分别对应前后左右。
其中update函数是每一帧执行一遍(start只是开始执行一遍),而fixedupdate则是每0.02秒执行一次,Time.deltaTime则是根据机型、电脑的配置自适应帧数,所以,如果是Update中就需要用Time.deltaTime来优化,但FixedUpdate中用Time.deltaTime的话就会显得速度很慢。