Page 1 of 1

Box2D collision issue

Posted: Tue Apr 21, 2015 8:39 pm
by HoryWan
Hi,
I have tried to use Box2D to bounce a ball on a platform.
The problem is that the ball seems to hit an invisible platform and bounce some 20 pixels above the actual platform.
Any suggestion is welcome!
love.physics.setMeter(64)
local world = love.physics.newWorld(0, 9.8 * 64, true)

objects = {}

objects.ground = {}
objects.ground.body = love.physics.newBody(world, 0, 400, "static")
objects.ground.shape = love.physics.newRectangleShape(800, 50)
objects.ground.fixture = love.physics.newFixture(objects.ground.body, objects.ground.shape, 1)

objects.ball = {}
objects.ball.body = love.physics.newBody(world, 220, 100, "dynamic")
objects.ball.shape = love.physics.newCircleShape(20)
objects.ball.fixture = love.physics.newFixture(objects.ball.body, objects.ball.shape, 1)
objects.ball.fixture:setRestitution(0.9)

function love.load(arg)

end

function love.draw(dt)
love.graphics.setColor(192,23, 30)
love.graphics.rectangle ("fill", objects.ground.body:getX(), objects.ground.body:getY(), 800, 50)

love.graphics.setColor(92,123, 30)
love.graphics.circle ("fill", objects.ball.body:getX(), objects.ball.body:getY(), objects.ball.shape:getRadius())
end

function love.update(dt)
world:update(dt)

end

Re: Box2D collision issue

Posted: Wed Apr 22, 2015 3:43 am
by bobbyjones
Hey I think most likely the problem is the way you are drawing your rectangle. I believe if you switch that with love.graphics.polygon("fill",objects.ball.shape:getPoints()) it would work and the reason for this is that the bodies x and y for a rectangle is the center if I'm not mistaken so when you try to draw you draw it wrong. Also if your going to be using box2d I recommend using a debug draw lib. If you google "love2d box2d debug draw" you should find one. A debug draw lib can help figure out why certain things are not working right

Re: Box2D collision issue

Posted: Wed Apr 22, 2015 3:46 am
by adnzzzzZ
What bobbyjones said is right. When you do

Code: Select all

love.graphics.rectangle ("fill", objects.ground.body:getX(), objects.ground.body:getY(), 800, 50)
The x, y positions you're getting are the center of the box2d body, meaning you're drawing from the center position 800 units to the right and then 50 down, leaving 400 units left and 25 units up unaccounted for, which seems to be the behavior you're describing. To fix you should just do:

Code: Select all

love.graphics.rectangle ("fill", objects.ground.body:getX() - 400, objects.ground.body:getY() - 25, 800, 50)
Or you can use getPoints like bobbyjones said.

Re: Box2D collision issue

Posted: Wed Apr 22, 2015 5:38 am
by HoryWan
It works now, thank you guys!