Physics Raycasting
Use raycasting to detect physics objects:
// Cast a ray through the physics world
const origin = new BABYLON.Vector3(0, 10, -10);
const direction = new BABYLON.Vector3(0, -1, 1).normalize();
const length = 20;
const raycastResult = scene.getPhysicsEngine().raycast(
origin,
direction,
length
);
// Check if we hit something
if (raycastResult.hasHit) {
console.log(`Hit object: ${raycastResult.body.object.name}`);
console.log(`Hit point: ${raycastResult.hitPointWorld}`);
console.log(`Hit normal: ${raycastResult.hitNormalWorld}`);
console.log(`Hit distance: ${raycastResult.hitDistance}`);
}
// Visualize the ray
const rayHelper = new BABYLON.RayHelper(new BABYLON.Ray(origin, direction, length));
rayHelper.show(scene);
// Interactive raycasting with mouse click
scene.onPointerDown = (evt, pickResult) => {
if (pickResult.hit) {
// Cast ray from camera through click point
const ray = scene.createPickingRay(
scene.pointerX,
scene.pointerY,
BABYLON.Matrix.Identity(),
camera
);
const raycastResult = scene.getPhysicsEngine().raycast(
ray.origin,
ray.direction,
100
);
if (raycastResult.hasHit) {
// Apply force at hit point
const hitBody = raycastResult.body;
const hitPoint = raycastResult.hitPointWorld;
const force = ray.direction.scale(50); // Force strength
hitBody.applyForce(force, hitPoint);
}
}
};