using UnityEngine;
public class PlayerControl : MonoBehaviour
{
// 走速
public float walkSpeed = 2f;
// 跑速
public float runSpeed = 5f;
// 水平输入
public float horizontalInput;
// 垂直输入
public float verticalInput;
// 旋转速度
public float rotationSpeed = 50f;
// 动画控制器
private Animator animator;
// rigidbody
public Rigidbody rigid;
// 跳跃力
public float jumpForce = 3f;
// 是否处于地面
public bool isGrounded;
// 检测地面的transform
public Transform groundCheck;
// 检测地面的距离
public float groundCheckDistance = 0;
// 检测地面的层级
public LayerMask groundLayer;
void Start()
{
// 获取动画控制器
animator = GetComponent<Animator>();
}
void Update()
{
// 获取水平和垂直输入
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
// 根据是否按下shift键来决定当前速度
float currentSpeed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;
// 移动
Vector3 move = new Vector3(horizontalInput, 0, verticalInput);
transform.Translate(move * currentSpeed * Time.deltaTime, Space.Self);
// 旋转
transform.Rotate(Vector3.up, horizontalInput * rotationSpeed * Time.deltaTime);
// 动画速度
float animSpeed = Mathf.Abs(verticalInput);
if (Input.GetKey(KeyCode.LeftShift))
{
animSpeed *= 2f;
}
// 设置动画速度
animator.SetFloat("Speed", animSpeed);
// 检测地面
CheckGround();
// Debug画出检测地面的线
Debug.DrawRay(groundCheck.position, Vector3.down * groundCheckDistance, Color.red);
// 如果按下空格键且处于地面
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
// 跳跃
Jump();
}
}
// 检测地面
void CheckGround()
{
// 检测是否有物体在检测距离内
isGrounded = Physics.Raycast(groundCheck.position, Vector3.down, groundCheckDistance, groundLayer);
}
// 跳跃
private void Jump()
{
// 添加一个向上的力
rigid.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
评论 (0)