Turret Rotation

So I have a turret and it turns when I want it to but I don’t know how to make it stop when it is facing the target. I have the position of the target I just don’t know how to detect when it is facing the target

Here’s the part of the script:

local target = Vector3.new(targ.X, targ.Y, targ.Z)
repeat wait()
	headRoot.CFrame = headRoot.CFrame * CFrame.Angles(0, math.rad(.5), 0)
until --turret is facing target
3 Likes

Since you already have the position, you can use TweenService to tween the CFrame to the target

local TweenService = game:GetService("TweenService")

local target = Vector3.new(targ.X, targ.Y, targ.Z)
local seconds = 4 -- time takes to reach target
local easingStyle = Enum.EasingStyle.Linear -- play around to find what you like

TweenService:Create(headRoot, TweenInfo.new(seconds, easingStyle), {CFrame = CFrame.new(headRoot.Position, target)}):Play()

TweenService | Documentation - Roblox Creator Hub

3 Likes
local targetPosition = Vector3.new(targ.X, targ.Y, targ.Z)
local toleranceAngle = 1

while true do
    wait()
    local directionToTarget = (targetPosition - headRoot.Position).unit
    local turretForward = headRoot.CFrame.LookVector
    local angleToTarget = math.deg(math.acos(turretForward:Dot(directionToTarget)))
    
    if angleToTarget <= toleranceAngle then
        break
    end
    
    headRoot.CFrame = headRoot.CFrame * CFrame.Angles(0, math.rad(.5), 0)
end
2 Likes

Since you already have the target’s position, you can just use raycast. And then add a variable that triggers to stop.

local target = Vector3.new(targ.X, targ.Y, targ.Z)
local isfacingtarget = false

repeat
	headRoot.CFrame = headRoot.CFrame * CFrame.Angles(0, math.rad(.5), 0)
	
	local origin = headRoot.Position
	local direction = (target - origin).Unit * 100 -- if how long do you think the raycast should go
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {script.Parent} -- avoid detecting the current assuming script is inside a model

	local raycastResult = workspace:Raycast(origin, direction, raycastParams)
	isfacingtarget = raycastResult and raycastResult.Instance == modeloftarg -- assuming you have a character model for the target
until isfacingtarget == true

Documentation On WorldRoot:Raycast

1 Like

Thank you so much, just tried this and it worked

Ya figured it would. Just following what you had… Actually like that tween more. GL.

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