Currently, I’ve gotten the player the ability to damage an enemy, and what I want to do next is to give some attacks knockback. I’m wanting the angle in which the enemy is pushed back to be the same as the angle between the player and the enemy.
So, for example, if the enemy is above the player and knockback is applied, the enemy would be pushed upwards, since there’d be about a 180 degree angle between it and the player. Or if the enemy was straight ahead of the player and it was applied, then the enemy would be pushed at a zero-degree angle. Stuff like that.
What sort of crazy stuff could I use to achieve this?
(Also, do note that the enemy in question has a rigidbody attached, but it won’t let me set it as non-kinematic for whatever reason)
Get the positions of the player and of the enemy. Subtract those two and use the resulting vector as the direction vector for the velocity. No angle calculations required.
EDIT:
Kinda tricky with the conditions that you set, but here’s a workaround to not being able to use a non-kinematic rigidbody:
var fDistOfKnockback : float = 2;
var dirVector : Vector3 = (enemy.transform.position - transform.position).normalized * fDistOfKnockback;
var newEnemyPos : Vector3 = enemy.transform.position + dirVector;
Vector3.Lerp(enemy.transform.position, newEnemyPos, t);
That’s obviously pseudocode only, but it shows the theory. Basically, once you get the direction vector that your enemy is supposed to be knocked back towards, get a position a certain distance away from the enemy’s position that’s within the path of the direction vector. Then lerp your enemy towards that new position to simulate knockback.
Prolly not the best way, but it works given the constraints we’re working with.
Oh God! I guess it’s time to change my glasses: I missed that kinematic thing. If you’re not applying any kind of fake gravity to your enemies, you can simulate the movement as @Dreamblur suggested (upvote him - it’s a good solution):
private var newPos:Vector3;
private var tKnock:float = 0;
var knockForce:float = 5;
// when knocking the enemy:
var dir = enemy.position-transform.position;
newPos = dir.normalized*knockForce+transform.position;
tKnock = Time.time+1.2; // enemy movement will last 1.2 seconds
function Update(){
if (Time.time<=tKnock){
enemy.transform.position = Vector3.Lerp(enemy.transform.position, newPos, knockForce*Time.deltaTime);
}
}