user2028856
user2028856

Reputation: 3183

Three JS check if position is behind object

I have a 3D character along with several predefined positions on the floor. Is there a way to check if a position is behind the 3D character and not in front or sideways?

I’ve included a rough sketch of what I’m trying to achieve (sorry for the poor drawing). Essentially I would like to return all of the positions of the red circles within the red lines and exclude all other circles outside of these two lines.

enter image description here

Is this possible? If so, is there any suggestion on how I can achieve this? I’m sorry but I don’t actually know which functions to use from Three JS for something like this or if it is possible.

Thank you!

Upvotes: 1

Views: 684

Answers (1)

Kitanga Nday
Kitanga Nday

Reputation: 3565

Yes, it's possible.

You start out by first checking if a point/circle is behind the player. You do this by getting the dot product between the direction player is facing (a unit vector) and the direction vector to the circle (normalize it so that it's also a unit vector). If the values dotProduct <= 0 then the circle is behind your player.

(unit vector means that your vector has a magnitude of one. Which is a fancy way of saying your x/y/z will never go beyond 1)

Code example

// Let's assume that the following code is in some sort of loop, yes

// Get the direction vector to the circle
const directionVect = circle.position.clone().sub(player.position).normalize();

// If your player is a camera you can get the direction like so
const playerFacing = player.getWorldDirection(new THREE.Vector3());

// Orientation
if (playerFacing.dot(directionVect) <= 0) {
    // Circle is behind the player
    // ...to be continued...
} else {
    return;
}

Now that you know which circles are behind your player, you can get the circles within the cone. This is done by getting the angle between the player's position and the circle's position. Then check that the angle fits some criteria (e.g. the angle can't be more than 45deg from back of player).

// ...

// Orientation
if (playerFacing.dot(directionVect) <= 0) {
    // Circle is behind the player
    const angle = player.position.angleTo(circle.position);
    
    if (angle < Math.PI * 0.25) {
        // Do something with circle
    }
} else {
    return;
}

Upvotes: 1

Related Questions