Hi, I’ve got another question in regards to raytracing with PlayCanvas in React. I’ve created a scene with an entity with a sphere, collision and rigidbody (collision set to mesh and rigidbody is set to static). I’m using a script attached to my camera that runs a rigidbody.raycastFirst from my camera’s nearClip to farClip. I can’t seem to get the raycast to detect my sphere at all. I can post further clarification if necessary.
Did you enable usePhysics
on your Application
?
Yes, I have activated physics on application. I’m trying to raycast against a glb model with multiple mesh and targeting that specific mesh. I’m able to get the multiple mesh instances and add a collision mesh, static rigidbody onto the mesh instance through addComponent. But my raycast doesn’t seem to detect anything. So to focus on my problem, I created a simple scene with just a cube and camera, and I tried to raycast against the cube.
class RaycastCamera extends PcScript {
static attributes = {
cameraEntity: { type: "entity", title: "camera" },
};
initialize() {
this._onMouseDown = this._onMouseDown.bind(this);
this._onTouchStart = this._onTouchStart.bind(this);
this.app.mouse.on(pc.EVENT_MOUSEDOWN, this._onMouseDown);
if (this.app.touch) {
this.app.touch.on(pc.EVENT_TOUCHSTART, this._onTouchStart);
}
}
destroy() {
this.app.mouse.off(pc.EVENT_MOUSEDOWN, this._onMouseDown);
if (this.app.touch) {
this.app.touch.off(pc.EVENT_TOUCHSTART, this._onTouchStart);
}
}
_onMouseDown(evt) {
this._doPick(evt.x, evt.y);
}
_onTouchStart(evt) {
if (evt.touches.length === 1) {
this._doPick(evt.touches[0].x, evt.touches[0].y);
}
evt.event.preventDefault();
}
_doPick(x, y) {
const from = this.cameraEntity.current.getPosition();
const to = this.cameraEntity.current.camera.screenToWorld(x, y, 10000);
const hit = this.app.systems.rigidbody.raycastFirst(from, to);
if (!hit) {
console.log("RaycastCamera: Nothing hit.");
return;
}
console.log("RaycastCamera selected entity:", hit.entity.name);
console.log(" Mesh asset name:", hit.meshInstance.mesh.name);
console.log(" GraphNode (node) name:", hit.meshInstance.node.name);
}
update() {
if (this.camera) return;
this.camera = this.cameraEntity.camera;
}
}
<Application usePhysics={true}>
<Entity scale={(5, 5, 5)}>
<Render type="sphere"></Render>
<Collision type="mesh"></Collision>
<RigidBody type="static"></RigidBody>
</Entity>
<Entity>
<Light
type="directional"
intensity={5}
color="#ff0000"
affectDynamic={true}
affectSpecularity={true}
></Light>
</Entity>
<Entity ref={cameraEntity}>
<Camera></Camera>
<OrbitControls></OrbitControls>
<Script script={RaycastCamera} cameraEntity={cameraEntity} />
</Entity>
</Application>