How to get a crosshair to line up with the mouse's position

im trying to get a tank’s turret crosshair to line up with the player’s mouse position (which is locked to the centre of the screen) like so:

im using camera:WorldToScreenPoint() to get the crosshair to follow the muzzle of the cannon, but the crosshairs will never line up with the mouse’s position (the black circle). When the tank fires, it fires in the direction the mouse is pointing at, but it can cause confusion since the crosshairs show it would fire in a different spot.

heres the script i have for the crosshair:

local RunService = game:GetService("RunService")

local guiObject = script.Parent.ImageLabel
local part = workspace.Tank.Gun.Gun.Barrel.CameraFocus
local mouse = game.Players.LocalPlayer:GetMouse()
local camera = workspace.CurrentCamera

guiObject.AnchorPoint = Vector2.new(.5, .5)
guiObject.Visible = true
RunService.RenderStepped:Connect(function()
	local worldPos = part.Position
	local x, y, z = mouse.Hit:ToOrientation()
	local pos, isOnScreen = camera:WorldToScreenPoint(part.Position)
	local screenpoint = Vector2.new(pos.X,pos.Y)
	if isOnScreen then
		guiObject.Visible = true
		guiObject.Position = UDim2.new(0,pos.X,0,pos.Y)
	else guiObject.Visible = false
	end
end)

any help would be appreciated! :slight_smile:

You can use mouse.X and mouse.Y to get 2D positional information regarding the mouse and apply that to the crosshair instead.

I’m not 100% sure but I think you can use Mouse.Moved to make it more accurate

the crosshair is supposed to travel with the turret’s position, not the mouse’s position

I would recommend you to use RayCast() instead of part.Position. Find RayCastResult.Position and then put it into WorldToScreenPoint()

I usually just prefer using mouse.Hit.Position but to each their own, however another way you could try is instead using camera:ViewPortToRay() I can’t remember the exact name or syntax for it but that’s the name it’s similiar to. It returns a Unit ray which you can use. You can get the origin, direction, etc.

Oh yeah you can also use a getpropertychangedsignal for the turret’s position. Like trick was kind of saying.