移动
// 当前速度
private float _speed = 6.0f;
// FixedUpdate 用于物理计算
void FixedUpdate()
{
// 获取水平和垂直输入
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
// 计算移动向量
Vector3 direction = new Vector3(horizontalInput, 0, verticalInput);
// 将移动向量规范化
direction.Normalize();
// 移动
GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + direction * _speed * Time.fixedDeltaTime);
}
跳跃
// 跳跃力
private float _jumpForce = 1000.0f;
void Update()
{
// 如果按下了跳跃键
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
{
// 向上施加力
GetComponent<Rigidbody>().AddForce(Vector3.up * _jumpForce);
}
}
旋转视角
// 鼠标灵敏度
private float _sensitivity = 2.0f;
// FixedUpdate 用于物理计算
void FixedUpdate()
{
// 获取鼠标输入
float mouseX = Input.GetAxisRaw("Mouse X");
float mouseY = Input.GetAxisRaw("Mouse Y");
// 旋转相机
transform.Rotate(Vector3.up * mouseX * _sensitivity);
transform.Rotate(Vector3.left * mouseY * _sensitivity);
}
奔跑
// 跑步时的速度
private float _runSpeed = 10.0f;
void Update()
{
// 如果按下了奔跑键
if (Input.GetKey(KeyCode.LeftShift))
{
// 设置速度为奔跑速度
_speed = _runSpeed;
}
else
{
// 设置速度为正常速度
_speed = 6.0f;
}
}
在地上判定
// 地面判定半径
private float _groundCheckRadius = 0.2f;
// 层级掩码(地面层)
private LayerMask _groundLayer;
bool IsGrounded()
{
// 创建一个射线
Ray ray = new Ray(transform.position + Vector3.up * _groundCheckRadius, Vector3.down);
// 执行射线检测
RaycastHit hit;
if (Physics.Raycast(ray, out hit, _groundCheckRadius, _groundLayer))
{
return true;
}
return false;
}