What i want to do is when the hitbox trigger with the enemy, it get a knockback towards the opposite side of the hitbox coming.
But when i do it, the coroutine did start, yet the enemy just stop for a second and continue moving without any knockback.
I was thinking is it because of the `MoveTowards` function prevent the enemy from moving away from the trace(and prevent knockback). Im not sure if i am right, can someone teach me how to do the knockback?
public class Enemy : MonoBehaviour
{
private Rigidbody2D rb;
private float waitTime;
public float startWaitTime;
public float speed;
public Transform MaxPos;
public Transform MinPos;
public Transform moveSpot;
public Vector2 KnockbackDir;
public HitBox hitBox;
public bool ishitting;
// Start is called before the first frame update
void Start()
{
moveSpot.position = new Vector2(Random.Range(MinPos.position.x,MaxPos.position.x),Random.Range(MinPos.position.y,MaxPos.position.y));
rb = GetComponent();
hitBox = FindObjectOfType();
}
void Update()
{
if(!ishitting){
transform.position = Vector2.MoveTowards(transform.position,moveSpot.position, speed * Time.deltaTime);
if(Vector2.Distance(transform.position,moveSpot.position)<0.1f){
if(waitTime<=0){
MovePosition();
}else{
waitTime -= Time.deltaTime;
}
}
}
private void MovePosition(){
moveSpot.position = new Vector2(Random.Range(MinPos.position.x,MaxPos.position.x),Random.Range(MinPos.position.y,MaxPos.position.y));
waitTime = startWaitTime;
}
private void OnTriggerEnter2D(Collider2D other) {
if(other.CompareTag("Hitbox")){
StartCoroutine("KnockbackCo");
}
}
private IEnumerator KnockbackCo(){
ishitting = true;
KnockbackDir = rb.transform.position - hitBox.transform.position;
rb.AddForce(KnockbackDir * 10, ForceMode.Impulse)
yield return new WaitForSeconds(1);
ishitting = false;
}
}
This is my first time asking questions here, please forgive me if i ask not clear enough.
↧