65 lines
1.9 KiB
C#
65 lines
1.9 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class Knockback : MonoBehaviour
|
|
|
|
{
|
|
public float thrust;
|
|
public float knockTime;
|
|
private float timer = 0f;
|
|
private float waitTime = 0.35f;
|
|
private bool firstAttack = true;
|
|
|
|
void Update()
|
|
{
|
|
timer += Time.deltaTime;
|
|
if (timer >= 0.5f)
|
|
{
|
|
firstAttack = true;
|
|
}
|
|
}
|
|
|
|
void OnTriggerEnter2D(Collider2D collision)
|
|
{
|
|
if (collision.gameObject.CompareTag("Enemy"))
|
|
{
|
|
if(firstAttack == true)
|
|
{
|
|
Rigidbody2D enemy = collision.GetComponent<Rigidbody2D>();
|
|
firstAttack = false;
|
|
if (enemy != null)
|
|
{
|
|
enemy.isKinematic = false;
|
|
Vector2 difference = enemy.transform.position - transform.position;
|
|
difference = difference.normalized * thrust;
|
|
enemy.AddForce(difference, ForceMode2D.Impulse);
|
|
StartCoroutine(KnockCo(enemy));
|
|
}
|
|
}
|
|
else if (timer >= waitTime)
|
|
{
|
|
Rigidbody2D enemy = collision.GetComponent<Rigidbody2D>();
|
|
if (enemy != null)
|
|
{
|
|
enemy.isKinematic = false;
|
|
Vector2 difference = enemy.transform.position - transform.position;
|
|
difference = difference.normalized * thrust;
|
|
enemy.AddForce(difference, ForceMode2D.Impulse);
|
|
StartCoroutine(KnockCo(enemy));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private IEnumerator KnockCo(Rigidbody2D enemy)
|
|
{
|
|
if (enemy != null)
|
|
{
|
|
yield return new WaitForSeconds(knockTime);
|
|
enemy.velocity = Vector2.zero;
|
|
enemy.isKinematic = true;
|
|
}
|
|
}
|
|
}
|