So, I have this module script which is called by another to script to shoot at an enemy tank. It gets the angle to rotate to to point at the enemy tank and then sets the weld of the turret to that rotation so as to point at the enemy. The problem is its rotation is relative to the part it is welded to. I tried to fix this by subtracting the rotation of the tank, from the rotation which is used to point towards the other tank, but it doesn't seem to work.
local Move = {} local Tank = script.Parent.Parent local TurretPart = Tank.Turret local Stats = Tank.Stats function Move:Shoot(target) TurretPart.Shoot:Play() spawn(function() local Particle = Tank.TurretAttachments.Muzzle.Shoot Particle.Enabled = true wait(.2) Particle.Enabled = false end) print(target.Engine.Position) local Difference = Tank.Engine.Position - target.Engine.Position local look = Tank.Engine.CFrame.lookVector local EngineRot = math.atan(look.x,look.z) local rot = math.atan(Difference.x,Difference.z) print(math.deg(rot)) TurretPart.Weld.C0 = CFrame.new(0,.2,.2) TurretPart.Weld.C1 = CFrame.new(0,0,0) * CFrame.Angles(0,rot - EngineRot,0) end return Move
Also the rotation is only about the about the y axis. And the area where the rotation stuff happens is between line 15 and line 22
To understand this problem you have to understand how welds work. The wiki is probably the best place to learn that, but here's the jist of what you need to know.
Welds satisfy the following constraint:
weld.Part0.CFrame * weld.C0 == weld.Part1.CFrame * weld.C1
weld.Part0.CFrame
and weld.Part1.CFrame
are world space representations of the CFrame of the two parts connected in the weld. This simply means the single CFrame you would use to position the parts if you weren't using welds at all.
You can rearrange this equality to solve for the C0
or the C1
that will satisfy the constraint:
-- C0 weld.C0 == weld.Part0.CFrame:inverse() * weld.Part1.CFrame * weld.C1 -- C1 weld.C1 == weld.Part1.CFrame:inverse() * weld.Part0.CFrame * weld.C0
Hopefully that helps you figure out the rest.
Good luck!