Search code examples
unity-game-enginebullet

Unity, Diagonal Bullets


I'm currently creating a game in unity 2D with different powerups, one will allow you to have a spread shot, but I'm currently stumped being the scrub I am. I'm having trouble making it travel diagonally. My code is as follows.

public Rigidbody2D rb;
public float speed = 20f;
public float speed2 = 20f;

void Update()
{
    rb.velocity = transform.up * speed;
    rb.velocity = transform.right * speed2;
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Alien"))
    {
        Destroy(gameObject);
    }
}

Before you say anything, I know that the main problem is giving value to rb.velocity twice, and I've tried many work arounds but nothing works. I'd like to keep the current simple style of coding that I have at the moment, but I will change it if necassary. Thanks in advance.


Solution

  • You're right that the issue is that you're setting setting velocity twice, so the second assignment is simply overwriting the first.

    To fix this, simply add the two vectors together before you assign to velocity:

    rb.velocity = (transform.up * speed) + (transform.right * speed2);
    

    or since you're using the same value for speed, you can simply add the two vectors prior to scaling it:

    rb.velocity = (transform.up + transform.right) * speed;