Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.
Hi! I’m current working on some pet projects and I’m just diving back into coding, with some minor successes - however, I’ve run into a couple stumbling blocks, hence why I’m now posting.
I am working on moving a tank turret and gun towards a target, and I’ve explored a couple options of doing so - again, with minor success. I started by trying to use Linear Interpolation to angle the turret and gun, but I ran into issues with the various welds on the tank.
So instead, I used Motors to connect the gun to the turret, and the turret to the hull - which does work as I would like. However, the issue I ran into was accurately calculating the angles necessary to orient those motors correctly; first starting with some classic trigonometry (which I’ve arrived back to after pursuing other solutions) - at least with the trigonometry, I started with using the math.sin function but quickly realized that it’s not particularly useful for accurately representing the quadrants. Then, I found atan2 and tried to adapt it, but failed.
function MoveTurret(x,y)
local found, message = pcall(function()
Pivots:FindFirstChildWhichIsA("Motor")
end)
if found then
for _,child in pairs(Pivots:GetChildren()) do
if child:IsA("Motor") then
if child.Name == "Gun_Pivot" then
child.DesiredAngle = y
elseif child.Name == "Turret_Pivot" then
child.DesiredAngle = x
end
end
end
else
Pivots.ChildAdded:Connect(function(child)
if child:IsA("Motor") then
if child.Name == "Gun_Pivot" then
child.DesiredAngle = y
elseif child.Name == "Turret_Pivot" then
child.DesiredAngle = x
end
end
end)
end
end
function CalculateAngleFromTarget(target,pivot_x,pivot_y)
local dis_y = -(pivot_y.Position.Y-target.Position.Y)
local dis_xz = (Vector3.new(pivot_y.Position.X,0,pivot_y.Position.Z)-Vector3.new(target.Position.X,0,target.Position.Z)).Magnitude
local ytan2 = math.atan2(dis_y,dis_xz)
local dis_x = (pivot_y.Position.X-target.Position.X)
local dis_z = (pivot_y.Position.Z-target.Position.Z)
local xtan2 = math.atan2(dis_x,dis_z)
local xy = {xtan2,ytan2}
return xy
end
game:GetService("RunService").Heartbeat:Connect(function()
local angle = CalculateAngleFromTarget(script.Parent.Parent.Target,Pivots:FindFirstChild("Turret_Pivot"),Pivots:FindFirstChild("Gun_Pivot"))
local angle1 = angle[1]
local angle2 = angle[2]
MoveTurret(angle1,angle2)
end)
If you have any tips on reconciling this, I would appreciate it - as well as any alternative methods, knowledge about CFrame and/or the various API-integrated math functions. I’m trying to learn as much as possible so any take on this would be appreciated.