- Home /
How to add a force to a Rigidbody2D?
Hello,
I'm working on my first project and I would like to get some help with using the Rigidbody2D.addForce() command.
This is what i have so far and I would like it to add a force to the bullets actually fly out of the gun instead of dropping down instantly. I am sure I am using the addForce method wrong (last line) so could anyone set me straight?
using UnityEngine;
using System.Collections;
public class fireBullets : MonoBehaviour
{
public GameObject projectileType; //the prefab that should be spawned.
void Update ( )
{
if (Input.GetMouseButtonDown(0)) //when left mousebutton is pressed.
{
Fire(); //fire projectile.
}
}
void Fire( )
{
Transform spawn = transform.Find( "Spawn" ); //find the posotion where the projectile should spawn.
GameObject projectile = Instantiate( projectileType, spawn.position, spawn.rotation ) as GameObject; //create projectile.
Vector2 force = new Vector2 (10, 0); //create a force.
projectile.Rigidbody2D.addForce(force, ForceMode2D.Impulse); //add it to the newly created projectile.
}
}
Comment
Best Answer
Answer by meat5000 · May 29, 2014 at 11:13 PM
Use a Capital A in AddForce. You might also need a small r in the call to the rigidbody (only).
Thanks, that seems to fix a few compiler errors! I am used to lowerCamelCase from previous program$$anonymous$$g experiences =/
Here are the errors that still show up:
Assets/Scripts/fireBullets.cs(21,56): error CS0103: The name `Force$$anonymous$$ode2D' does not exist in the current context
Assets/Scripts/fireBullets.cs(21,40): error CS1501: No overload for method `AddForce' takes `2' arguments
Seems like I add the Force$$anonymous$$ode incorrectly.
Your answer
![](https://koobas.hobune.stream/wayback/20220613150218im_/https://answers.unity.com/themes/thub/images/avi.jpg)