Shooting a bullet in the direction you are facing.

I am making a top-down 2D game, and I have a character which automatically rotates towards the nearest enemy unit and fires. I would like to convert the unit’s rotation into X and Y vectors, which are passed to the bullet object to determine which direction the bullet moves.

The problem is, the bullets either fire only to the right. If I remove the radian transformation, they fire in different directions, but not in a way related to the objects orientation, and only in about 1/3rd of possible directions (which makes me think this is something to do with converting between orientaiton and XY).

The unit’s fire bullet code is:

  // Update is called once per frame
    void Update()
    {
        if (Time.time > next_fire)
        {
            next_fire = Time.time + fire_rate;
            fire();
        }

    }

    void fire()
    {
        bullet_pos = transform.position;
        GameObject new_bullet = Instantiate(projectile, bullet_pos, Quaternion.identity);

        Quaternion direction = transform.rotation;
        var radians = direction.z * Mathf.Deg2Rad;
       
        x = Mathf.Cos(radians);
        y = Mathf.Sin(radians);
       
        new_bullet.GetComponent<bullet_flying>().velX = x;
        new_bullet.GetComponent<bullet_flying>().velY = y;

      
    }

The bullet’s code is:

    public float velocity = 10;
    public float velX = 0f;
    public float velY = 0f;
    Rigidbody2D rb;

    // Start is called before the first frame update
    void Start()
    {
        Destroy(gameObject, 5);
        rb = GetComponent<Rigidbody2D > ();
    }

    // Update is called once per frame
    void Update()
    {
        rb.velocity = new Vector2(velX*velocity, velY*velocity);  
    }

try to use transform.right (if the bullet and player are right faced

 void fire()
    {
        bullet_pos = transform.position;
        GameObject new_bullet = Instantiate(projectile, bullet_pos, Quaternion.identity);
        //rotate the bullet as the gameobject
        new_bullet.transform.right = transform.right.normalized;
    }

in the bullet

rb.velocity = transform.right * velocity;
1 Like

Thanks, but won’t this just move the bullet left or right (but no Y direction)? I want it to be able to move in any direction in X/Y because it’s a top-down game where the unit can face any direction

this is not just left or right. transform.right is the local vector on the gameobject. If the object was rotated with its “right” in the left side, then the local vector transform.right is pointed left in the world.
Just I don’t know how the sprite is painted and where is its “face”. Also you should take the needed local direction (transform.up, - transform.up, transform.right, - transform.right)

Ah right, I see! Yes it worked, thank you!