I am scripting a gun script, I am making it so the gun follows the mouse in first person. I have the basics but it is extremely choppy and I have no idea what the problem is.
local player = game.Players.LocalPlayer wait(.5) OFFSET = Vector3.new(0, 1, 1) local body = player.Character local mouse = player:GetMouse() r = false --Aim Part-- function onmove() body.Torso.Neck.C1 = CFrame.new() body.Torso.Neck.C0 = CFrame.new(0, 1.5, 0) * CFrame.Angles(math.asin((mouse.Hit.p - mouse.Origin.p).unit.y), 0, 0) if body.Torso:FindFirstChild("RightArmWeld") ~= nil then if r == true then a = 0 local dif = body.Head.CFrame:toObjectSpace(script.Parent.Parent.Handle.CFrame).p + OFFSET body.Torso.RightArmWeld.C1 = CFrame.new(dif) end new = (mouse.Hit.p - mouse.Origin.p).unit.y x = -1.3 y = .5 z = .5 body.Torso:FindFirstChild("RightArmWeld").C1 = CFrame.new(x,y,z)*CFrame.Angles(-math.asin((mouse.Hit.p - mouse.Origin.p).unit.y)-1.7,0,0) end end -- function ondown() r = true end function onup() r = false end mouse.Move:connect(onmove) mouse.Button2Down:connect(ondown) mouse.Button2Up:connect(onup)
You should still probably use RenderStepped
, by the way.
Anyway, calculate the attitude, or pitch, of the gun to get what angle it is pointing at compared to a vertical line through the character's head.
If an angle of 90* from the vertical is an offset of 0
, take the proportion of the angle above and below this point compared to the maximum possible angle in that direction (1* less than straight up or down, iirc), and multiply it by the max (or min) offset to get get how much to slide up or down the arm.
The distortion you're seeing is linear, so you only need a linear offset to fix it.