Weapon traversal does not point towards mouse

I wish to achieve the gun pointing towards the mouse pointer by going left/right

It does do what I want if I point down, but does not take into account distance and spreads out if the player looks too far up. (see the right pistol)

Solutions I have tried so far:

  • Using X and/or Z instead of Y
    spreads out when pointing in axis directions, ignores height
  • CFrame.lookat()
    breaks from the local CFrame’s X and Z breaking immersion of holding a gun correctly

Here is the part of the script shown in the video

-- reference variables used in the example
local rightHand = character:FindFirstChild("Right Arm") or  character:FindFirstChild("RightHand")
local rightGrip = rightHand:FindFirstChild("RightGriprWeld_local", .1)

local mousePosition = mouse.Hit.Position
local distance = (Camera.CFrame.Position - mousePosition).magnitude

-- the part I need help with (ran on renderstepped)
local answer = math.asin((Camera.CFrame.Position.Y - mousePosition.Y) / distance)
rightGrip.C0 = CFrame.new(0, -1, 0) * CFrame.Angles(math.rad(-90), answer, math.rad(0))

I know my current code is the incorrect way to solve this.

Any math or CFrame stuff that might solve this is appreciated, I plan to implement it with left grips later.

And if possible, a simplified explanation of how your solution works would help me a lot.

I have played around with the math a bit more and believe I made some progress

local answer =(character.Head.Position.Unit - mousePosition.Unit).Magnitude print(answer)

rightGrip.C0 = rightGrip.C0:Lerp(CFrame.new(0, -1, 0) * CFrame.Angles(math.rad(-90), answer, math.rad(0)), .7)

I need to reverse the effect so that the gun goes straight at far distances, however making answer in -answer makes it face outward instead of inward as shown

I believe I got it about right by subtracting the answer from 1, ill put my solution here in case it helps anybody in the future!

local answer = ((character.Head.Position.Unit + character.Head.CFrame.LookVector) - (mousePosition.Unit + mouse.Hit.LookVector)).Magnitude
rightGrip.C0 = rightGrip.C0:Lerp(CFrame.new(0, -1, 0) * CFrame.Angles(math.rad(-90), (1 - answer) * math.rad(15), math.rad(0)), .9)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.