Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Gun that rotates with camera?

My game is locked in first person and I'm trying to make my gun "attached" to the player's camera. Tools rotate about the Y axis just fine, however if you look up or down the tool stays in place.

local weld = char["Right Arm"]:WaitForChild("RightGrip")

local Target = cam.CoordinateFrame * CFrame.new(0, 0, -100)

local headpos = (char["Torso"].CFrame * CFrame.new(1,2,0)).p

weld.C1 = ((CFrame.new(headpos, Target.p) - headpos):inverse()) * (char["Torso"].CFrame - char["Torso"].Position)

weld.C0 = cam.CFrame

This is my closest attempt, however the tool is moving on the wrong axes and I cant figure out how to adjust it properly

1 answer

✓ Accepted answer

The following script creates a function that runs before rendering each frame. It then includes making your arms, head, and torso rotate depending on where your cursor is pointing. Let me know if this helps!

-- This is open source code, probably written by Sharksie
local Player = game.Players.LocalPlayer
local Character = Player.Character

if not Character then
	Player.CharacterAdded:wait()
	Character = Player.Character
end

local Torso = Character:WaitForChild'Torso'
local Neck = Torso:WaitForChild("Neck")
local LeftShoulder = Torso:WaitForChild("Left Shoulder")
local RightShoulder = Torso:WaitForChild("Right Shoulder")
local Humanoid = Character:WaitForChild("Humanoid")
Humanoid.AutoRotate = false
local HMR = Character:WaitForChild("HumanoidRootPart")

local Mouse = Player:GetMouse()

local RC0 = CFrame.new(1, .5, 0, 0, 0, 1, 0, 1, 0, -1, 0, 0)
local RC1 = CFrame.new(-.5, .5, 0, 0, 0, 1, 0, 1, 0, -1, 0, 0)

local LC0 = CFrame.new(-1, .5, 0, 0, 0, -1, 0, 1, 0, 1, 0, 0)
local LC1 = CFrame.new(.5, .5, 0, 0, 0, -1, 0, 1, 0, 1, 0, 0)

local NeckC0 = Neck.C0
local NeckC1 = Neck.C1

game:GetService("RunService").RenderStepped:connect(function()
	local cf = workspace.CurrentCamera.CFrame.lookVector.Y
	
	local Kek = CFrame.Angles(0, 0, math.asin(Mouse.Origin.lookVector.Y))
	RightShoulder.C1 = RC1 * Kek:inverse()
	LeftShoulder.C1 = LC1 * Kek
	
	Neck.C0 = NeckC0 * CFrame.Angles(math.asin(Mouse.Origin.lookVector.Y), 0, 0):inverse()
	HMR.CFrame = CFrame.new(HMR.Position, Vector3.new(Mouse.Hit.p.x, HMR.Position.Y, Mouse.Hit.p.z))
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.