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

65 lines
1.7 KiB
C#

using UnityEngine;
using UnityEngine.Assertions;
[RequireComponent(typeof(Collider))]
public class Projectile : MonoBehaviour
{
[SerializeField, Range(0f, 1f)]
private float bounciness = 0.5f;
private Collider projCol;
private Rigidbody body;
[SerializeField, Range(0, 50)]
private int damage = 10;
[SerializeField]
private int wallRebounces = 4;
private int hitWalls = 0;
public HealthComponent comingFrom;
private Vector3 prevVel;
private void Awake()
{
projCol = GetComponent<Collider>();
body = GetComponent<Rigidbody>();
Assert.IsNotNull(projCol);
PhysicMaterial pMat = new();
pMat.bounciness = this.bounciness;
pMat.staticFriction = 0f;
pMat.dynamicFriction = 0f;
pMat.frictionCombine = PhysicMaterialCombine.Minimum;
pMat.bounceCombine = PhysicMaterialCombine.Minimum;
projCol.material = pMat;
}
private void LateUpdate()
{
prevVel = body.velocity;
}
private void OnCollisionEnter(Collision collision)
{
HealthComponent hitHealthComp = collision.gameObject.GetComponent<HealthComponent>();
// if (hitHealthComp == comingFrom) return;
if (hitHealthComp)
{
hitHealthComp.TakeDamage(damage);
Destroy(gameObject);
}
else
{
if (++hitWalls == wallRebounces)
{
Destroy(gameObject);
}
Vector3 newVel = Vector3.Reflect(prevVel.normalized, collision.contacts[0].normal.normalized);
body.velocity = newVel.normalized * prevVel.magnitude * bounciness;
}
}
}