- void Update()
- {
- if(jumpButtonDown&& !jumping)
- {
- jumping= true;
- StartCoroutine(JumpRoutine());
- }
- }
复制代码在实际的工程中,你最好在FixedUpdate中处理物理运动相关的行为。
匀加速情况:
- {
- rigidbody.velocity= Vector2.zero;
- floattimer = 0;
- while(jumpButtonPressed &&timer < jumpTime)
- {
- //Adda constant force every frame of the jump
- rigidbody.AddForce(jumpVector);
- timer+= Time.deltaTime;
- yieldreturn null;
- }
- jumping= false;
- }
复制代码优点:
跳跃高度的最小最大值差距较大,玩家可以更好的控制角色跳跃的高度和距离。
缺点:
每一帧都给角色施以一个固定的外力,导致角色在竖直方向上的速度会越来越快,就像背着一个喷气装置。
类抛物情况:
- IEnumeratorJumpRoutine()
- {
- //Setthe gravity to zero and apply the force once
- floatstartGravity = rigidbody.gravityScale;
- rigidbody.gravityScale= 0;
- rigidbody.velocity= jumpVector;
- floattimer = 0f;
- while(jumpButtonPressed&& timer < jumpTime)
- {
- timer+= Time.deltaTime;
- yieldreturn null;
- }
- //Setgravity back to normal at the end of the jump
- rigidbody.gravityScale= startGravity;
- jumping= false;
- }
复制代码优点:
在跳起的过程中不会一直加速。在开始跳跃的那一刻,角色就会获得最大的跳跃速度,当用户松开按键或者达到跳跃最大高度后,便落下。这种跳跃形式和《超级玛丽》 比较接近。
缺点:
在玩家松开跳跃键后,角色还会持续几帧跳跃动画,继续上升直到向上的速度降为零才下落。这意味着即使你只是快速按一下跳跃键,角色也会跳起相当高的一端距离。
类抛物情况改进版:
- IEnumeratorJumpRoutine()
- {
- //Addforce on the first frame of the jump
- rigidbody.velocity= Vector2.zero;
- rigidbody.AddForce(jumpVector,ForceMode2D.Impulse);
- //Waitwhile the character's y-velocity is positive (the character is going
- //up)
- while(jumpButtonPressed&& rigidbody.velocity.y > 0)
- {
- yieldreturn null;
- }
- //Ifthe jumpButton is released but the character's y-velocity is still
- //positive...
- if(rigidbody.velocity.y> 0)
- {
- //...setthe character's y-velocity to 0;
- rigidbody.velocity= new Vector2(rigidbody.velocity.x, 0);
- }
- jumping= false;
- }
复制代码