- Home /
AddForce with 2D Character
I got a character with a 2D rigidbody, the game is an infinite runner. Traps are coming from the right to the left and the player needs to jump above them. Now, I want that if the player hits a trap he will be knocked back a specific distance (that I can modify).
I got the collision part working fine but how can I make the trap to push back the player? am I suppose to use AddForce here? If you answer please tell me if I need to put rigidbody2D on the traps or anything important in addition to your code.
(this is in C#, 2D mode as I mentioned).
Well if you have the collision part working fine and all you need is to hit the player backwards, then, assu$$anonymous$$g that you want to push the player back on the x axis (-x) rigidbody.AddForce( -10, 0 )... Since you have the collision part working fine, I wouldn't worry about adding a rigid body to your traps
Answer by MileSplit · Feb 11, 2014 at 12:52 AM
Yes you are supposed to use add force. It works almost the same way as it does in 2d but it ignores the z axis. Because of that you need to use a Vector2 instead of a Vector3. Also you would use rigidbody2D.AddForce, instead of the rigidbody.AddForce.
Answer by ordaskal · Feb 11, 2014 at 03:30 PM
It Doesn't work, am I suppose to put the script on my traps or on the 2D character? Right now I got on both and still nothing happens. here is the script on the trap:
void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "Player")
{
rigidbody2D.AddForce(-transform.right * 500);
}
}
and the script on the 2D character:
void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "TrapLevel1")
{
rigidbody2D.AddForce(-transform.right * 500);
}
}
There is no such thing as transform.right
Its Vector3.right or Vector2.right
The second thing that you're doing wrong is if your trap has rogidbody attached it will shoot itself to the direction specified in your code.
ITrap: if(col.tag == "player") col.rigidbody2D.AddForce( -Vector2.right * power);
You shouldn't answer yourself with a comment. When you have more questions, just comment
Your answer
Follow this Question
Related Questions
AddForce vs Velocity issues with Rigidbody2D 2 Answers
Get result (force & torque) of AddForceAtPosition? 2 Answers
Make a player jump tile 1 Answer
2D floating object 2 Answers
rigidbody2D.addforce in collider 1 Answer