Hello, I am making a tank system for a game I am working on. Currently, I am trying to figure out how to make the tank turret follow the mouse. I was able to make it follow the mouse horizontally with the help of my brother and some weird trigonometry stuff, but neither I or him could figure out how to make it work vertically. I am using servos for both horizontal and vertical movement.
Calculation code:
local function doHorizontalMathForRotate(MousePos,Base)
local baseToTargetVector = Base.Position - MousePos
local xAngle = math.deg(math.atan2(baseToTargetVector.Z,baseToTargetVector.X))-90 + Base.Orientation.Y
return xAngle
end
local function doVerticalMathForRotate(MousePos,Base)
--local object_horizontal_offset = Base.CFrame:PointToObjectSpace(MousePos)
--local object_yaw_angle = math.atan2(-object_horizontal_offset.X, -object_horizontal_offset.Z)
--local yaw_force = yaw_controller(0, object_yaw_angle)
--local distance = math.sqrt((Base.Position.X-MousePos.X)^2+(Base.Position.Z-MousePos.Z)^2)
--local yAngle=math.deg(math.tan(Base.Position.Y+MousePos.Y/distance))-2
--print(yaw_force)
return 0
end
-The commented code was taken from a different developer forum post, which ended up not working as expected.
-The variable named “Base” refers to the bottom part of the tank.
-The variable named “MousePos” refers to mouse.hit.p
-This script is ran on the server, and the math calculation functions are called every 20th of a second. I know this is not the best for performance, but I currently have it set up this way because I am trying to fix a different unrelated bug.
I do not know any trig, as I am taking geometry this year, so please try to simplify things for me as much as possible.
The path to the tube of the turret is tank.TankTube, and the path to the part above the base is tank.TankTop