在unity实现跳跃的时候按下时间越长,跳跃高度越高的功能
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControl : MonoBehaviour { private Rigidbody2D rb; private Animator animator; public float speed = 10; public bool isGround,isJump; public Transform groundCheck; public LayerMask ground; public float jumpForce = 30; public float jumpTime,jumpTimeCounter; void Start() { rb = GetComponent(); animator = GetComponent(); } void Update() { float x = Input.GetAxisRaw("Horizontal"); float y = Input.GetAxis("Vertical"); if(x != 0) transform.localScale = new Vector3(x, 1 ,1); Vector2 dir = new Vector2(x,y); MoveMent(dir); //如果按下jump并且人物此时在地面,就可以跳跃 if(Input.GetButtonDown("Jump") && isGround){ isJump = true; jumpTimeCounter = jumpTime; Jump(); } //跳跃持续增高 if(Input.GetKey(KeyCode.Space) && isJump ){ if(jumpTimeCounter>0){ rb.velocity = new Vector2(rb.velocity.x,0); rb.velocity += Vector2.up * jumpForce; jumpTimeCounter -= Time.deltaTime; } else { isJump = false; } } if(Input.GetKeyUp(KeyCode.Space)) isJump = false; } //判断是否在地面 void FixedUpdate() { isGround = Physics2D.OverlapCircle(groundCheck.position,0.3f,ground); } void MoveMent(Vector2 dir) { //地面移动 rb.velocity = new Vector2(dir.x*speed , rb.velocity.y); //rb.velocity = Vector2.Lerp(rb.velocity , (new Vector2(dir.x*speed , rb.velocity.y)) , Time.deltaTime); } //正常跳跃 void Jump() { rb.velocity = new Vector2(rb.velocity.x,0); rb.velocity += Vector2.up * jumpForce; } }