Wednesday, September 14, 2016

xna - Ball bouncing infinitely and constantly


Alright, so I've got hold of some simple physics mechanics, and am currently trying to implement bouncing. Based on the first answer of this question, I've developed the following algorithm:


    Vector2 velocity;

float gravity;
float elasticity;


Hitbox dummy;

// ---

void bounce() {
dummy.MoveY(velocity.Y);
velocity.Y += gravity;

if (dummy.ThereWasContact.South) velocity.Y *= -elasticity;
}


Gravity can be any value, and Elasticity is always between 0.0f and 1.0f. Velocity.Y's initial value can also be anything.


Weight factors aside, which would determine a minimal rebound force for the object to be able to leave the ground again and (probably) aren't related to the problem, this is apparently fallacious.


What happens here is somewhat like this:


enter image description here


If I drop an object from a height of 128 units, for example, 0u marking ground height, with a gravity of 1u and elasticity of 0.9, the object would bounce once, reach a maximum height of ~126u from the rebound, and from then on keep alternating on maximum heights between this and ~122u.


This example is based on one of my own experiments, in which I drop an object from a height of 64 pixels and there is a floor at 192 pixels. The maximum height will keep going from ~66 pixels to ~70.


What am I missing? Does weight after all do more than I think? If I need to explain something better or details appear to be missing, let me know.



Answer



Whenever the ball hit the ground, first you add gravity, then you invert the direction, thus the ball is going to spring back with greater speed. Let's step through a case where elasticity is 1, gravity is 1 and the ball's initial speed is 10:




  1. The ball moves 10 and hit the ground.

  2. The speed is increased to 11.

  3. The ball's speed is changed to -11.


Next update:



  1. The ball moves -11.

  2. The speed is decreased to -10.



So the ball impacted the ground with speed 10 and left with speed -11, next time it hit the ground it will be at speed 11, and it will leave at speed -12 etc.


A very simple fix is to split gravity application into two, half before collision detection and half after.


The future


Your next error will be that the ball get stuck in the ground. This happens because you let the ball pass into the ground before registering a collision, and sometimes the ball will have lost so much speed that the following move doesn't take it out of the ground, so your collision detection invert its direction again. The easy fix is to check that the ball is actually moving towards the object that it is colliding with before inverting the direction.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...