以下代码来实现在 Unity 中通过按键控制物体移动:

using UnityEngine;

public class ObjectMovement : MonoBehaviour
{
    public float speed = 10f; // 物体移动速度

    void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal"); // 获取水平轴上的输入
        float verticalInput = Input.GetAxis("Vertical"); // 获取垂直轴上的输入
    
        Vector3 direction = new Vector3(horizontalInput, 0, verticalInput); // 创建一个向量表示物体移动方向
        transform.position += direction * speed * Time.deltaTime; // 向物体的位置添加移动方向和速度乘以时间增量的积,从而控制物体移动
    }
}

  要使用此脚本,请将其添加到您想要在游戏中移动的物体上。将所需的速度设置为适当的值,并按照需要调整代码中的其他参数

posted @ 2023-04-24 13:15  xiondun  阅读(399)  评论(0)    收藏  举报