SamesJeabrook
SamesJeabrook

Reputation: 1567

Raycasting in threeJs, when target is over object

I'm fairly new to three.js and trying to get a better understanding of ray casting. I have used it so far in a game to show when an object collides with another on the page which works perfectly. In the game I'm building this is to take health from the hero as it crashes into walls.

I am now trying to implement a target which when hovered over some objects it will auto shoot. However the target only registers a target hit once the object passes through the target mesh rather than when its ray is cast through it.

to further detail this, the ray is cast from the camera through the target, if the target is on a mesh (stored as an object array) then I want it to trigger a function.

within my update function I have this:

    var ray = new THREE.Raycaster();
    var crossHairClone = crossHair.position.clone();
    var coards = {};
    coards.x = crossHairClone.x
    coards.y = crossHairClone.y
    ray.setFromCamera(coards, camera);
    var collisionResults = ray.intersectObjects( collidableMeshList );
    if ( collisionResults.length > 0 ) {
        console.log('Target Hit!', collisionResults)
    }

The console log is only triggered when the collidableMeshList actually touches the target mesh rather than when it is aiming at it.

How do I extend the ray to pass through the target (which I thought it was already doing) so that if anything hits the ray then it triggers my console log.

Edit

I've added a URL to the game in progress. There are other wider issues with the game, my current focus is just the target ray casting.

Game Link

Upvotes: 1

Views: 1178

Answers (1)

SamesJeabrook
SamesJeabrook

Reputation: 1567

Many thanks to everyone who helped me along the way on this one but I finally solved it, only not through the means that I had expected to. Upon reading into the setFromCamera() function it looks like it is mainly used around mouse coards which in my instance was not what I wanted. I wanted a target on the page and the ray to pass through this. For some reason my Ray was shooting vertically up from the centre of the whole scene.

In the end I tried a different approach and set the Rays position and direction directly rather rely on setting it from the cameras position.

var vector = new THREE.Vector3(crossHair.position.x, crossHair.position.y, crossHair.position.z);
var targetRay = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
var enemyHit = targetRay.intersectObject( enemy );

if ( enemyHit.length > 0 ) {
    console.log('Target Hit!', targetRay)
}

I'll leave this up for a while before accepting this answer in case anyone has a better approach than this or has any corrections over what I have said in regards to setFromCamera().

Upvotes: 0

Related Questions