- Home /
AddForce not pushing back my RigidBody2D
I am trying to add force in the opposite direction of my colliding object (in this case the player). I've scrolled through a dozen of answers but they seem to give me no results. AddForce simply refuses to move the object. (2D space)
This is how I move my enemy which I want to push back on collision. To clarify the object is Dynamic, Mass is 1 and gravity scale is 0:
public void Movement_Follow(GameObject player, float Speed)
{
Vector3 playerPosition = player.transform.position;
transform.position = Vector3.MoveTowards(transform.position, playerPosition, Speed);
}
However, even with the moving commented out and simply spawning them at a certain position and then running into them still gives me nothing.
And this is how I try to push it back when it bumps in the player (opposite direction):
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Player")
{
health.Damage(5);
float force = 50;
//rb is the components RigidBody2D initialized in Start()
rb.AddForce(-collision.gameObject.GetComponent<Rigidbody2D>().velocity.normalized * force, ForceMode2D.Impulse);
}
}
I considered that maybe I don't have enough force applied, but even values of 500 000 produce no effect. Different methods of adding force also give me no results.
Answer by MelvMay · Mar 10, 2017 at 03:19 PM
You added a Rigidbody2D because you want it to update the Transform position and rotation. This is what it does. You then proceed to directly modify the Transform position yourself overwriting what the Rigidbody2D is doing.
Do not modify the Transform if you're using a Rigidbody2D.
If you want to move the body or change its rotation using Rigidbody2D.MovePosition or Rigidbody2D.MoveRotation. These move the Rigidbody2D to the specified position/rotation during the next fixed-update. If you set your Rigidbody2D to use interpolation then the Transform will be updated per-frame giving you smooth movement as well.
That solved some other issues I had on the movement, but still, the object does not react when AddForce is applied to it. Not even a slight bump backwards. This is how the movement looks like now:
velocity = (player.transform.position - transform.position).normalized;
public void $$anonymous$$ovement_Follow(Rigidbody2D body, Vector2 velocity, float speed)
{
body.$$anonymous$$ovePosition(body.position + velocity * speed * Time.fixedDeltaTime);
}
The collision is still the same.
Your answer
Follow this Question
Related Questions
Add force once when object is created 1 Answer
Rigidbody2D.AddForce fails to add force 0 Answers
Jump problem 1 Answer
Unity 2D Physics .AddForce 1 Answer