as you can see from this great demonstration. if the mouse is above it then it will point upwards,
If its to the side then it will take the top of it and point it in that direction.
In this image you can see if the mouse is farther back it still is not pointing towards it rather just pointing up in the direction of it
local plr = game.Players.LocalPlayer
local part = workspace.Part
local mouse = plr:GetMouse()
local RS = game:GetService("RunService")
RS.Heartbeat:Connect(function()
part.CFrame = CFrame.lookAt(part.Position, mouse.Hit.Position)
end)
To get a part to point directly upwards towards the mouse in 3D space, you can use the LookAt method available on instances of CFrame. Here’s an example script that shows how to use this method to rotate a part towards the mouse while keeping the part oriented vertically:
local part = workspace.Part -- Replace "Part" with the name of your part
local maxDistance = 100 -- Maximum distance from the part that the mouse can be to rotate the part
-- Function to get the world position of the mouse
local function getMousePos()
local mouse = game:GetService("Players").LocalPlayer:GetMouse()
return mouse.UnitRay.Origin + mouse.UnitRay.Direction * (workspace.Camera.CFrame.p - mouse.UnitRay.Origin).Magnitude
end
-- Loop to rotate the part towards the mouse while keeping it upright
while true do
task.wait()
local mousePos = getMousePos()
local distance = (mousePos - part.Position).Magnitude
if distance < maxDistance then -- Only rotate if the mouse is within the maximum distance from the part
local lookVector = (mousePos - part.Position).Unit
local upVector = Vector3.new(0, 1, 0) -- Define the up direction for the part
local rightVector = upVector:Cross(lookVector).Unit -- Calculate a vector perpendicular to both the look and up vectors
local newUpVector = lookVector:Cross(rightVector).Unit -- Calculate a new up vector perpendicular to both the look and right vectors
part.CFrame = CFrame.new(part.Position, mousePos) -- Set the part's position to be at its current position, looking at the mouse position
part.CFrame = part.CFrame - part.CFrame.UpVector * (part.Size.Y/2) -- Adjust the part's position to put its bottom surface at its original position
part.CFrame = part.CFrame * CFrame.fromMatrix(Vector3.new(), rightVector, newUpVector) -- Rotate the part to align its up direction with the new up vector
end
end