CFrame lookVector point to target: lookAt()

" CFrame.new( Vector3 pos, Vector3 lookAt )" is apparently deprecated (I don’t know why they would do that with no easy/simple alternative) according to the wiki, and gives the function below as a way to achieve the same effect. However, it seems to be looking away from the target.

Here’s a test place. Click play, switch to server view, and drag around either part (I’ve marked the front surface of the light gray part with a different surface type to show which way it’s facing).

function lookAt(target, eye)
    local forwardVector = (eye - target).Unit
    local upVector = Vector3.new(0, 1, 0)
    -- You have to remember the right hand rule or google search to get this right
    local rightVector = forwardVector:Cross(upVector)
    local upVector2 = rightVector:Cross(forwardVector)
 
    return CFrame.fromMatrix(eye, rightVector, upVector2)
end


while true do
	script.Parent.CFrame = lookAt(workspace.Part2.Position, script.Parent.Position)
	wait()
end
1 Like

I don’t know why but the arguments of the function provided by the developer hub are in reverse: you pass the position you want your cframe to look at first, then where to position it. It’s essentially CFrame.new(lookAt, position)

4 Likes

That moves the eye part to the position of target

Nevermind, you are correct, I just had to switch all instances of eye and target. Thanks.

function lookAt(eye, target)
    local forwardVector = (target - eye).Unit
    local upVector = Vector3.new(0, 1, 0)
    -- You have to remember the right hand rule or google search to get this right
    local rightVector = forwardVector:Cross(upVector)
    local upVector2 = rightVector:Cross(forwardVector)
 
    return CFrame.fromMatrix(eye, rightVector, upVector2)
end


while true do
	script.Parent.CFrame = lookAt(script.Parent.Position, workspace.Part2.Position)
	wait()
end
5 Likes