4
\$\begingroup\$

I have a character in a 3D world which is facing an arbitrary direction on a flat plane, the player can click on the left or right side of the character and based on which side is clicked on a different action happens.

How can I determine which side the click occured on? Obviously for straight on ahead (0,0,1) I can simply use the x coordinate of the click point to determine if it's the left or right hand side, but what about other cases?

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

You first have to figure out which direction is 'to the right' of your character. For thsi you will need to know which way the character is facing (uusally 'direction') and which way is up typically (0,1,0) or it could be the normal of the plane the character moves around on.

right = Vector3.Cross(direction, up);

enter image description here

Next, we need a vector representing the relative position of the mouse click and the character.

mouseDir= mousePos-charPos;

finally, we need to check if the angle between the right vector and the mouseDir vector is greater than or less than 90 degrees. If the angle is less than 90deg the the mouse click is on the right, other wise it is on the left.

The dot product will return a positive value if the angle is less than 90, a negative value if the angle is greater than 90.

if(Vector3.Dot(right, mouseDir) <0){
   //do left hand stuff
}else{
   //do right hand stuff
}
\$\endgroup\$
2
\$\begingroup\$

You can use vector cross product for that. Create a vector from character to the clicked position and take a cross product of that and the character facing direction. The sign of the cross product "up" component determines which side was clicked. For ground plane this is the y-component of the cross product. For arbitrary plane, use dot product of the cross product and the plane normal to get the sign.

vec3 delta = clickPosition - characterPosition;
vec3 cross = crossProduct(delta, characterDirection);
float dot = dotProduct(cross, planeNormal);
if (dot < 0) {
    // Do something
}
else {
    // Do something else
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .