- Home /
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?
Answer by ADiSiN · Jun 01, 2020 at 11:07 PM
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.
Thank you a lot, it works very well. I'm also glad you included a way to specify how much movement to put in each direction since it probably would've been my next question.
Glad that it worked for you.
Good luck in your project!
Your answer
Follow this Question
Related Questions
How do I stop my sprite from jumping in the air? 1 Answer
Making the enemy follow the path of the Player,How to make the enemy follow the path of the player? 0 Answers
[2D]Tank track animation 0 Answers
In my 2D platformer game, how would I create a height marker?, 1 Answer
How to stop crouching automaticaly after getting out of a small area 0 Answers