How would I move an AI-controlled turret so it faces its target?

I have some vehicles with turrets in my game that I want AI to be able to use. I know how to make them fire it and move it, but I don’t know how I’d make them move the turret to the correct position so that they shoot at their target accurately. I should add that the turrets move around via HingeConstraints.

(In the image above for example, I’d need to position the turret left and downwards slightly)

I did try subtracting the vector3’s of the target and the gun, but that system didn’t work very well (from how I implemented it at least)

This is the part of the code where I got the difference and tried to change the TargetAngles of the hinges based off it:

local difference =  target.Position - script.Parent.Parent.Turret.GunHandle.Position
if difference.Y < -0.5 then
	MoveGun("decreaseY")
elseif difference.Y > 0.5 then
	MoveGun("increaseY")
end

if difference.Z  > -0.5 then
	MoveGun("decreaseZ")
elseif difference.Z < 0.5 then
	MoveGun("increaseZ")
end 

This kind of worked - the turret moved to where the target was at first, but the position of the gun isn’t updated when it moves around via the hinges (this was in a loop so I expected it to), so it’d just turn all the way up/ down and left/ right and didn’t stop where the target actually was.

In case anyone wants this also, here is the code for the MoveGun function:

function MoveGun(info)
	if target then
		if info == "decreaseY" then
			script.Parent.Parent.FrontRotate.HingeConstraint.TargetAngle += 2
		elseif info == "increaseY" then
			script.Parent.Parent.FrontRotate.HingeConstraint.TargetAngle -= 2
		elseif info == "increaseZ" then
			script.Parent.Parent.Parent.Hull.BottomAnchor.HingeConstraint.TargetAngle += 2
		elseif info == "decreaseZ" then
			script.Parent.Parent.Parent.Hull.BottomAnchor.HingeConstraint.TargetAngle -= 2
		end
	end
end

When doing this sort of fine adjustment in the past I have found that printing out the value of the adjustment helped me to complete the fine tuning.

1 Like