Make part face Vector2

I want to achieve a simple mechanic to make my tank’s cannon face toward a certain Vector2 point on screen. I’ve tried this:

cannon.CFrame = CFrame.new(Center) * CFrame.fromEulerAnglesXYZ(90, 0, 0) * CFrame.fromAxisAngle(Vector3.FromNormalId(Enum.NormalId.Top), Angle) * CFrame.new(0, -cannon.Size.Y/2, 0) * CFrame.new(0, 0, 1)

and it works for the most part, although when looking closer at the part, you can see it’s not correctly aligned.

Video (notice how when I rotate it the angle of the cannon it kinda rotates to the right) I only want there to be vertical rotations..

Here’s what I tried

Full code:
	local Camera = workspace.CurrentCamera
	local Center = workspace.Bot.Model.Pointer.Attachment.WorldPosition
	
	local CenterPos = ConvertToVec2(Camera:WorldToScreenPoint(Center))
	local Position = Vector3.new(mouse.Y - frameCenter.Y, mouse.X - frameCenter.X)

	local Difference = Position - CenterPos
	local Angle = math.atan(Difference.X/Difference.Y)
	
	if Position.Y > CenterPos.Y then
		Angle = Angle + math.rad(270)
	else
		Angle = Angle + math.rad(90)
	end
	
	local cannon = local_tank.Model.Cannon
	cannon.CFrame = CFrame.new(Center) * CFrame.fromEulerAnglesXYZ(90, 0, 0) * CFrame.fromAxisAngle(Vector3.FromNormalId(Enum.NormalId.Top), Angle) * CFrame.new(0, -cannon.Size.Y/2, 0) * CFrame.new(0, 0, 1)

Any help is appreciated! :slight_smile:

Have you tried using ScreenPointToRay? It should allow you to fire that ray and get a point within the world that you can point the cannon at.

2 Likes

I’ve tried this for about an hour and couldn’t find a working solution using ScreenPointToRay. It gives me the same effect as I had previously.