In my top-down 2D game, the enemies have a simple AI to just move straight towards the player. Originally, I was just doing this with the following code on the enemy:
void FixedUpdate() {
var newPos = Vector3.MoveTowards(transform.position, PlayerData.Position, MoveSpeed * Time.fixedDeltaTime);
rbody.MovePosition(newPos);
}
Then, I wanted the enemies to get knocked back when hit by a projectile, which I do with this function on the enemy:
(enemies have a mass of 0.5, linear damping of 0.01, and are dynamic)
public void TakeKnockback(Vector2 amount) {
rbody.AddForce(amount, ForceMode2D.Impulse);
}
The projectile is kinematic with a trigger collider since I want it to move through enemies. In its OnTriggerEnter2D
, I call TakeKnockback
like this (other
is the Collider2D parameter, knockback is 100f):
enemy.TakeKnockback((other.transform.position - transform.position).normalized * knockback);
As you may have guessed, the enemies don’t get knocked back, because in the first code block, their position is being directly modified, overriding the changes in position due to the knockback force.
So my question is:
How can I make enemies follow a target while being knockback-able?
I’ve seen lots of explanations of how to make an enemy follow a target, and almost all of them say “just use Rigidbody2D.MovePosition
toward the target”, and I’ve seen lots of explanations of how to apply knockback to an enemy using AddForce
with an impulse force, but these two are mutually exclusive, unless I’m missing something.
I also saw one thing claiming there was a Velocity
force mode, but maybe that only exists with 3D rigidbodies? There is no ForceMode2D.Velocity
, only Force
and Impulse
.
Another thing I tried was to add a Force
force based on the difference between the target velocity and the actual velocity, but it caused the enemies to just start sliding around everywhere. Maybe I didn’t have the math right, but even then, I can’t imagine this working in a way where the enemies don’t slide at all.