Goals:
Implement the first-person jump function in Unity, based on CharacterController
components
private float jumpSpeed; //跳跃速度
private bool isGround;//是否在地面
private bool verticalVelocity; //当前垂直速度
void Update() {
Jump(); //跳跃事件
}
void Jump() {
bool isKeyDownSpace = Input.GetKeyDown(KeyCode.Space);
if (verticalVelocity != 0 || isKeyDownSpace) {
//按下空格键 或者 具备速度 检测地面
isGround = Physics.Raycast(transform.position, Vector3.down,0.1f);
}
if (isGround && isKeyDownSpace) {
//跳跃速度初始值
MyLogger.Print("玩家跳跃");
verticalVelocity = jumpSpeed;
}
if (!isGround) {
//空中持续受到重力
verticalVelocity -= gravity * Time.deltaTime;
}
if (isGround && verticalVelocity < 0) {
//是否在地面(下落时) Y 轴速度为 0
verticalVelocity = 0;
}
transform.position += Vector3.up * verticalVelocity * Time.deltaTime;
}