How to create a Knockback vector2 directions script (c#)
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)
What have you tried ? What didn't work ? Where did you run into trouble? Did you already search and look at these answers ?
Is your OnTriggerEnter() firing correctly or should that be fixed first? If so, there's plenty of questions and answers covering that on this site too.
Answer by Firedan1176 · Dec 22, 2015 at 02:14 AM
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!
Thank you for replying back but I'm getting four errors in my console these are:
(18,44): error CS1525: Unexpected symbol `GetComponent'
(10,36): error CS1525: Unexpected symbol ==', expecting
.'
(6,41): error CS1519: Unexpected symbol `;' in class, struct, or interface member declaration
Your answer
Follow this Question
Related Questions
How to get directional words with vector2? 0 Answers
Struggling with bounce pad in platformer game. 1 Answer
Object rotates normaly while moving, then does zig zags? 0 Answers
Lerping at a constant rate? 2 Answers
Bounce between two exact points 1 Answer