- Home /
How do I add forward velocity to a Rigidbody2D?
I am creating a 2d game and need to make projectiles that shoot towards were you clicked. I was able to make the projectiles spawn in and point at the mouse, but am unable to add forward velocity allowing them to shoot in the right direction. I have tried using the code Rigidbody2D.velocity = Vector2.up * 10;
but this just led to the objects launching strait up instead of forward. I tried using Vector2.forward, but then the object wouldnt move at all. I also tried Rigidbody2D.AddForce(Vector2.up * 500);
but this brought up the same problems.
Answer by MomkeyDev · Jul 31, 2020 at 04:08 AM
Use transform.forward instead. vector3.up use global position so it doesn't care where you're object look at. transform.forward use a local position which basically mean the x,y,z changes on rotation.
Answer by Megamelonman · Aug 28, 2020 at 12:29 AM
This still didn't work. I'm assuming because its in 2d and transform.forward uses vector 3. In case there is something else wrong with my code that I don't know of that is preventing this from working I am putting the section of code that spawns the rocket and the one that is supposed to launch it.
void Shoot()
{
//Create rocket
GameObject rocketDuplicate = Instantiate(rocket) as GameObject;
Vector3 cursorPositon = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rocketDuplicate.transform.position = new Vector2(player.transform.position.x, player.transform.position.y); ;
Vector2 direction = new Vector2(cursorPositon.x - rocketDuplicate.transform.position.x, cursorPositon.y - rocketDuplicate.transform.position.y);
rocketDuplicate.transform.up = direction;
Rigidbody2D rocketForce = rocketDuplicate.GetComponent<Rigidbody2D>();
//Shoot rocket
rocketForce.velocity = transform.forward * 10;
}
just set it to transform.right or transform.up because it's 2D
Your answer
Follow this Question
Related Questions
Character won't move (Fixed) 1 Answer
Rigidbody2D.velocity is not working. 0 Answers
Object jitters when the scene starts 0 Answers
Rigidbody2D.Velocity = Vector2 not changing X Position 1 Answer
slide and dash 2D 0 Answers