Quick Links: Gideros Home | Download Gideros | Developer Guide
How to get collision in box2d?
  • HolonistHolonist +1 -1
    Member
    Hi,

    In box2d the Debug Draw is highlighting objects that are colliding.
    How can I get that information in the code? (test if object A collides with object B)

    I want to apply a modification on an object, based on the other object it collides with.

    Edit: Also, I need to access the sprite which the body is attached to.

    Greetings
  • HolonistHolonist +1 -1
    Member
    Found out how to detect collision by looking at one of the tutorials.

    To access the sprite, you can actually set a back-reference to it in the body.

    ball.body = self.physics:createBody{type = b2.DYNAMIC_BODY}
    ball.body:setPosition(ball:getPosition())
    ball.body:setAngle( ball:getRotation() * math.pi/180 )
    ball.body.parent = ball


    To get the sprite, you can:
    - get fixture
    - get body from fixture
    - get parent from body, which we did set above
    self.physics:addEventListener(Event.BEGIN_CONTACT, function(e)
    local fixtureA = e.fixtureA
    local fixtureB = e.fixtureB
    local bodyA = fixtureA:getBody()
    local bodyB = fixtureB:getBody()

    bodyB.parent:setRotation(bodyA.parent:getRotation())
    end)


    Note that this is not usually needed if you do something with physics!

    But it my case it was. Now if someone wants to know why, here's an awful video :'D
    The guy's body is a ball, and the sprite is not synced with the ball's rotation (obviously). But the guy's sprite orientation should be synced with the surface's rotation.
    https://youtu.be/SDvgwrDQIIw


    Just for fun, what happens IF the guy's rotation is synced with his body :D
    https://youtu.be/bf8i3YVPo0Y
  • totebototebo +1 -1 (+2 / -0 )
    Member
    Welcome to the world of physics! I use collision data all the time, and, in fact, built an entire game dependent on collisions; Scrappy Cat.

    It takes a little getting used to, because you get collisions for all fixtures at the same time. It takes a little filtering to use them.

    Likes: Holonist, antix

    My Gideros games: www.totebogames.com

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Login with Facebook Sign In with Google Sign In with OpenID

In this Discussion

Top Posters