How do I check if something is to the left of something and something is to the right of something?

For example a car that needs to do corrections.

The destination is in front but it’s slightly to the right relative to the front direction of the car. Like the lookvector.

I want to determine if the destination is to the left or to the right side of the car.

2 Likes

have you tried raycasting not only would this let you know whats to the side but also the distance

I’m not exactly sure but maybe you need to use CFrame.LeftVector and CFrame.RightVector?

Assume you have a part and want to see if this part is to left or right of player’s torso

local cframe = torso.CFrame:ToObjectSpace(part.CFrame)
if cframe.X > 0 then
   print "Part is to right of player!"
else
   print "Part is to left of player!"
end

For more on relative and global CFrames, see this article.

19 Likes

As @B2ontwitch said, you can use the CFrame.RightVector property. The left vector is then CFrame.RightVector*-1. You can use the Vector3:Dot function to see how parallel the the right/left vector is with the vector between the object.

If you’re wondering how the Dot operation works, here is a visualizer:

Here is a code example:

local cframe --the CFrame of the object
local position --the position we want to check

local rightVector = cframe.RightVector
--local leftVecotr = rightVector*-1 --This code doesn't need this: If the direction is not right then it's left

local directionToPosition = position - cframe.Position

if rightVector:Dot(directionToPosition) > 0 then
	print("right")
else --If the dot product is 0 the position is directly in front, though this will almost never happen
	print("left")
end

Edit:
@njesk12 has a great solution. I didn’t see that they used :ToObjectSpace, which is super clever.

10 Likes