Addforce function not adding force in a 2D game and cannot figure out why
public class ShootScript : MonoBehaviour
{
public GameObject bulletPrefab;
public Transform bulletSpawn;
public int bulletSpeed = 2000;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
bulletPrefab.GetComponent<Rigidbody2D>().AddForce(transform.right * bulletSpeed);
}
}
Currently the bulletPrefab game object is being spawned but no force is being applied to it and i have no idea why. Any help would be appreciated.
Answer by aditya · Feb 17, 2017 at 05:43 AM
If you've setup your rigidbody correctly then the only problem in your script is that GetButtonDown function only executes for the frame that you starts pressing the button this means you are adding Force for on frame only, so if you want add force continuously then change this function to GetButton but if you want a BLAST of force in that single frame then pass ForceMode2D.Impulse as argument in AddForce method
Answer by Voyder_Rozann · Feb 17, 2017 at 09:27 AM
What is the mass of the bullet ? Because if the bullet mass is too high, the force added will be calculated with the mass ! Put the mass to 0.0001 and the bullet speed to 0.25 !
Here's the fixed version :
public class ShootScript : MonoBehaviour
{
public GameObject bulletPrefab;
public Transform bulletSpawn;
public float bulletSpeed = 0.25f;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
bulletPrefab.GetComponent<Rigidbody2D().AddForce(transform.right * bulletSpeed);
bulletPrefab.GetComponent<Rigidbody2D>().mass = 0.0001f;
}
}
Your answer
Follow this Question
Related Questions
Rigidbody bullet force not being applied 0 Answers
Can I spawn with an array in order? 2 Answers
My instantiate clones won't behave like the original Prefab 0 Answers
Addforce is not working 1 Answer