I have this topdown game on which I want to create a knockback effect when my player collides with my object. I want to create a knock back script using OnTriggerEnter2D. I want the knock back script to look like this. How Would I do that? (sorry I’m a bit of a noob)
(http://noobtuts.com/content/unity/2d-pong-game/vector2_directions.png)
How are you checking to see where the object is? If the object is in front, you should push the player the other way. One way to do this would be to get the difference of the player’s location and the object’s location. Then, you can get that as a 1 or a -1, and add that as a force. Something like this:
public class BounceBack : MonoBehaviour {
public GameObject theObject; //The object you collide with.
public Vector2 bounceIntensity; //The amount of force applied to the player.
void Start() {
if(theObject == null)
Debug.Log("Object isn't set!");
}
void OnTriggerEnter2D(Collider2D col) {
Vector2 bounceBack = transform.position - theObject.transform.position; //This should just "Chop off" the Z coordinate.
bounceBack = new Vector2((bounceBack.x > 0) ? 1 : -1, (bounceBack.y > 0) ? 1 : -1)
GetComponent<Rigidbody2D>().AddForce(bounceBack * bounceIntensity, ForceMode2D.Impulse);
}
}
Now I haven’t tested this, but it should work. Leave a comment if it doesn’t give you the result you want.
*EDIT: I have replaced object
with theObject
, since object is a predefined word, and cannot be a variable name. Sorry about that!