0
\$\begingroup\$

I need someone to help me think about how this works so I can implement this behavior in my game. Below is a video from a game that does exactly what I am trying to accomplish. An airplane that only moves forward and automatically flips depending on the angle.

Here is a working sample of what I want to accomplish: https://youtu.be/VchXH0DvB-4

Here is my game in its current state: https://youtu.be/S1kDiF9wA7Y?si=599jcxnK4oA8ofGr&t=20

Currenlty the only code I have for my airplane is the forward translation and the right rotation depending on the vertical input.

void Update()
{
    transform.Translate(Vector3.forward * Time.deltaTime * forwardSpeed, Space.Self);
    transform.Rotate(Vector3.forward, -Input.GetAxis("Vertical") * rotationSpeed * Time.deltaTime, Space.World);
}

Quick explanation. The reason why I currently have the Rotate function rotating in the world space is so it would not interfere with airplane movement as I believe it needs to rotate around its own Z axis to accomplish what I am trying to do.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

I think you are looking for Quaternion.LookRotation(Vector3 direction, Vector3 up). This very useful method allows you to generate a new rotation that represents a tilt up and down, a yaw left and right, but no roll relative to the horizon (as defined by the up vector). So when you pass through the -90° or +90° vertical angle, it will flip the object around by 180° around the roll axis, so it doesn't end up upside-down.

If you don't want that rotation to be immediate but only happen in increments, then Quaternion.RotateTowards(Quaternion currentRotation, Quaternion desiredRotation, float maximumChange) could be what you are looking for. This generates a quaternion that changes the rotation from one to another, but limited by an amount of degrees.

Or in a more complete code snippet:

float turnRate = /* turn rate in degrees per second */
Vector3 direction = /* read input to get the direction you want to fly into */
Quaternion desiredRotation = Quaternion.LookRotation(direction, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, desiredRotation, turnRate * Time.deltaTime);
\$\endgroup\$
2
  • \$\begingroup\$ This is not quite what I am looking for, but this feels like the right direction. Thank you for taking the time to write the answer, and show me a possible direction. \$\endgroup\$
    – Fabio S.
    Commented Feb 25 at 1:52
  • 1
    \$\begingroup\$ @FabioS. How does this differ from what you want? We can tailor answers better to your needs if you explain what those needs are. \$\endgroup\$
    – DMGregory
    Commented Feb 27 at 14:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .