Search code examples
luagame-physics

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.


Solution

  • 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.