Trying to make a the character face the mouse. Mouse.Hit has an annoying offset because of the camera position, so I’m hardcoding this.
The method I’ve chosen is as follows.
Using Camera:WorldToViewportPoint(HumanoidRootPart.Position), I can work out where the HRP appears on screen and convert the Vector3 given into a Vector2 by eliminating the Z axis (the depth).
Create a Vector2 of the mouse’s position.
Get the bearing of the mouse relative to the HRP’s On-Screen position.
Use this bearing and apply it to the HRP.
These last 2 steps are pretty difficult, and I’m still very rusty on my vector math. I’ve got the other steps down, but some guidance would be appreciated.
I’m on my phone presently and can’t test until much later.
the character needs to face the same way as the bearing (which we need to find out)
I should also mention that (obviously) the character should rotate exclusively on the Y axis, so the orientation should look like Vector3.new(0, Y, 0)
I guess the question now is “how do you get the direction between two vectors?”. Tried using (vectorA - vectorB).Unit) but I’m not sure how I translate this into degrees.
Fixed! I bypassed the whole use for unit and did some research into vectors (which, in hindsight, I should’ve done before). I settled on using atan2 (arc-tangent 2 parameters)
Here’s the updated script (inside an RS.RenderStepped loop):
local characterPosition, onScreen = cam:WorldToViewportPoint(hrp.Position)
local characterPositionOnScreen = Vector2.new(characterPosition.X, characterPosition.Y)
local mousePosition = Vector2.new(mouse.X, mouse.Y)
if onScreen and characterPositionOnScreen then
local vectorDiff = characterPositionOnScreen - mousePosition
local angle = math.atan2(vectorDiff.Y, vectorDiff.X) - math.rad(90)
hrp.CFrame = hrp.CFrame:Lerp(CFrame.new(hrp.Position) * CFrame.Angles(0, -angle, 0), 0.15)
end