NPC pitch wont Aim relative to where its facing

I want to make the NPC always Aim in the pitch rotation(up-down) to where the target is. When the NPC is rotated towards the right direction it works great. Like this:

But when i rotate the NPC 90 degrees, the aim is not rotating towards the pitch relative to where its facing.



I want my NPC to always aim relative to where its aiming the rifle.

here is the code:

local char = script.Parent
local charHumanoid = char.Humanoid
local anim = charHumanoid.Animator:LoadAnimation(script.Parent.M4.Aim)
local waist = char.UpperTorso.Waist
local waC0 = waist.Transform

function equipRifle()
	char.M4.RifleWeld.Part1 = nil
	char.M4.CFrame = char.RightHand.CFrame * CFrame.new(0,-0.6,-0.3) * CFrame.Angles(math.rad(-90),0,0)
	char.M4.RifleWeld.Part1 = char.RightHand

	
	anim:Play()
end

wait(2)
equipRifle()
while task.wait() do
	local target = workspace.target
	if target then
		local x1,y1,z1 = char.HumanoidRootPart.CFrame:ToOrientation()
		local x2,y2,z2 = char.LowerTorso.CFrame:ToOrientation()
		local x3,y3,z3 = char.UpperTorso.CFrame:ToOrientation()
		local direction = (target.Position - char.HumanoidRootPart.Position).unit
		local verticalAngle = math.asin(direction.Y)
		char.UpperTorso.Waist.C0 = waC0 * CFrame.Angles(-x2+x1,-y2+y1,-z2+z1) * CFrame.fromAxisAngle(-char.HumanoidRootPart.CFrame.LookVector,verticalAngle)
	end
	
end
2 Likes

this is my code for aiming a bow up/down, which should be the exact same thing

the rotation up/down is based on the camera angle

local upAngle, _, _ = CameraCFrame:ToOrientation()
			
upAngle = math.clamp(upAngle, -1, 1)
		
local torsoX, torsoY, torsoZ = Torso.CFrame:ToOrientation()
		
if Neck and Waist then
			
	local goalNeckCFrame = Torso.CFrame:Inverse() * HumanoidRootPart.CFrame:ToWorldSpace(CFrame.Angles(upAngle*1.2, 0, 0))

	Neck.C0 = (goalNeckCFrame*NeckOriginC0).Rotation + NeckOriginC0.Position
			
	local rotationWaistCFrame = CFrame.Angles(upAngle, 0, 0)
	local goalWaistCFrame = rotationWaistCFrame*WaistOriginC0
			
	Waist.C0 = Waist.C0:lerp(goalWaistCFrame, 0.5).Rotation + WaistOriginC0.Position
			
	local legsCounterCFrame = CFrame.Angles(-torsoX/1.5, 0, -torsoZ/1.5)

	RHip.C0 =  legsCounterCFrame*RHipOriginC0
	LHip.C0 = legsCounterCFrame*LHipOriginC0
			
end

legs are also rotated because they twist weirdly when rotating waist

and some of the magic numbers like 1.5 and 1.2 arent mathematically precise, i think they just make the rotations look better aesthetically

I fixed it by doing vector3.New(1,0,0) instead of -char.HumanoidRootPart.CFrame.LookVector

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