Created
September 20, 2024 23:31
-
-
Save Ddemon26/4456bd20d463f451c331557ed3c76e6a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using FPSPlayerController.DamonFPS.Player; | |
using UnityEngine; | |
namespace NewGameLogic.DamageSystem.Testing | |
{ | |
[System.Serializable] | |
public class BulletPenetration | |
{ | |
[SerializeField] private float damageMultiplier = 0.5f; | |
private List<IDamageable> damageableList = new List<IDamageable>(); | |
private RaycastHit[] hits = new RaycastHit[20]; | |
private class RaycastHitComparer : IComparer<RaycastHit> | |
{ | |
public int Compare(RaycastHit x, RaycastHit y) | |
{ | |
return x.distance.CompareTo(y.distance); | |
} | |
} | |
public void CastPenetrationRay(Component camera, float damage, LayerMask layerMask) | |
{ | |
damageableList.Clear(); | |
Vector3 rayOrigin = camera.transform.position; | |
Vector3 rayDirection = camera.transform.forward; | |
while (true) | |
{ | |
int numHits = CastRayAndSortHits(rayOrigin, rayDirection, layerMask); | |
if (numHits == 0) | |
{ | |
break; | |
} | |
ProcessHits(numHits); | |
rayOrigin = hits[numHits - 1].point + rayDirection * 0.01f; | |
} | |
ApplyPenetrationDamage(damage); | |
} | |
private int CastRayAndSortHits(Vector3 rayOrigin, Vector3 rayDirection, LayerMask layerMask, float maxDistance = 200f) | |
{ | |
Ray ray = new Ray(rayOrigin, rayDirection); | |
int numHits = Physics.RaycastNonAlloc(ray, hits, maxDistance, layerMask); | |
Array.Sort(hits, 0, numHits, new RaycastHitComparer()); | |
return numHits; | |
} | |
private void ProcessHits(int hitNumber) | |
{ | |
for (int i = 0; i < hitNumber; i++) | |
{ | |
RaycastHit hit = hits[i]; | |
if (!hit.collider.TryGetComponent(out IDamageable damageable) || | |
damageable == null || damageableList.Contains(damageable)) continue; | |
damageableList.Add(damageable); | |
damageable.GiveHitInfo(hit); | |
} | |
} | |
private void ApplyPenetrationDamage(float damage) | |
{ | |
float currentMultiplier = 1f; | |
foreach (IDamageable damageable in damageableList) | |
{ | |
damageable.ApplyDamage(damage * currentMultiplier); | |
currentMultiplier *= damageMultiplier; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment