/// --------------------------------------------- /// Behavior Designer /// Copyright (c) Opsive. All Rights Reserved. /// https://www.opsive.com /// --------------------------------------------- namespace Opsive.BehaviorDesigner.Samples { using UnityEngine; /// /// Moves a projectile towards the specified target. /// public class Projectile : MonoBehaviour { [Tooltip("The speed at which the projectile should move.")] [SerializeField] protected float m_Speed = 5; [Tooltip("The amount of damage that should be applied.")] [SerializeField] protected float m_DamageAmount = 20; [Tooltip("The +/- range of damage that should be applied.")] [SerializeField] protected float m_DamageVariance; [Tooltip("Should the y-axis direction be ignored?")] [SerializeField] protected bool m_IgnoreY = true; [Tooltip("Should the projectile rotate towards the target?")] [SerializeField] protected bool m_RotateTowardsTarget; private Transform m_Transform; private Transform m_Target; /// /// Initializes the projectile to the specified target. /// /// The target the projectile should move towards. public void Initialize(GameObject target) { m_Transform = transform; m_Target = target.transform; if (m_RotateTowardsTarget) { var direction = GetDirection(); var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; m_Transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); } } /// /// Returns the direction that the projectile should move. /// /// The direction that the projectile should move. private Vector3 GetDirection() { var direction = m_Target.position - m_Transform.position; if (m_IgnoreY) { direction.y = 0; } return direction.normalized; } /// /// Move towards the target. /// private void Update() { var direction = GetDirection(); m_Transform.position += direction * m_Speed * Time.deltaTime; if (m_RotateTowardsTarget) { var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; m_Transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); } } /// /// The projectile collided with another object. /// /// The other object. private void OnCollisionEnter(Collision collision) { Health health; if (collision.transform == m_Target && (health = collision.collider.gameObject.GetComponent()) != null) { health.Value -= (m_DamageAmount + Random.Range(-m_DamageVariance, m_DamageVariance)); Destroy(gameObject); } } /// /// The projectile collided with another object. /// /// The other object. private void OnCollisionEnter2D(Collision2D collision) { Health health; if (collision.transform == m_Target && (health = collision.collider.gameObject.GetComponent()) != null) { health.Value -= (m_DamageAmount + Random.Range(-m_DamageVariance, m_DamageVariance)); Destroy(gameObject); } } } }