U_跳跃运动实现源码(非物理/物理)

/*直接改变Y值*/
public class Player : MonoBehaviour {
    public float jumpStartSpeed = 20;
    public float gravitySpeed = 0;

    private float jumpSpeed;
    private bool isJumping;
    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            jumpSpeed = jumpStartSpeed;
            isJumping = true;
        }

        if (isJumping) {
            jumpSpeed += gravitySpeed * Time.deltaTime;
            transform.position += Vector3.up * jumpSpeed * Time.deltaTime;

            if (transform.position.y <= 1) {
                transform.position = new Vector3(transform.position.x, 1, transform.position.z);
                isJumping = false;
            }
        }
    }
}

/*控制器 基于重力加速度公式*/
public class TestJump : MonoBehaviour {
    private bool isGround;/*自己计算是否到地面 官方的 CharacterController.isGrounded 不准*/
    private CharacterController controller;
    public Vector3 playerVelocity;
    private float jumpHeight = 1.0f;
    private float gravityValue = -9.81f;

    private void Start() {
        controller = gameObject.GetComponent<CharacterController>();
    }

    void Update() {
        // 到达地面 速度置空
        if (isGround && playerVelocity.y < 0) {
            playerVelocity.y = 0f;
        }

        // 按下跳跃键 且在地面 垂直速度赋值
        if (isGround && Input.GetKeyDown(KeyCode.F)) {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
        }

        // 不在地面且有速度
        playerVelocity.y += playerVelocity.y == 0 && isGround ? 0 : gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);
    }
}
posted @ 2023-01-31 14:12  匿鱼  阅读(66)  评论(0)    收藏  举报