c#前后左右移动代码
时间: 2023-12-14 21:34:48 浏览: 31
以下是一个简单的C#脚本,可以实现在Unity中WASD或方向键来控制物体的前后左右移动,并且可以使用鼠标来控制物体的旋转:
```csharp
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float MoveSpeed = 5f;
public float RotateSpeed = 100f;
void Update()
{
// 获取用户输入
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
// 计算移动向量
Vector3 moveDirection = new Vector3(horizontal, 0f, vertical).normalized;
// 移动物体
transform.Translate(moveDirection * MoveSpeed * Time.deltaTime);
// 计算旋转向量
float rotateAmount = -Input.GetAxis("Mouse X") * RotateSpeed * Time.deltaTime;
Vector3 rotateDirection = new Vector3(0f, rotateAmount, 0f);
// 旋转物体
transform.Rotate(rotateDirection);
}
}
```