Knockback and directions problem
I have this script attached to an object, if my player encounters that object it will be knocked back. I have six directions on which it will be knocked back. This image will show you the different direction of which my player may get knock back. My problem: X=0,Y=1 and X=0,Y=-1 doesn't work, however every other velocity works. How can I also include the directions of X=0,Y=1 and X=0,Y=-1. Thank you and here is my code:
public class Knockback : MonoBehaviour {
public float xForceToAdd;
public float yForceToAdd;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "Player")
{
//Store the vector 2 of the location where the initial hit happened;
Vector2 initialHitPoint = new Vector2 (other.gameObject.transform.position.x, other.gameObject.transform.position.y);
float xForce = 0;
float yForce = 0;
//Grab our collided with objects rigibody
Rigidbody2D rigidForForce = other.gameObject.GetComponent<Rigidbody2D>();
//Determine left right center of X hit
if (initialHitPoint.x > (this.transform.position.x + (this.transform.localScale.x /3)))
{
xForce = 1;
}
else if (initialHitPoint.x < (this.transform.position.x - (this.transform.localScale.x /3)))
{
xForce = -1;
}
else
{
xForce = 0;
}
if (initialHitPoint.y > (this.transform.position.y + (this.transform.localScale.y /3)))
{
yForce = 1;
}
else if (initialHitPoint.y < (this.transform.position.y - (this.transform.localScale.y /3)))
{
yForce = -1;
}
else
{
yForce = 0;
}
rigidForForce.velocity = new Vector2(xForce * xForceToAdd, yForce * yForceToAdd);
}
}
}
(http://noobtuts.com/content/unity/2d-pong-game/vector2_directions.png)
Answer by Soraphis · Dec 16, 2015 at 09:44 PM
In your image you show 8 knockback directions (9 possible in your code) :P
is your y value always zero? does the knockback in (1, 1) or (1, -1) work? is yForceToAdd set to something != 0?
you dont need both "else" cases (32-35, 44-47) because you set yForce and xForce to 0 in 19. and 20. your code seems to be correct, but im pretty sure there is a more elegant way of doing it.
So what should I do? $$anonymous$$y yForceToAdd it set to 100 and so is my xForceToAdd.
Then what should I replace "else" with? because I tried taking it out the "else" statement but it didn't go well like at all. Also could you tell me the more elegant way of doing this?
Your answer