- Home /
AddForce not working on instantiated bullets
I'm trying to make a 2D shooter, the ship constantly looks at the mouse cursor and should fire with left click.
Right now I have
public GameObject bullet // The prefab
float nextFire;
void Update ()
{
// Movement Code
// Rotation Code
// Shooting
if (Input.GetMouseButton(0) && Time.time > nextFire)
{
nextFire = Time.time + 0.1f;
GameObject bulletInstance = (GameObject)Instantiate(bullet, transform.position, transform.rotation);
bulletInstance.GetComponent<Rigidbody2D>().AddForce(transform.forward * 8000);
}
}
The ship is able to fire bullets, but they don't move. The prefab already has a rigidbody2D and the code compiles smoothly.
Answer by Aetsoft · Nov 07, 2016 at 10:48 AM
here is several issues in youre logic:
1) Transform.forward works fine for 3d objects. You game is 2d. Transform forward point vector through the camera, so you can't see any different, because you gameObject change Z position. Change it to transform.up or transform.right, or whatever, custom Vector2(depending of ship position and rotation).
2) Dont forget, than bulletInstance collider must Ignore ship collider, or bullet just "stuck" in ship.
I hope this help.