Colliding multiple enemys but only one at a time attacked
Hello,
I've got a litte game where the player is able to control a group of soldiers, each soldier is individual. There are enemy soldiers on the battlefield which could been attacked by moving the group of soldiers to the position of the enemy.
Each soldier should attack only one enemy approx. every 1 sec. And there is the thing i struggle with.
**Question:**How do I get the soldiers to attack only one enemy at a time and not every soldier they are colliding with?
void OnCollisionStay2D(Collision2D coll)
{
if ((coll.gameObject.tag == "Enemy" && this.tag == "Friend") || (coll.gameObject.tag == "Friend" && this.tag == "Enemy")) //The if, because friendly and enemy soldiers are controlled by same script
{
HitTimer += Time.deltaTime;
if (HitTimer > HitTime)
{
coll.gameObject.GetComponent<SoldierLogic>().Health -= 30;
HitTimer = 0f;
}
}
}
Im thankful for every hint!
Best regards
Comment
Best Answer
Answer by Adam-Mechtley · Nov 28, 2016 at 09:43 AM
Hi! You should probably do something like this:
public class Solider : MonoBehaviour {
private Solider m_CurrentTarget;
void OnCollisionEnter2D (Collision2D other) {
if (m_CurrentTarget == null)
m_CurrentTarget = other.gameObject.GetComponent<Solider> ();
}
void OnCollisionStay2D (Collision2D other) {
if (m_CurrentTarget == null || other.gameObject != m_CurrentTarget.gameObject)
return;
// do your logic here
}
void OnCollisionExit2D (Collision2D other) {
if (m_CurrentTarget != null && other.gameObject.GetComponent<Solider> () == m_CurrentTarget)
m_CurrentTarget = null;
}
}
Your answer
Follow this Question
Related Questions
How to Make A Character Stop At Wall? 0 Answers
problem with tilemap collider and composite collider 1 Answer
Collision With Text 0 Answers