- Home /
Trying to move an instantiated object with a Rigidbody2D and AddForce
I am setting up a gameobject that uses a coroutine to endlessly spawn bullets, and I want to make it so that when I rotate the gameobject it also changes the direction the bullets are spawning and moving at. Currently, the projectiles do not move at all.
The first if statement is determined by a public bool laser, which I have toggled in the editor for specific prefabs. I have declared _bullet and _laser as GameObjects and serialized them so I can plug them in the editor. I have also declared a public RigidBody rb but haven't assigned anything to it in the editor. The Rigidbodies are kinematic.
IEnumerator Shoot()
{
while (true)
{
yield return new WaitForSeconds(1);
if (laser == false)
{
Instantiate(_bullet, transform.position + new Vector3(0, 0, 0), Quaternion.identity);
rb = _bullet.GetComponent<Rigidbody2D>();
rb.AddForce(new Vector2(10, 0));
}
else if (laser == true)
{
Instantiate(_laser, transform.position + new Vector3(0, 0, 0), Quaternion.identity);
rb = _laser.GetComponent<Rigidbody2D>();
rb.AddForce(new Vector2(10, 0));
}
}
}
Answer by pako · Dec 15, 2017 at 07:37 PM
Rigidbody rb;
GameObject go;
IEnumerator Shoot()
{
while (true)
{
yield return new WaitForSeconds(1);
if (laser == false)
{
go = Instantiate(_bullet, transform.position + new Vector3(0, 0, 0), Quaternion.identity) as GameObject; //you must get a reference to the newly instantiated GameObject
rb = go.GetComponent<Rigidbody2D>(); //then, get a reference to the Rigidbody of the newly instantiated GameObject (not the one on the prefab)
rb.AddForce(new Vector2(10, 0));
}
else if (laser == true)
{
go = Instantiate(_laser, transform.position + new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
rb = go.GetComponent<Rigidbody2D>();
rb.AddForce(new Vector2(10, 0));
}
}
}
EDIT: Your Rigidbodies must not be kinematic if you want to move them using the Physics Engine, e.g. with AddForce().
Thank you very much for clearing that up! I also had to change Quaternion.identity to transform.rotation. The turrets work as intended!
I'm glad it now works for you. Could you please mark my answer as "accepted"? (Click on the green "check mark" ).