0
\$\begingroup\$

Gun upside down aiming to the left Gun right side up aiming to the right

When the player turns to the left, the texture of the weapon turns upside down. How can I solve this?

Shooting Script

public class Weapon : MonoBehaviour
{
    [SerializeField] private float _offset;
    [SerializeField] private GameObject _prefabBullet;
    [SerializeField] private Transform _shootPoint;
    [SerializeField] private PlayerMove _playerMove;


    public void Shoot()
    {
        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float rotateZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotateZ);
        Instantiate(_prefabBullet, _shootPoint.position, _shootPoint.rotation);
    }
}

Movement script (only method here)

private void Flip()
{
    // Switch the way the player is labelled as facing.
    m_FacingRight = !m_FacingRight;

    // Multiply the player's x local scale by -1.
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
    //transform.Rotate (0f, 180f, 0f);
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Does this answer your question? How do I get my fish to face the right way? (Check at the bottom of the answer where it shows how to conditionally flip a sprite when facing left) \$\endgroup\$
    – DMGregory
    Commented Oct 25, 2023 at 12:28

1 Answer 1

0
\$\begingroup\$

You may want to try doing the calculation in the parent's coordinate space instead, so it correctly flips when the parent does.

public void Shoot()
{
    // Get offset from gun to target, expressed in parent coordinate space.
    Vector3 worldTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector3 localTarget = transform.parent.InverseTransformPoint(worldTarget);
    Vector3 localDifference = localTarget - transform.localPosition;

    // Take the perpendicular to this vector.
    Vector3 perp = new Vector3(localDifference.x, -localDifference.y, 0);
    
    // Aim the sprite so its up vector points at that perpendicular
    // (so its right vector points toward the target).
    transform.localRotation = Quaternion.LookRotation(Vector3.forward, perp);

    // Spawn bullet.
    Instantiate(_prefabBullet, _shootPoint.position, _shootPoint.rotation);
}

I've also shown a trick to avoid doing the trigonometry manually. If the gun's "right" vector is meant to aim in the direction localDifference, then its "up" vector will point toward the perpendicular direction perp. We can construct a quaternion that points the up vector that way while keeping the forward vector pointing into the screen (so the sprite faces the camera), and assign that to the localRotation property without having to do any angle math or radian/degree conversions ourselves.

\$\endgroup\$

You must log in to answer this question.

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