Line up gun 'sight'

Line up the gun sight. Currently when I move my mouse up or down it gets a wierd kind of rotation offset.
What I want for every rotation:
image
What happens when I aim up/down:
image
(This is all in first person)

I want the sights to line up correctly while also ‘aiming’ at the mouse.
I’ve tried many thing over the last couple of days, Nothing seems to help.

The test place:
test.rbxl (43.4 KB)
(The script is under StarterPlayerScripts)
The code that is inside of the script:

wait(1)
local g = workspace.G
local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local x = {}
local c = plr.Character
mouse.TargetFilter = g
for k,v in pairs(g:GetChildren()) do
   if v.Name ~= "Main" then
      x[k] = {v,v.Position-g.Main.Position}
   end
end
local gToA = -(g.Aim.Position-g.Main.Position)
while wait() do
   local b = CFrame.new(c.Head.Position,mouse.Hit.Position)
   g.Main.CFrame = b*CFrame.Angles(0,math.pi/2,0)*CFrame.new(gToA.x,gToA.y,gToA.z)
   for k,v in pairs(x) do
      v[1].CFrame = workspace.G.Main.CFrame * CFrame.new(v[2].x,v[2].y,v[2].z)
    end
end

The code is a little messy I hope that doesn’t really bother anyone. :grimacing:

Thanks!

3 Likes

Instead of mouse hit try using camera:ScreenPointToRay(mouse.X, mouse.Y, 0.2).Origin

2 Likes

I totally forgot about that function :joy:
I went as far as trying to use math.cos to counter the rotation totally skipping camera functions.

Thank you!