Created
May 11, 2017 19:52
-
-
Save unity3dcollege/a241c5677dbf8cd8ba772c7c70224f0a 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 UnityEngine; | |
public class Projectile : MonoBehaviour, IPoolable | |
{ | |
[SerializeField] | |
protected float speed = 5f; | |
[SerializeField] | |
[Tooltip("How much damage it will do to a player on hit.")] | |
protected int damage = 10; | |
[SerializeField] | |
private float lifetime = 10f; | |
private bool collided; | |
private float timer; | |
public event Action OnDestroyEvent = delegate { }; | |
public Vector3 Direction { get; private set; } | |
private void OnDisable() { OnDestroyEvent(); } | |
private void OnEnable() | |
{ | |
Reset(); | |
} | |
protected virtual void Reset() | |
{ | |
timer = 0f; | |
GetComponent<Rigidbody>().velocity = Vector3.zero; | |
collided = false; | |
} | |
public void SetDirection(Vector3 direction) | |
{ | |
Direction = direction; | |
} | |
internal void DamagePlayer(Health health) | |
{ | |
health.TakeDamage(damage); | |
SelfDestruct(); | |
} | |
private void Update() | |
{ | |
if (ShouldMove()) | |
Move(); | |
timer += Time.deltaTime; | |
if (timer >= lifetime) | |
SelfDestruct(); | |
} | |
private bool ShouldMove() | |
{ | |
return true; | |
} | |
protected virtual void Move() | |
{ | |
var movement = Direction * speed * Time.deltaTime; | |
GetComponent<Rigidbody>().MovePosition(transform.position + movement); | |
} | |
private void OnCollisionEnter(Collision collision) | |
{ | |
if (collided) | |
return; | |
if (collision.collider.GetComponent<Health>() != null) | |
{ | |
var health = collision.collider.GetComponent<Health>(); | |
health.TakeDamage(damage); | |
collided = true; | |
SelfDestruct(); | |
} | |
} | |
protected void SelfDestruct() | |
{ | |
// particles, etc, remove from pool | |
gameObject.SetActive(false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment