一、使用 Transform 组件
public float speed = 3.0f;
void Update()
{
transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
}
二、使用 Vector3 的插值方法
public Transform target; //被跟随的物体
public float speed = 3.0f;
void Update()
{
Vector3 lerp = Vector3.Lerp(transform.position, target.position, Time.deltaTime * speed);
transform.position = lerp;}
三.通过输入控制物体移动
2D移动
public float speed = 3.0f;
private Rigidbody2D rb;
private void Start()
{
rb=GetComponent<Rigidbody2D>();
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vetical = Input.GetAxis("Vertical");
rb.velocity = new Vector2(horizontal, vetical);
}
3D移动
private void Move()
{
float h = Input.GetAxisRaw("Horizontal") * Time.deltaTime * speed;
float v = Input.GetAxisRaw("Vertical")*Time.deltaTime*speed;
this.transform.Translate(h, 0, v);
}