Cloud Critters是一个跳跃类的游戏。我们的目的是将一些类似《几何大战》这种具有潜质的游戏同《Flappy Bird》和《Don’t Touch the Spikes》这些单点跳跃游戏进行细致的融合。
在《Flappy Bird》中,用户每次点击都会使小鸟上升一个固定的高度。我们在游戏《Cloud Critters》开发前期就决定可以控制角色跳跃的高度,就和《超级玛丽》或者《密特罗德》一样。这样将会给玩家更多的操作空间。
在进入如何实现这样一个可以正确控制跳跃高度的之前,我们先看一下这一段代码,之后的示例都将基于它。
注意:这里为了示范方便,我们将在Update函数中启用跳跃协程(JumpRoutine)。
- 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;
- }
复制代码优点: 能很精确地控制跳跃的最高点,当跳跃按钮松开时,角色即刻下落。
缺点: 尽管说此种跳跃达到最远跳跃距离时,角色的运动轨迹是一条平滑的弧线,可是当我们没有跳到最远距离时,这条运动轨迹就会出现较为明显的波动。
终极版本: - IEnumerator JumpRoutine()
- {
- rigidbody.velocity= Vector2.zero;
- float timer = 0;
- while(jumpButtonPressed&& timer < jumpTime)
- {
- //Calculatehow far through the jump we are as a percentage
- //applythe full jump force on the first frame, then apply less force
- //eachconsecutive frame
- float proportionCompleted = timer / jumpTime;
- Vector2 thisFrameJumpVector = Vector2.Lerp(jumpVector, Vector2.zero,proportionCompleted);
- rigidbody.AddForce(thisFrameJumpVector);
- timer+= Time.deltaTime;
- yieldreturn null;
- }
- jumping= false;
- }
复制代码优点: 玩家可以很好地控制角色跳跃的高度,并且跳跃过程中的运动轨迹都是很平滑的弧线,也不会出现类似喷气式上升的情况。 缺点: 没有缺点,简直完美!
|