Physics Raycast?

So I’ve recently recalled people saying a while back that it’s possible to do raycasts in physics space, but I haven’t seen any obvious example around here.

I’m aware that the fancy car uses 4 of them for wheels but looking through the code of it there doesn’t seem to be anything resembling the usual collisionresults->cast->checkhits process that is used in the scene graph raycasting.

Does anyone know what the most basic and straightforward example would be? Or even which classes are used for it at all.


1 Like

I wrote such a thing a few years back, it uses physics raycasts to check how far above the terrain my vehicle was flying:

import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.PhysicsTickListener;
import com.jme3.bullet.collision.PhysicsRayTestResult;
import com.jme3.bullet.objects.PhysicsRigidBody;
    private float findHeight(final Vector3f from) {
        Vector3f to = new Vector3f(from.x, from.y - RAYTEST_LENGTH, from.z);
        List<PhysicsRayTestResult> results = new ArrayList<PhysicsRayTestResult>();
        this.physicsSpace.rayTest(from, to, results);
        float height = RAYTEST_LENGTH;
        for (PhysicsRayTestResult result : results) {
            int collisionGroup = result.getCollisionObject().getCollisionGroup();
            if (!Constants.CollisionGroup.isPlayer(collisionGroup)) {
                float intersection = result.getHitFraction() * RAYTEST_LENGTH;
                height = Math.min(height, intersection);
        return height;

It casta a ray of length RAYTEST_LENGTH in the negative-Y direction. It filters out collisions with ‘player’ to eliminate self-intersections.
Hope that’ll get you started.


Ah superb, exactly what I needed! :smiley:

Well not exactly exactly, but you know what I mean.

Slight follow up, any possibility to restrict the rayTest to one rigidbody only for optimization?

Curious: if you already know which body you are checking then why not do collisions without physics?

…and if this is for block-based shapes, a custom collider is going to be way more efficient than any of this.

I’ll take that as a no.

If I’m I’m honest it would take way too much time and energy to adequately explain what exactly I’m doing than I have at the moment - to be told what I probably already know at the end.

Thanks anyway :slight_smile:

You can just make a physics space with only that one object in it you want to test against. Otherwise what paul said. Generally the broadphase picks up objects that are far apart using the AABB so if your scene is well partitioned you shouldn‘t have many issues.

But note: if this is for your block ships, intersecting the 3D grid is way faster than individually checking sides. It’s a simple block stepping algorithm.