3
\$\begingroup\$

In my top down 2D game, there is a plane as shown below:

enter image description here

The plane shoots bullets forward. For firing bullets, I use:

obj.GetComponent<Rigidbody2D>().AddForce(transform.up*500);

However, when player presses up arrow or A key, plane speed increases. At this point, bullets are slower than the plane and appear to move backwards when plane moves at maximum speed.

How do I take into account player speed so that force applied takes into account player speed?

\$\endgroup\$
2
\$\begingroup\$

There are lacking of code, however I would suggest that the bullet obj is a result of the method Instantiate. If it so, you should just inherit velocity of the plane right after instantiation and before adding force.

GameObject obj = Instantiate(bulletPrefab, plane.tranform.position, plane.transform.rotation) as GameObject;
Rigidbody2D rb2d = obj.GetComponent<Rigidbody2D>();
rb2d.velocity = plane.GetComponent<Rigidbody2D>().velocity;  // set bullet's velocity equal to 'source' velocity
rb2d.AddForce(transform.up * 500);  // and then add force

Also, you can play around with ForceMode2D and optionally try Rigidbody2D.AddRelativeForce to get desired/unusual effects.

\$\endgroup\$
  • \$\begingroup\$ Inheriting parent velocity was the key \$\endgroup\$ – SanSolo Oct 15 '15 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.