Unity 之 Transform.Translate 实现局部坐标系中进行平移操作的方法

在这里插入图片描述

Translate 默认使用局部坐标

在Unity中,Transform.Translate是用于在游戏对象的局部坐标系中进行平移操作的方法。这意味着它将游戏对象沿着其自身的轴进行移动,而不是世界坐标轴。这在实现物体移动、相机跟随、用户交互等方面非常有用。

以下是一个使用Translate方法的示例代码,附带详细的注释:

using UnityEngine;

public class TranslateExample : MonoBehaviour
{
    
    
    public float speed = 5f; // 移动速度

    private void Update()
    {
    
    
        // 获取用户输入的方向
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        // 计算移动方向
        Vector3 moveDirection = new Vector3(horizontalInput, 0f, verticalInput);

        
        // 使用 Translate 方法进行平移
        transform.Translate(moveDirection * speed * Time.deltaTime);

        // 注意:在 Update 方法中使用 Translate 会导致每帧移动,所以速度乘以 Time.deltaTime 以平衡不同帧率下的速度。
    }
}

在这个示例中,我们:

  1. 获取用户输入的方向(水平和垂直)。
  2. 创建一个表示移动方向的向量。
  3. 使用 Translate 方法将游戏对象沿着其自身的轴进行平移。乘以 speedTime.deltaTime 以平衡不同帧率下的速度。

需要注意的是,Translate 方法会修改游戏对象的位置,但它不会受到物理引擎的影响,因此可能不适合用于需要物理交互的情况。此外,Translate 方法是在游戏对象的 Transform 组件上调用的,所以您需要确保对象具有 Transform 组件。

也可以转换成世界坐标

对于世界坐标系的平移,您可以使用Transform.position属性来进行操作,例如:

using UnityEngine;

public class TranslateWorldExample : MonoBehaviour
{
    
    
    public float speed = 5f; // 移动速度

    private void Update()
    {
    
    
        // 获取用户输入的方向
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        // 计算移动方向
        Vector3 moveDirection = new Vector3(horizontalInput, 0f, verticalInput);

        // 使用世界坐标系进行平移
        transform.position += moveDirection * speed * Time.deltaTime;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_74850661/article/details/132461225