Hello Fellow Developers,
I am currently in the process of making an robot using constraints. The problem is making the head rotate to face the player. However, I have encountered some issues in construction. Due to the nature of the robot, I am unable to use Vector3.new(Part.Position, Character.HumanoidRootPart.Position)
as this needs to be compatible with constraints.
Some sample code I have tried includes:
Sample 1
-- Uses HingeConstraint, calculating angle to rotate to player from origin using a chord on an imaginary circle
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
RunService.RenderStepped:wait()
local LocalPlayer = Players.LocalPlayer
local character = script.Parent
local part = game.Workspace.Part
RunService.Heartbeat:Connect(function()
local c = (part.Position + part.CFrame.LookVector * Vector3.new(character.HumanoidRootPart.Position*Vector3.new(1, 0, 1).Magnitude, 0, character.HumanoidRootPart.Position*Vector3.new(1, 0, 1).Magnitude) - character.HumanoidRootPart.Position*Vector3.new(1, 0, 1)).Magnitude
local r = (part.Position*Vector3.new(1, 0, 1) - character.HumanoidRootPart.Position*Vector3.new(1, 0, 1)).Magnitude
part.HingeConstraint.TargetAngle = 2 * math.deg(math.asin(c/(2*r)))
end)
Sample 2
-- Uses an SSS triangle calculated within an imaginary circle and uses The Law of Consines to find the angle of rotation
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
RunService.RenderStepped:wait()
local LocalPlayer = Players.LocalPlayer
local character = script.Parent
local part = game.Workspace.Part
RunService.Heartbeat:Connect(function()
local a = (part.Position*Vector3.new(1, 0, 1) - character.HumanoidRootPart.Position*Vector3.new(1, 0, 1)).Magnitude
local b = (part.Position*Vector3.new(1, 0, 1) - character.HumanoidRootPart.Position*Vector3.new(1, 0, 1)).Magnitude
local c = (part.Position + part.CFrame.LookVector * Vector3.new(character.HumanoidRootPart.Position*Vector3.new(1, 0, 1).Magnitude, 0, character.HumanoidRootPart.Position*Vector3.new(1, 0, 1).Magnitude) - character.HumanoidRootPart.Position*Vector3.new(1, 0, 1)).Magnitude
local ta = math.deg(math.acos(((a^2)+(b^2)-(c^2))/(2*a*b)))
part.HingeConstraint.TargetAngle = ta
end)
Occasionally during debugging the HingeConstrant.TargetAngle
will be set to -nan(ind)
, probably due to the player being (directly?) behind the part, therefore causing an āimpossibleā triangle (some speculation here, forgive me for my lack of knowledge). Not to mention you would also have to calculate the direction in which to rotate the constraint.
Any help on this would be appreciated. Maybe the amount of effort being put into this isnāt worth it and maybe I should just make it CFrame optimized.
Thanks in advance.