- Home /
Question by
gruffybears · Apr 28, 2014 at 03:20 PM ·
2dphysicsknockback
[Unity 2D] Knockback in a 2D platformer
I'm trying to get my character to be knocked back by attacks from enemies. At the moment I have this:
rigidbody2D.velocity = new Vector2 (0, 0);
GetComponent<MovementScript> ().enabled = false;
Vector3 EnemyDirection = ((transform.position.x - enemy.position.x)>0?rightvec:leftvec) + (Vector3.up);
this.rigidbody2D.velocity = (EnemyDirection * force);
Debug.Log (EnemyDirection);
MyHealth--;
GetComponent<MovementScript> ().enabled = true;
However my character goes straight up rather being knocked into a direction. Any suggestion why this might be?
Any help is much appreciated, thanks. :)
Comment
I doubt that disabling and re-enabling a script within the same function is having the effect you desire. $$anonymous$$ost likely, this script is setting the velocity both horizontal and vertical, but your $$anonymous$$ovementScript is taking over the horizontal without any delay.
Answer by ScriptingPaul · Apr 28, 2014 at 04:25 PM
Dunno if there is some helper class in unity but from maths.
Its actually Javacode but i think you get the idea what to calculate
double radian = Math.toRadians(MathUtil.convertHeadingToDegree(effector.getHeading()));
float x1 = (float) (Math.cos(radian) * meters);
float y1 = (float) (Math.sin(radian) * meters);
// new position
float newX = effected.getX() + x1;
float newY = effected.getX() + y1;
// Update pos with new x,y