Search code examples
javalibgdxbox2draycasting

LibGDX raycast does not collide with Box2D static object


I'm trying to implement a simple AI for a 2D game in libGDX. The AI should make an enemy follow the player if the player is in range and if the enemy can see the player. To determine whether the enemy can see the player I'm using a raycast.

Now my problem is, that the raycast does not seem to collide with a static body in the Box2D world.

(It's just an assumption, that the static body is the problem, because it's working fine with a dynamic body)

The Question

Do raycasts in libGDX collide with static bodies by default? Or is there an other way to make a raycast collide with static bodies?

I couldn't find any information on this in the libGDX wiki or in the API.

What I've tried so far

I've tested the raycast AI with a dynamic body in between the enemy and the player: dynamic body between enemy and player

Here the enemy with the raycast AI (the one in the upper left) is not moving towards the player (in the lower right) because there is a dynamic body in between them (the other enemy in the middle), which is correctly colliding with the raycast.

But if I put a static body in between the enemy and the player the raycast won't detect the static body, but only the dynamic body (that should be found later than the static body):

static body between enemy and player

Here the static body in the middle is not detected by the raycast.

I've also tested to use setSleepingAllowed(false) on the static body, to make sure it's not just sleeping. But that also didn't fix it.


Solution

  • In box2d, RayCasts should collide with static bodies, so your problem is probably somewhere else.

    Keep in mind that the raycast callback is not reporting the fixtures in order of the distance to the start point. Instead the order is random and you have to handle that in you callback. If this is not the problem, you might want to add some code to the question.