I am trying to make it so that in my EnemyAI script when they get hit with a bullet, they get knockback. This code I have worked but it teleports them backward, I want to use AddForce instead but I am not sure how I would change it here. can anyone help? My enemy already has a Rigidbody2D named rb in this code. Thanks in advance!
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Bullet")
{
Vector2 difference = transform.position - other.transform.position;
transform.position = new Vector2(transform.position.x + difference.x, transform.position.y + difference.y);
}
}
public float knockbackForce;
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Bullet")
{
Vector2 difference = (transform.position - other.transform.position).normalized;
Vector2 force = difference * knockbackForce;
rb.AddForce(force, ForceMode.Impulse); //if you don't want to take into consideration enemy's mass then use ForceMode.VelocityChange
}
}
Panda Strong code is perfect, just in case of 2d you need to use ForceMode2D.Impulse instead of ForceMode.Impulse!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.