Unity 角色左右移动教程:简单实现角色移动
要在Unity中使角色左右移动,可以通过以下步骤实现:
- 创建一个角色游戏对象,并将其添加到场景中。
- 在角色游戏对象上添加一个Rigidbody组件,以便可以在物理引擎中进行移动。
- 在脚本中添加以下代码:
public class CharacterController : MonoBehaviour
{
public float moveSpeed = 5f; // 移动速度
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float horizontalInput = Input.GetAxis('Horizontal'); // 获取水平输入
Vector3 movement = new Vector3(horizontalInput, 0f, 0f) * moveSpeed; // 创建移动向量
rb.velocity = movement; // 应用移动向量到Rigidbody的速度
}
}
- 将此脚本添加到角色游戏对象上。
- 运行游戏,在Unity编辑器中按下左右箭头键或A/D键,角色将左右移动。
原文地址: https://www.cveoy.top/t/topic/qfUA 著作权归作者所有。请勿转载和采集!