Math Question: Transform, Camera or checkCulling

Hello everybody,
in your opinion what is the best way to understand if an object is in front of or behind the camera?
Method 1, 2 or 3?
An example of use could be removing dead enemy models when they are no longer visible from the player’s camera or adding enemies to the scene when not looking at the spawn point.

// 1.
@Override
public void controlUpdate(float tpf) {
	if (isDead && !spatial.checkCulling(cam)) {
		spatial.removeFromParent();
	}
}

// 2.
@Override
public void controlUpdate(float tpf) {
	if (isDead) {
		Transform tr = new Transform(cam.getLocation(), cam.getRotation(), Vector3f.UNIT_XYZ);
		Vector3f camRelative = tr.transformInverseVector(spatial.getWorldTranslation(), null);
		
		if (camRelative < 0) {
			//The object is behind the camera
			spatial.removeFromParent();
		}
	}
}

// 3.
@Override
public void controlUpdate(float tpf) {
	if (isDead) {
		Vector3f dirToTarget = spatial.getWorldTranslation().subtract(cam.getLocation()).normalizeLocal();
		float angleDiff = cam.getDirection().angleBetween(dirToTarget);
		float threshold = FastMath.DEG_TO_RAD * 45;
		
		if (angleDiff > threshold) {
			spatial.removeFromParent();
		}
	}
}

Just out of curiosity, what does this comment mean in the Transform class? Is the formula correct or not?

        // The author of this code should look above and take the inverse of that
        // But for some reason, they didn't ..
//        in.subtract(translation, store).divideLocal(scale);
//        rot.inverse().mult(store, store);

Do you really want to know if the object is in front of or behind? Or do you want to know if it is in the camera view?

Because “in front” or “behind” is way easier to just take a dot product.

Vector3f camRelative = spatial.getWorldTranslation().subtract(camera.getLocation());
float dot = cam.getDirection().dot(camRelative);

If dot is positive, object is in front (and dot is the distance along its view vector). If dot is negative then the object is behind.

The dot product is a super powerful tool and is cheap (a few mutiplies and a couple adds). It’s uses are myriad and I think it’s one of the main reasons the original Doom was possible at all on that hardware.

3 Likes

I agree with you, I was so into the formulas that I forgot the dot product. Thanks for the reply.