Gerard Ramon
Gerard Ramon

Reputation: 67

Unity 2D - Rotate object and limiting the rotation

I'm trying to do a rotating cannon which rotates back and forward. I want to limit the rotation from -55 to 55 (i mean transform.position.z), but i can't make it work.

For the moment my code is:

public class Cannon : MonoBehaviour
{
    bool hit = false;

    void Update ()
    {
        float angle = transform.rotation.z;
        if (angle > -55 & angle < 55 & !hit)
        {
            transform.Rotate(Vector3.back * Time.deltaTime);
        }

        if (angle <= -55)
        {
            transform.Rotate(Vector3.back * Time.deltaTime);
            hit = true;
        }
        if (angle >= 55)
        {
            transform.Rotate(Vector3.forward * Time.deltaTime);
            hit = true;
        }
    }
}

The only think that is working is the first rotation which I've done for the object to start rotating, so it just rotates back and don't stop, it seems to be ignoring "angle"

I've also tried to put the last 2 If statements, inside the first one but still not working.

I want to make it rotate until it hit -55, then start rotating until it hits +55 and repeat this.

Upvotes: 1

Views: 4300

Answers (1)

K Scandrett
K Scandrett

Reputation: 16541

The first thing you need to do is to use Euler Angles rather than Quarternions to find the rotation in degrees.

Then, since it doesn't report negative angles but rather angles from 0 to 360, you will need to subtract 360 whenever greater than 180 to get the negative angle equivalent.

From there you can apply your test to keep it in bounds:

public class Cannon : MonoBehaviour {

    public float direction = 1f; // initial direction
    public float speed = 20f; // speed of rotation

    void Update ()
    {
        float angle = transform.eulerAngles.z;
        if (angle > 180f) angle -= 360f;

        if ((angle < -55f) || (angle > 55f)) direction *= -1f; // reverse direction (toggles between 1 & -1)

        transform.Rotate (0, 0, speed * direction * Time.deltaTime);
    }
}

Upvotes: 1

Related Questions