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).
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.
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);
}
}