📜  unity move 字符 - C# (1)

📅  最后修改于: 2023-12-03 15:35:29.990000             🧑  作者: Mango

Unity Move 字符 - C# 介绍

在 Unity 中,通过使用 C# 脚本,我们可以轻松地在场景中移动游戏对象。这篇文章将介绍 Unity 中移动字符的方法。

常用数据类型

在 C# 中,我们可以使用以下数据类型来存储对象的位置和方向:

  • Vector3:3D 向量,包含 X、Y 和 Z 轴坐标;
  • Quaternion:四元数,包含对象的旋转值。
移动游戏对象

我们可以在脚本中使用以下代码来移动游戏对象:

using UnityEngine;

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

    private void Update()
    {
        // 根据当前输入进行移动
        float horizontal = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        float vertical = Input.GetAxis("Vertical") * speed * Time.deltaTime;
        transform.Translate(horizontal, 0, vertical);
    }
}

在这个脚本中,我们在每一帧都检查用户输入,使用 Input.GetAxis 方法获取水平和垂直方向上的移动值。我们乘以游戏对象的速度和 Time.deltaTime,以确保运动平滑。最后,我们使用 transform.Translate 方法将游戏对象移动到新的位置。

旋转游戏对象

我们可以使用以下代码旋转游戏对象:

using UnityEngine;

public class RotateObject : MonoBehaviour
{
    public float speed = 5f; // 旋转速度

    private void Update()
    {
        // 根据当前输入进行旋转
        float horizontal = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        float vertical = Input.GetAxis("Vertical") * speed * Time.deltaTime;
        transform.Rotate(vertical, horizontal, 0);
    }
}

在这个脚本中,我们通过使用 Input.GetAxis 获取水平和垂直方向上的旋转值,并乘以旋转速度和 Time.deltaTime。然后,我们使用 transform.Rotate 方法将游戏对象旋转到新的角度。

移动字符

通过组合移动和旋转代码,我们可以移动字符。以下是一个简单的脚本,用于在相应的方向上移动字符,使其看起来像是在行走:

using UnityEngine;

public class MoveCharacter : MonoBehaviour
{
    public float speed = 5f; // 移动速度
    public float rotateSpeed = 30f; // 旋转速度

    private void Update()
    {
        // 获取当前输入
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        // 如果字符正在移动,则调用 Move 方法
        if (horizontal != 0 || vertical != 0)
        {
            Move(horizontal, vertical);
        }
    }

    private void Move(float horizontal, float vertical)
    {
        // 计算移动方向、旋转方向和速度
        Vector3 direction = new Vector3(horizontal, 0, vertical);
        Quaternion rotation = Quaternion.LookRotation(direction);
        float moveSpeed = speed * Time.deltaTime;

        // 旋转到正确的角度并移动游戏对象
        transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, rotateSpeed * Time.deltaTime);
        transform.Translate(Vector3.forward * moveSpeed);
    }
}

在这个脚本中,我们首先使用 Input.GetAxis 获取移动值,并检查它们是否为零,以避免不必要的计算。

Move 方法中,我们计算移动方向和旋转方向,并将它们传递给 Quaternion.LookRotation 方法。然后我们计算速度,旋转游戏对象到正确的角度,并移动游戏对象。