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,经测试效果一样。

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值