I just wanted to know how to make a Part face a Player's Torso. And can you explain how it works too?
Thanks in advance!
I just wanted to know how to make a Part face a Player's Torso. And can you explain how it works too?
Thanks in advance!
Hey MBbraveDragon,
part.CFrame = CFrame.new(position, lookAt);
###As you can see from above, you give the CFrame 2 Vector3s. One is the Part's position, which in this case is going to be the Part's own position because, we're not moving the part. The other is, the position it will be looking at, in this case it'd be our torso. I'll show you an example of this below...
-- Torso and Part defined above as 'torso' and 'part'.
part.CFrame = CFrame.new(part.Position, torso.Position);
###Now that's about the simplest way to do it. However, people usually don't want to affect the y coordinate of the part because, they want to keep the part grounded. I'll show you below how you can do this.
-- Torso and Part defined above as 'torso' and 'part'.
part.CFrame = CFrame.new(part.Position, Vector3.new(torso.Position.X, part.Position.Y, torso.Position.Z));
##Well, that's how you can simply do it and I hope I helped and have a wonderful day/night.
~~ KingLoneCat
The most common way in Roblox is to use a CFrame since it can calculate the rotation for us though there is nothing stopping you from creating your own function to calculate the angles with trigonometry.
It is important to look at the constructors for a Roblox data constructor as you should use the correct one depending upon your needs. In your case we would use CFrame.new(Vector3 pos, Vector3 lookAt) desc:- "Creates a CFrame positioned at pos looking at the lookAt position." the most important part is the "lookAt" position as this Vector3 is what will be used internally to calculate the rotation to look at that given Vector3 point.
Side note:- CFrame rotation is in radians not in degrees
A simple example:-
-- setup the part
local part = Instance.new('Part')
part.CFrame = CFrame.new(0, 5, 0)
part.Anchored = true
part.Parent = workspace
local partPosition = part.CFrame.p -- the vector 3 position as it will not change
local torso
game.Players.PlayerAdded:Connect(function(plr)
plr.CharacterAdded:Connect(function(charModel)
torso = charModel:WaitForChild('Torso') -- store the torso in a variable
end)
end)
-- a small loop
while true do
wait()
if torso then -- if we have a torso ie not nil
-- usin the constructor CFrame.new(position, lookAt)
part.CFrame = CFrame.new(partPosition, torso.Position)
end
end
I hope this helps, please comment if you do not understand how / why this code works.
This discussion is preserved as it was. New answers, comments, and votes are closed.