How Does CFame.lookAt Work?

I was in studio, thinking to myself about raycasting. I visualized it like a part looking at another (origin-destination).unit was the “lookvector” between the two points. CFame-(CFrame*CFrame.new(1,0,0)).Position gave you this as it moves one unit forward based on orientation. But how would you calculate how to make a part face another similarly? CFrame.lookAt and CFrame.new do this, but whats the background code for this? What if I wanted the top face to “lookAt” a part?

While I can’t provide detail on how it fully works, I can say this much:

CFrame.lookAt has a third parameter, which is the up vector. You can make use of this to try and make it so the top face looks at another part.

Another method is to use the lookAt function as normal, then multiply the resultant CFrame by some CFrame angle, such that the correct face appears to look at the second part.

2 Likes

I want to know how it actually works but I will look into up vector. thanks!

lookAt, under the hood

local function lookAt(originPosition : Vector3, toPosition : Vector3)
	local upV: Vector3 = Vector3.yAxis -- (0,1,0)
	local lookV: Vector3 = (toPosition - originPosition).Unit -- direction with magnitude of 1, we subtract the vectors to do this
	local rightV = lookV:Cross(upV).Unit -- right vector, perpendicular to look and up
	-- now we correct the upvector
	upV = rightV:Cross(lookV).Unit
	-- construct it
	return CFrame.fromMatrix(originPosition, rightV, upV)
end
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.