Smooth fly movement like flappy bird or jet pack joy ride with gravity and Accelaration

纵然是瞬间 提交于 2019-12-01 21:07:46

Gravity is just a downward acceleration. An acceleration is in turn just a change in velocity (directed speed). For the following discussion, I make the following assumptions to keep things simpler:

  • your horizontal speed is constant
  • input tapping is called 'flapping'
  • gravity behaves normally
  • simplistic, rather than a scientific approach/verbiage is OK for our purposes

For each pass through the update loop, all of the various accelerations must be summed and the total added to the current speed. In your situation, there are 2 possible accelerations, gravity and possibly flapping. Gravity is constant and is a negative value (is works downward), while flapping only occurs during tapping as is positive (upwards).

Let's set gravity to -10 pixels per loop, tapping to be +25 pixels per loop, and initial height to 500. Some initial definitions are:

static final int gravity = -10;   // constant downward acceleration
static final int flapping = 25;   // upward acceleration whenever isFlapping is true

Boolean isFlapping = false;   // Is the bird flapping

int dY = 0; // current vertical speed
y = 500;    // current vertical position

Each time through the loop, without flapping, the speed calculation would be:

dY += gravity + flapping;

So the first time through, the speed calculation would be dY = 0 + (-10) + 0 = -10. The second time, dy = -10 + (-10) + 0 = -20. The 5th time, dy = -40 + (-10) = -50. Each time through, the downward speed is 10 more than the time before.

The height is simple. Each time through, the height changes by the amount of vertical acceleration. So:

y += dY;

So the first time through, the height would be y = 500 + (-10) = 490. The second time, y = 490 + (-20) = 470. And the 5th time, y = 400 + (-50) = 350. Because the rate of falling increases each time through, the bird will plummet faster and faster until splat!

That's where flapping comes in. Each time through the loop where flapping is occurring, a +25 will be applied to the dY calculation. So lets assume the bird starts flapping in 6th iteration. The dy calculation would be dy = -50 + (-10) + 25 = -35 and the height would be y = 350 + (-35) = 315. The next time through would give dy = -35 + (-10) + 25 = -20 and the height would be y = 350 + (-20) = 295. Still falling, but more slowly. The time after: that dy = -20 + (-10) + 25 = -5 and y = 295 + (-5) = 290. The time after that finally shows a gain in height: dy = -5 + (-10) + 25 = 10 and y = 290 + 10 = 300.

All that said, you'll definitely need to play with the numbers until you get a satisfying result.

TLDR: You don't want to change the height directly using gravity and flapping. Instead you want to use gravity and flapping to calculate the speed for each iteration and then use that to adjust the height.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!