Search code examples
unity-game-enginerotationangle

Can't set rotation z right


I have a bullet, you shoot and when you step on a boost, i need other three bullets to spawn going left, right and down each in angle 90 degrees. Player has a firePoint that is just an empty object, that rotates every time the main bullet is shot. That is working perfectly.

Now I just need to set the rotation for the three other bullets -90, +90, -180 from the spawnPoint. This is the important part of my code, counts down the angles, but not from the firePoint. Why might that be?

    var bullet = (GameObject) Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
    rb = bullet.GetComponent<Rigidbody2D>();

    Vector3 mouse = Input.mousePosition;
    mouse.z = 10;
    mousePos = cam.ScreenToWorldPoint(mouse);

    Vector3 slay = rb.position;
    Vector3 lookDir = mousePos - slay;
    float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg;
    rbs.rotation = angle;

    while(Boost == true)
    {
        if(four == 0)
        {
            Quaternion rotation = Quaternion.Euler(firePoint.rotation.x, firePoint.rotation.y, firePoint.rotation.z - 90);
            Instantiate(cloneBulletPrefab, firePoint.position, rotation);
            four++;
            yield return null;
        }
        else if(four == 1)
        {
            Quaternion rotation = Quaternion.Euler(firePoint.rotation.x, firePoint.rotation.y, firePoint.rotation.z + 90);
            Instantiate(cloneBulletPrefab, firePoint.position, rotation);
            four++;
            yield return null;
        }
        else if(four == 2)
        {
            Quaternion rotation = Quaternion.Euler(firePoint.rotation.x, firePoint.rotation.y, firePoint.rotation.z - 180);
            Instantiate(cloneBulletPrefab, firePoint.position, rotation);
            Boost = false;
        }
    }

Solution

  • You should be using firePoint.eulerAngles.x rather than firePoint.rotaton.x. Rotation is a quaternion, and is using a different rotation system than the one in the unity inspector. Rotating along z in a quaternion may not rotate along z in euler angles (inspector transform).

    I quote from unity:

    Unity stores all GameObject rotations internally as Quaternions, because the benefits outweigh the limitations. In the Transform Inspector however, we display the rotation using Euler angles, because this is more easily understood and edited.

    This is a relevant quote because it shows that when you may be used to the z value rotate it along the z axis, that is not the case for quaternions.

    Also, Quaternion.Euler() is meant to be inputting 3 Vector3 values, which is not what you were doing. transform.rotation is a quaternion, meaning the 4th value w was never used.