AddForce rigidbody 2d not moving object
I wanted to shoot a projectile from Shooter transform's position, but AddForce is not moving the object at all. The rigidbody 2d on the projectile is set to dynamic, simulated is on and mass is very low. I am not able to find the problem.
Here is the code:
public Vector2 forceVector;
public GameObject projectile;
public Transform Shooter;
public float thrust = 10;
private void ShootProjectile(Vector2 forceVector) {
Instantiate(projectile,Shooter.position,Quaternion.Euler(0,0,0));
projectile.gameObject.GetComponent<Rigidbody2D>().AddForce(forceVector*thrust,ForceMode2D.Impulse);
}
void Update() {
if (Input.GetKeyDown(KeyCode.H)) {
ShootProjectile(forceVector));
}
}
Answer by tadadosi · Jun 11, 2020 at 01:39 PM
You are trying to AddForce to your project prefab
and not to your instantiated prefab
, what you should be doing to make this work is this:
private void ShootProjectile(Vector2 forceVector)
{
// Instantiante and store it as temporal Rigidbody2D
Rigidbody2D projectileRbody = Instantiate(projectile, Shooter.position, Quaternion.Euler(0, 0, 0)).GetComponent<Rigidbody2D>();
// AddForce to the stored Rigidbody2D
projectileRbody.AddForce(forceVector * thrust, ForceMode2D.Impulse);
}
This method works, but it's not a good way to handle this. What you could be doing is controlling the projectile with its own class and simply calling a method that could be called Launch() that adds a Force internally (that way you can have all sort of projectile with different thurst and your Shoot class simply Launch them.
Answer by Raviish123 · Jun 11, 2020 at 01:57 PM
@tadadosi Thank you so much, this fixed my problem!
Np! Glad I could help!
Tip: You can add comments to the answers, just click Add comment
on the bottom of an answer and the editor appears. No need to post an answer as a comment ;-)
Your answer
Follow this Question
Related Questions
Why doesn't my knockback function apply force to it's target? 1 Answer
RigidBody2D velocity randomly drops to zero 1 Answer
How do I make a 2D player controlled ball roll when moving? 1 Answer
How do I keep enemies (rigidbodies) from pushing each other? 1 Answer
2D Top-Down Character: How to make my character move using physics? 1 Answer