mmorpg/Assets/Script/RangeProjectile.cs
2024-08-23 16:17:24 +05:30

106 lines
2.9 KiB
C#
Executable File

using System.Collections;
using System.Collections.Generic;
using Mirror;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Events;
public class RangeProjectile : NetworkBehaviour
{
public float speed;
public float distance;
public float lifetime;
public float hitLifetime;
public LayerMask isEnemy;
public Vector3 direction;
public uint shooterId;
public float castRadius;
public GameObject hitEffectVfx;
public UnityEvent<enemyScript> OnHit;
void Start(){
// if(!isLocalPlayer){return;}
Invoke("DestroyProjectile",lifetime);
}
public bool isLocalp;
void Update(){
isLocalp = isLocalPlayer;
transform.Translate(direction * speed * Time.deltaTime);
// if(!isLocalPlayer){return;}
//raycast
Collider2D overlapCol = Physics2D.OverlapCircle(transform.position, castRadius);
if(overlapCol != null){
enemyScript enemy = overlapCol.GetComponent<enemyScript>();
bool hasPlayer = overlapCol.transform.root.GetComponent<playerNetwork>()!=null;
Debug.Log($"{shooterId} shot {overlapCol.name}({netId}), has player? : {hasPlayer}");
if(hasPlayer){return;}
// Debug.Log()
if(enemy == null){
//no enemy
DestroyProjectile();
}else{
OnHit.Invoke(enemy);
DestroyProjectile();
}
}
return;
RaycastHit2D hitRay = Physics2D.CircleCast(transform.position, castRadius, transform.up , distance , isEnemy);
if(hitRay.collider != null){
enemyScript enemy = hitRay.collider.GetComponent<enemyScript>();
bool hasPlayer = hitRay.collider.transform.root.GetComponent<playerNetwork>()!=null;
Debug.Log($"{shooterId} shot {hitRay.collider.name}({netId}), has player? : {hasPlayer}");
if(hasPlayer){return;}
// Debug.Log()
if(enemy == null){
//no enemy
DestroyProjectile();
}else{
OnHit.Invoke(enemy);
DestroyProjectile();
}
// if(hitRay.collider.CompareTag("Enemy")){
// //enemyTakeDamage
// Debug.Log("Enemy Took Magical Damage Range");
// }else{
// DestroyProjectile();
// }
}
}
void DestroyProjectile(){
//Instantiate hit effect
if (isServer)
{
RpcDestroyProjectile();
destroyProjectile();
}
//Destroy(hitEffectVfx, hitLifetime);
}
[ClientRpc]
void RpcDestroyProjectile()
{
destroyProjectile();
}
void destroyProjectile()
{
Instantiate(hitEffectVfx, transform.position, Quaternion.identity);
Destroy(gameObject);
}
void OnDrawGizmos(){
Gizmos.DrawWireSphere(transform.position, castRadius);
}
}