mmorpg/Assets/Script/PlayerAttack.cs
2024-02-16 00:42:43 +05:30

103 lines
3.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class PlayerAttack : NetworkBehaviour{
private float timeBetweenAttacks;
public float startTimeBtwAttacks;
//public Transform attackPosition;
public LayerMask enemyMask;
public float attackRange;
public Vector3 castOffset;
public int damage;
public playerNetwork pnet;
public GameObject leftAnim,rightAnim,upAnim,downAnim;
void Start(){
if(!isLocalPlayer){
Destroy(this);
}
}
void Update(){
//Get player look dir
if(timeBetweenAttacks <=0){
if(Input.GetMouseButtonDown(0)){
StartCoroutine(couroutineAttack());
timeBetweenAttacks = startTimeBtwAttacks;
}
}else{
timeBetweenAttacks -= Time.deltaTime;
}
}
IEnumerator couroutineAttack(){
yield return new WaitForSecondsRealtime(0.6f);
Attack();
}
void Attack(){
Vector3 direction = GetPlayerLookDir();
RaycastHit2D hit = Physics2D.Linecast(transform.position + castOffset, castOffset +transform.position + (direction * attackRange), enemyMask);
if(hit.collider == null){return;}
if(hit.collider.transform.GetComponent<enemyScript>() != null){
int damageamount = damage + (pnet.lvl*5);
hit.collider.transform.GetComponent<enemyScript>().TakeDamage(damageamount, netId);
Debug.Log("Attacked enemy " + damageamount);
}else{
Debug.Log("Not an enemy : " + hit.collider.transform.name);
}
}
Vector3 GetPlayerLookDir(){
Vector3 direction = Vector3.right;
if(leftAnim.activeSelf){
direction = Vector3.left;
}else if(rightAnim.activeSelf){
direction = Vector3.right;
}else if(upAnim.activeSelf){
direction = Vector3.up;
}else if(downAnim.activeSelf){
direction = Vector3.down;
}
return direction;
}
void OnDrawGizmos(){
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position+castOffset, castOffset+ transform.position + (GetPlayerLookDir() * attackRange));
}
// void Update() {
// if(timeBetweenAttacks <= 0){
// if(Input.GetMouseButtonDown(0)){
// Collider2D[] enemyInRange = Physics2D.OverlapCircleAll(attackPosition.position , attackRange , enemyMask);
// for(int i = 0; i< enemyInRange.Length; i++ ){
// enemyInRange[i].GetComponent<enemyScript>().TakeDamage(damage);
// }
// }
// timeBetweenAttacks = startTimeBtwAttacks;
// }
// else{
// timeBetweenAttacks -= Time.deltaTime;
// }
// }
// void OnDrawGizmosSelected() {
// Gizmos.color = Color.red;
// Gizmos.DrawSphere(attackPosition.position, attackRange);
// }
}