Shooting from the front of your sprite

I am making a simple top down shooter and am having trouble with shooting bullets. The bullets are firing but I can’t seem to figure out how to change where the bullets originate based on the rotation of my player. My rotation and bullet firing code is as follows:

void Update()
    {

        var mouse = Input.mousePosition;
        var screenPoint = Camera.main.WorldToScreenPoint(transform.localPosition);
        var offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);
        var angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, 0, angle);
        -
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 target = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
            Vector2 myPos = new Vector2(transform.position.x, transform.position.y);
            Vector2 direction = target - myPos;
            direction.Normalize();
            Quaternion rotation = Quaternion.Euler(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);
            GetComponent<Rigidbody2D>();
            GameObject projectile = (GameObject)Instantiate(bullet, myPos, rotation);
            projectile.GetComponent<Rigidbody2D>().velocity = direction * speed;
        }
}

I would do it like this (note the new variable distanceToStart which is how far from the player the bullet should originate):

    void FireUpdate()
    {
        var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        var dir = (mousePos - transform.position).normalized;
        // .right is providing you graphics points in that direction when
        // not rotated. Depending on what is 0 degrees you might want to use
        // either of these
        // transform.right = -dir;
        // transform.up = dir;
        // transform.up = -dir;
        transform.right = dir;
       
        if (Input.GetMouseButtonDown(0))
        {
            var myPos = transform.position + dir * distanceToStart;

            GameObject projectile = (GameObject)Instantiate(bullet, myPos, Quaternion.identity);

            // See above
            projectile.transform.right = dir;
            projectile.GetComponent<Rigidbody2D>().velocity = dir * speed;
        }
    }
1 Like