Bullet
A bullet require a manual check in FixedUpdate to detect obstacles without delay.
using System.Collections;
using System.Collections.Generic;
using EODE.Wonderland;
using UnityEngine;
public class Bullet : MonoBehaviour {
public UnityEngine.Events.UnityEvent OnCollide;
public float DestroyAfter = 3f;
public float MaxDistance = 50f;
public Transform Owner { get; set; }
bool _stopped = false;
Vector3 _prevPos;
bool _ready = false;
void Start() {
// first position
_prevPos = transform.position;
_ready = true;
StartCoroutine(DistanceRoutine());
}
void FixedUpdate() {
if (!_ready) return;
// manually detect collision
var dir = transform.position - _prevPos;
RaycastHit hit;
if (Physics.Raycast(_prevPos, dir.normalized, out hit, dir.magnitude + 0.05f, gameObject.GetLayerMask())) {
if (hit.transform != Owner) {
transform.position = hit.point;
Stop();
}
}
_prevPos = transform.position;
}
IEnumerator DistanceRoutine() {
var startAt = transform.position;
do {
yield return new WaitForSeconds(1f);
}
while (!_stopped && Vector3.Distance(startAt, transform.position) < MaxDistance);
Stop();
}
void OnTriggerEnter(Collider col) {
if (col.transform == Owner) return;
Stop();
}
void Stop() {
if (_stopped) return;
_stopped = true;
OnCollide.Invoke();
var da = gameObject.AddComponent<DestroyAfter>();
da.Delay = DestroyAfter;
}
}