Get direction of part from player

I’m trying to get the direction of a part from the player. So basically it works kind of like the player is the origin and I want to get the direction of the position of that part from this “origin”. I don’t want to use CFrames because I would need to construct a new one every single time I want to know the direction. Note: I’m checking for rotation multiple times per renderstep so it’s very important that it doesn’t perform many calculations.

This is how I currently get the direction but it’s not very efficient in the slightest.
local Direction = CFrame.lookat(PlayerPosition, PartPosition).LookVector

I want to know if there is any way with math to get the same result using just vectors. I’m not sure how much better performance will be if I don’t use CFrames but I still want to try.

There isn’t much a performance usage from this alone. CFrames tend to take up a very minimal amount of data for most usage cases anyways. Optimization would most likely rely on your end based on how you use this CFrame information.

1 Like

I have a slight problem though. I’m using custom tables for my vectors in my script so I would need to convert them into Roblox’s vector3s in order to preform CFrame calculations on them so I’m constructing extra Vector3s just to be able to calculate the direction.

If you just want the pure Vector3 lookVector without constructing CFrames, then you can use this method.

local direction : Vector3 = (position2 - position1).Unit

When using this method however, you must always subtract the second position by the first position, otherwise you’d get the opposite directional value. Hope this helps! :smile:

1 Like

Is position2 the player or the part in your code?

In your case, position2 should be your Part’s position and position1 should be your Player’s position.

I think, it’s where :VectorToWorldSpace() should be used.

while true do
    local vector = HumanoidRootPart.Position
    local pos = vector + HumanoidRootPart.CFrame:VectorToWorldSpace(Vector3.new(4,0,0))

    part.CFrame = CFrame.new(pos, HumanoidRootPart.CFrame.lookVector)

    task.wait()
end
1 Like