How can I make my character's head, point towards another player's head?

I’ve been trying to do this for around 30 minutes. This is my code so far, but it’s not working correctly. Sometimes the head points correctly, the other time it points to the opposite side it should be pointing at. Also, it doesn’t point on the Y axis but only on the X axis (basically horizontally only):

local targetHeadCF = lastTarget.Head.CFrame;
local targetHeadLook = targetHeadCF.LookVector;
local ToObjectSpace = CharacterPivot:ToObjectSpace(targetHeadCF).LookVector;
local cfTarget = CFrame.new(0, NeckC0Origin.Y, 0) * CFrame.Angles(0, ToObjectSpace.X, 0) * CFrame.Angles(-ToObjectSpace.Y, 0, 0);
Neck.C0 = Neck.C0:Lerp(cfTarget, 0.1);

Can anyone help me? I’ve been banging my head over this for a while now.

Edit:
Gonna specify:

  • CharacterPivot = My character’s pivot
  • targetHeadCF = The CFrame of the head of the other player (the one my head should point to)
  • NeckC0Origin = The original C0 of my head’s neck
5 Likes

I have developed a function to make world space CFrames, like CFrame.lookAt apply when using Motor6D or welds C0 property. This function should work with all rigs as it takes into account of the C1 as explained and derived through here.

I prefer using world space CFrames as it’s easier to visualize rather than thinking in object space relative to the Part0.

local neckJoint = script.Parent

local target = Workspace.Target

local Head = script.Parent.Parent
local upperTorso = neckJoint.Part0

local function worldCFrameToC0ObjectSpace(motor6DJoint,worldCFrame)
	local part1CF = motor6DJoint.Part1.CFrame
	local c1Store = motor6DJoint.C1
	local c0Store = motor6DJoint.C0
	local relativeToPart1 =c0Store*c1Store:Inverse()*part1CF:Inverse()*worldCFrame*c1Store
	relativeToPart1 -= relativeToPart1.Position
	
	local goalC0CFrame = relativeToPart1+c0Store.Position--New orientation but keep old C0 joint position
	return goalC0CFrame
end


while true do
	task.wait()
	local goalCF = CFrame.lookAt(Head.Position, target.Position, upperTorso.CFrame.UpVector)
	neckJoint.C0 = worldCFrameToC0ObjectSpace(neckJoint,goalCF)
end

Test file:

WeldToWorldSpaceTest.rbxl (44.3 KB)

If you wish to restrict it then that’s another story, but you make the goalCF relative to the torso via ToObjectSpace, Convert to orientation using :ToOrientation, then clamp the angles, then reconstruct using CFrame.fromOrientation. I have done this within my turret module.

22 Likes

Thank you so much! This is great. I’m sure it will help other people too. Thanks again.

2 Likes

Is there a way to add limits to this?

1 Like

You are a life saver; I’ve been trying to figure it out for days now!

1 Like