Sid
Sid

Reputation: 71

Gravity not working correctly

My code for physics in my game is this:

    -- dt = time after each update
    self.x = math.floor(self.x + math.sin(self.angle)*self.speed*dt)
    self.y = math.floor(self.y - math.cos(self.angle)*self.speed*dt)
    -- addVector(speed,angle,speed2,angle2)
    self.speed,self.angle = addVector(self.speed,self.angle,g,math.pi)`

when it hits the ground, the code for it to bounce is :

    self.angle = math.pi - self.angle
    self.y = other.y - self.r`

the function addVector is defined here:

    x = math.sin(angle)*speed + math.sin(angle2)*speed2
    y = math.cos(angle)*speed + math.cos(angle2)*speed2
    v = math.sqrt(x^2 + y^2)
    a = math.pi/2 - math.atan(y,x)
    return v,a

but when I place a single ball in the simulation without any drag or elasticity, the height of the ball after each bounce keeps getting higher. Any idea what may be causing the problem?

Edit: self.r is the radius, self.x and self.y are the position of the centre of the ball.

Upvotes: 1

Views: 75

Answers (2)

brianolive
brianolive

Reputation: 1671

I’ve managed to get your code to run and reproduce the behavior you are seeing. I also find it difficult to figure out the issue. Here’s why: movement physics involves position, which is affected by a velocity vector, which in turn is affected by an acceleration vector. In your code these are all there, but are in no way clearly separated. There are trig functions and floor functions all interacting in a way that makes it difficult to see what role they are playing in the final position calculation.

By far the best and easiest-to-understand tutorial to help you implement basic physics lime this is The Nature of Code (free to read online, with interactive examples). As an exercise I ported most of the early exercises into Lua. I would suggest you see how he clearly separates the position, velocity and acceleration calculations.

As an experiemnt, increase g to a much higher number. When I did that, I noticed the ball would eventually settle to the ground, but of course the bouces were too fast and it didnt bounce in a way that seems natural.

Also, define other.y - it doesnt seem to affect the bouncing issue, but just to be clear on what that is.

Upvotes: 0

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23737

Your Y axis is increasing downward and decreasing upward.
Making self.y = math.floor(..) moves your ball a bit upward every frame.
The solution is to store your coordinates with maximal precision.
You could make new variable y_for_drawing = math.floor(y) to draw the ball at pixel with integer coordinates, but your main y value must have fractional part.

Upvotes: 2

Related Questions