[SOLVED] raycastFirst works but not raycastAll

I have a raycastFirst which works perfectly with:

this.app.systems.rigidbody.raycastFirst(from, to, function(result) {
    var pickedEntity = result.entity;

But when I replace raycastFirst with raycastAll and result with result[0], it doesn’t work.

this.app.systems.rigidbody.raycastAll(from, to, function(result) {
    var pickedEntity = result[0].entity;

I don’t even get the console log. It seems the raycast isn’t firing at all. What am I doing wrong?

The callback in raycastFirst is legacy from an old version of the API.

Both functions return the result(s).

See API https://developer.playcanvas.com/en/api/pc.RigidBodyComponentSystem.html#raycastAll

I dont think I understand…

So does this mean I should not be using raycastFirst because it’s legacy?

So you mean that both functions are the same and return ALL entities the raycast detects?

I did have a look at the API, and this is what I understood:
Both the functions have the same syntax.
raycastFirst returns one RaycastResult object
raycastAll returns an array of RaycastResult objects.

And I still don’t understand why my code didn’t work.

The callback param shouldn’t be used in raycastFirst (you should see a warning in the console log about it when it is used). The API was changed several years ago but we kept the third param (the callback function) as optional legacy so old projects wouldn’t break.

That’s correct.

raycastAll takes two params, from and to vec3s.

The third param you used (the callback) is ignored because the function is only expecting two params.

Thanks a lot. I understand now. :grinning:

Actually I don’t see any warning about that.

When I use raycastAll, the array that is returned isn’t in order of which entity is detected first. It seems random…

If I have two cubes and I place one infront of the other and I fire a raycast, sometimes results[0] is the first cube and sometimes it’s the second cube.

Shouldn’t it be in order?

@Gamer_Wael I think that is by design in Ammo.js. You can relatively easily sort them in order by using an array sort and checking the distance from your raycast start point.

1 Like