using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour {
private Rigidbody rid;
public float speed = 5f;
// Use this for initialization
void Start () {
rid = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
//SelfMove ();
}
void FixedUpdate()
{
SelfMove ();
//SelfMove2 ();
}
private void SelfMove()
{
float hor = Input.GetAxisRaw ("Horizontal");
float ver = Input.GetAxisRaw ("Vertical");
Vector3 direction = new Vector3 (hor, 0, ver);
transform.Translate (direction * speed * Time.deltaTime);
}
private void SelfMove2()
{
float hor = Input.GetAxisRaw ("Horizontal");
float ver = Input.GetAxisRaw ("Vertical");
Vector3 direction = new Vector3 (hor, 0, ver);
direction.Normalize ();
rid.MovePosition (this.transform.position + direction*speed*Time.deltaTime);
}
private void jump()
{
}
}
①transform.Translate相当于直接改变物体的位置,可以参照自身坐标系或者世界坐标系,如果物体本身不是刚体,这个方法完全可以搞定,但如果物体是刚体,这个方法在刚体发生了碰撞后会发生不规则运动。默认是按自身坐标运动,可进行世界坐标的转换。
②MovePosition方法考虑到了物理引擎的东西。但是MovePosition使用的时候也有不足,比如直接在Update里写rigidbody.MovePosition(vector3.forward)你会发现根本运动不了。
这个方法需要在参数里加上自身的位置。比如写成rigidbody.MovePosition(transform.position + Vector3.forward),你会发现可以正常使用了,而且刚体间的碰撞不会影响接下来的移动,但是不能斜方向运动。默认是按世界坐标运动,不可强制转换。
MovePosition也可按照自身坐标移动:
eg:自身坐标移动
rid.MovePosition(transform.position+transform.forward*Time.deltaTime*speed);
世界坐标移动:
rid.MovePosition(transform.position+Vector3.forward*Time.delteTime*speed);