transform.up rotation? (2d game)

This is the top half of the code I have:

public float speed = 20f;
public Rigidbody2D rb;
public float damage = 1;
public GameObject impact;
void Start()
{
    rb.velocity = transform.up * speed;
}

Is there a way I can change the “transform.up” to something that will shoot the bullet diagonally?

Hi!

The diagonal direction in it’s core is the combined vertical and horizontal direction applied at the same time, therefore, for example, 45 degree direction will look like this:

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

However, this movement will be faster than strict vertical or horizontal direction it’s because by combining 2 vectors together their length become more than 1, so you want to normalize the vector in order to keep the speed diagonally same as horizontally:

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

And you can specify how much movement will be up and right, if you want to adjust the angle of movement:

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

Also, keep in mind that transform.up/right/etc. takes into consideration the orientation of gameobject, so if you rotate your object towards it’s movement direction then the next time you will apply the direction it will be different.

You can use Vector2.up/right/etc. if you want to use global consistent directions.


Hope it helps.