Unity获取物体自身坐标轴的方向以及沿着该方向运动的方法

有时候对于一个游戏对象,需要其沿着自身的坐标轴方向进行运动,那么首先如何获取自身的坐标轴方向?

获取自身的坐标轴方向可以通过transform组件进行获取(负方向加负号即可)

 Vector3 moveDirection = transform.right;  获取自身的x轴的方向

 Vector3 moveDirection = transform.forward;  获取自身的z轴的方向

 Vector3 moveDirection = transform.up;  获取自身的y轴的方向

下面举例说明,假设在场景中创建一个Cylinder圆柱体对象,如下:

下面测试代码,使其沿着自身坐标x轴(即红色轴线)进行运动,脚本MoveControl代码如下:

 

 
  1. using System.Collections;

  2. using System.Collections.Generic;

  3. using UnityEngine;

  4.  
  5. public class MoveControl : MonoBehaviour {

  6.  
  7. private float speed = 1.0f;

  8.  
  9. // Use this for initialization

  10. void Start () {

  11.  
  12. }

  13.  
  14. // Update is called once per frame

  15. void Update () {

  16. Vector3 moveDirection = transform.right;

  17. transform.position += moveDirection * Time.deltaTime * speed;

  18. // transform.Translate(Vector3.right * Time.deltaTime * speed, Space.Self);

  19. }

  20.  
  21. }

下面将脚本添加到场景中的Cylinder对象,测试其运动如下:

 



通过观察物体运动可知,正好符合我们的需求。

另外注意看我代码中标红的部分,还有另外一种方法,也可以实现沿着坐标轴的运动,代码如下:

 

 
  1. using System.Collections;

  2. using System.Collections.Generic;

  3. using UnityEngine;

  4.  
  5. public class MoveControl : MonoBehaviour {

  6.  
  7. private float speed = 1.0f;

  8.  
  9. // Use this for initialization

  10. void Start () {

  11.  
  12. }

  13.  
  14. // Update is called once per frame

  15. void Update () {

  16. transform.Translate(Vector3.right * Time.deltaTime * speed, Space.Self);

  17. }

  18.  
  19. }

即可以在平移函数里面,直接改变参考坐标系参数为Space.Self,经测试效果一样。