How to use math.atan2 to tilt the spaceship properly?

Hello guys, i am developing a space shooter game. by now, im trying to make the spaceship tilt as it turn using math.atan2 in the CFrame.Angles. And I think this is the best way to tilt the spaceship relative to the mouse.X and Mouse.Y positions.

game:GetService("RunService").RenderStepped:Connect(function()
-- HRP is the HumanoidRootPart
char.Ship.Core.BodyGyro.CFrame = CFrame.new(HRP.Position, Direction)* CFrame.Angles(0, 0,math.atan2(HRP.CFrame.X - mouse.Hit.X, HRP.CFrame.Z - mouse.Hit.Z))
--[...]--
end)

It’s actually works, but when i move the mouse below the character it happens:
update

You mean, you want to tilt in real time, rather than just tilt fully straight away?

Well, you already have a loop set up, the only thing you need to really do is lerp the angle.

OR (and this is a big or, because I think both ways are equally good), you can lower the torque on the body gyro. It will cause the gyro to gradually apply it’s CFrame on the spaceship.

Honestly I think the second way is better. Using lerp independently will cause weird behaviour if you try complex motions; the physcis-based method is a lot more fluid and you don’t have to worry about coding a bunch of special cases for a double loop-d-loop and stuff like that.

Hope this helps!

trying to lerp the angle, i found the math.atan2 and maybe it’s the the way next to the soluction… but ins’t working properly :frowning:

That’s not an issue with “below the mouse”. The spaceship is tilting the same way all around, it means that your CFrame is not rotating in the plane. You need to find out whether your spaceship is in line with the orientation of the camera, as well as seeing if the CFrame transformation you are using is correct (i.e., play around with it since I literally can’t do it for you with the code you provided). It should be you doing the debugging anyways, so good luck.

Maybe it is not related but in:

CFrame.new(char.HRP.Position, Vector3.new(Direction.X, char.HRP.Position.Y, Direction.Z))

The direction vector takes its X and Z values from the Direction vector, but the Y value from the char.HRP.Position. Is that what you intended?

Direction is a ray, it turns the spaceship where the mouse is pointing on. Now its more readable.

char.Ship.Core.BodyGyro.CFrame = CFrame.new(char.HRP.Position, Direction)

Doesn’t this change the behiavour? Btw, I’m not sure what you are trying to accomplish with

CFrame.Angles(0, 0,math.atan2(HRP.CFrame.X - mouse.Hit.X, HRP.CFrame.Z - mouse.Hit.Z))

part. You create a rotation matrix using Euler angles. I’m not sure about the Roblox convention, but I think it is roll, pitch and yaw. If so, you are computing the yaw angle from the difference in mouse position and space craft position. But everytime you change the yaw, the coordinate system changes. This means that the yaw axis also changes. Complicated stuff …

1 Like