3DTD/Assets/Scripts/Tower/Projectile.cs

70 lines
1.9 KiB
C#
Raw Normal View History

2024-04-20 15:56:26 +02:00
using UnityEngine;
using UnityEngine.Assertions;
2024-04-21 03:22:20 +02:00
using UnityEngine.Events;
2024-04-20 15:56:26 +02:00
[RequireComponent(typeof(Collider))]
public class Projectile : MonoBehaviour
{
[SerializeField, Range(0f, 1f)]
private float bounciness = 0.5f;
private Collider projCol;
2024-04-20 21:55:03 +02:00
private Rigidbody body;
2024-04-20 15:56:26 +02:00
2024-04-20 20:48:38 +02:00
[SerializeField, Range(0, 50)]
private int damage = 10;
[SerializeField]
private int wallRebounces = 4;
private int hitWalls = 0;
2024-04-20 21:55:03 +02:00
2024-04-20 20:48:38 +02:00
public HealthComponent comingFrom;
2024-04-21 03:22:20 +02:00
public UnityEvent OnReflect;
2024-04-20 21:55:03 +02:00
private Vector3 prevVel;
2024-04-20 15:56:26 +02:00
private void Awake()
{
projCol = GetComponent<Collider>();
2024-04-20 21:55:03 +02:00
body = GetComponent<Rigidbody>();
2024-04-20 15:56:26 +02:00
Assert.IsNotNull(projCol);
PhysicMaterial pMat = new();
pMat.bounciness = this.bounciness;
2024-04-20 21:55:03 +02:00
pMat.staticFriction = 0f;
pMat.dynamicFriction = 0f;
pMat.frictionCombine = PhysicMaterialCombine.Minimum;
pMat.bounceCombine = PhysicMaterialCombine.Minimum;
2024-04-20 15:56:26 +02:00
projCol.material = pMat;
}
2024-04-20 20:48:38 +02:00
2024-04-20 21:55:03 +02:00
private void LateUpdate()
{
prevVel = body.velocity;
}
2024-04-20 20:48:38 +02:00
private void OnCollisionEnter(Collision collision)
{
HealthComponent hitHealthComp = collision.gameObject.GetComponent<HealthComponent>();
2024-04-20 22:19:23 +02:00
// if (hitHealthComp == comingFrom) return;
2024-04-20 20:48:38 +02:00
if (hitHealthComp)
{
hitHealthComp.TakeDamage(damage);
Destroy(gameObject);
}
else
{
if (++hitWalls == wallRebounces)
{
Destroy(gameObject);
}
2024-04-20 21:55:03 +02:00
Vector3 newVel = Vector3.Reflect(prevVel.normalized, collision.contacts[0].normal.normalized);
body.velocity = newVel.normalized * prevVel.magnitude * bounciness;
2024-04-21 03:22:20 +02:00
OnReflect?.Invoke();
AudioManager.PlaySound("BulletBounce", transform.position);
2024-04-20 20:48:38 +02:00
}
}
2024-04-20 15:56:26 +02:00
}