BerkinAkkaya

Dash to Enemy Script (Unity)

Nov 12th, 2018
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.19 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. /* berkinakkaya.wixsite.com/blog */
  5. public class PlayerAttack : MonoBehaviour {
  6.  
  7.     [SerializeField] float jumpDistance = 25f;
  8.     [SerializeField] float knockBackPower = 10f;
  9.     [SerializeField] LayerMask enemy;
  10.  
  11.     bool attacking;
  12.     float lastHitTime;
  13.  
  14.     void Update()
  15.     {
  16.         if(Input.GetMouseButtonDown(0))
  17.             StartCoroutine("Attack");
  18.     }
  19.  
  20.     IEnumerator Attack()
  21.     {
  22.         PlayerMovement.PlayerRigidbody.AddForce(transform.right * jumpDistance, ForceMode2D.Impulse);
  23.         attacking = true;
  24.         yield return new WaitForSeconds(jumpDistance/10);
  25.         attacking = false;
  26.     }
  27.  
  28.     void Hit(GameObject enemy)
  29.     {
  30.         bool enoughtTimeElapsed = Time.time > lastHitTime + 0.1f;
  31.         if(attacking && enoughtTimeElapsed)
  32.         {
  33.             Rigidbody2D hitRigidbody = enemy.GetComponent<Rigidbody2D>();
  34.             Enemy enemyComponent = enemy.GetComponent<Enemy>();
  35.             enemyComponent.ReceiveHit();
  36.  
  37.             Vector3 force = (transform.right * knockBackPower) + (transform.up * knockBackPower / 2);
  38.             hitRigidbody.AddForce(force, ForceMode2D.Impulse);
  39.         }
  40.  
  41.         lastHitTime = Time.time;
  42.     }
  43.  
  44.     void OnCollisionStay2D(Collision2D col)
  45.     {
  46.         if(col.transform.CompareTag("Enemy")) Hit(col.gameObject);
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment