I am trying to get the test gun’s barrel/aim to line up with the player’s mouse. Currently, it is slightly off, and I do not know what the proper math to use is in order to line it up 100%.
I apologize if I missed a similar topic previously posted, I have looked through a bunch already and have now found the exact answer I am looking for. Not sure what words to use exactly to search.
Here is what I have so far and what it looks like in-game:
Not sure how else to explain it other than depending on the distance the mouse is from the humanoid root part, the shot bullets don’t 100% line up with the mouse.
The script so far:
mouse.Move:Connect(function()
local mouseHit = mouse.Hit;
local cframe = CFrame.new(mouseHit.LookVector.X, 0, mouseHit.LookVector.Z);
hrp.CFrame = CFrame.new(hrp.CFrame.Position, hrp.CFrame.Position + cframe.Position)
end)
Because the HumanoidRootPart is facing the mouse, but the gun itself is slightly yawed to the left relative to the HumanoidRootPart. In other words, the gun itself isn’t parallel with the player.
Simplest way to fix this is to not shoot the bullet from the actual gun model, but rather from the HumanoidRootPart. This is a technique used by many FPS games where you shoot from your eyes instead of the actual gun.
More complicated way to fix this is to also animate the arm to be facing the mouse. To do this, you have to get the inverse CFrame to be applied to the Motor6D.Transform.
rus.RenderStepped:Connect(function()
local cam = workspace.CurrentCamera
local mPos = uis:GetMouseLocation()
local mRay = cam:ViewportPointToRay(mPos.X, mPos.Y)
local rcr: RaycastResult? = workspace:Raycast(mRay.Origin, mRay.Direction*1e3)
local mPosWorld: Vector3 = if rcr then rcr.Position else mRay.Origin+mRay.Direction*1e3
local turretRel: CFrame = base.CFrame.Rotation:Inverse() * CFrame.lookAt(turret.Position, mPosWorld).Rotation
local _, turretYaw: number = turretRel:ToOrientation()
turretServo.TargetAngle = math.deg(turretYaw)
--you want to focus on this part below:
--in your use case, turret would be the player's torso, and gun is the player's arm
local gunRel: CFrame = turret.CFrame.Rotation:Inverse() * CFrame.lookAt(gun.Position, mPosWorld).Rotation
gunMotor6D.Transform = gunRel
end)