- Home /
get only one colliding body
I am making a game where there are melee troops.
The problem is that; when one collide with two, it hits both of them together because they both of the same scripts. I want my players to hit only one.
Options i think might help: -Raycast -Front Collider (might cause the same problem again)
Can you please help me with the techniques that can be used ?
Thank you in advance :)
Could you clarify the question? I'm not sure what you mean by it hits two of them together. do the troops collide with each other? Did you try using tags on each gameobject to filter out the collisions?
Answer by Bunny83 · Feb 26, 2016 at 04:04 AM
I guess that you simply have your attack code inside OnCollisionEnter / Stay which of course would run the code for every object your troops collider with. Here are some possible solutions depending on what behaviour is wanted:
Inside OnCollisionStay you simply attack the object you collided with (if it's "attackable") and then set a timeout / cooldown value to prevent more attacks. After that cooldown it automatically attacks again as long as it still collides with a target.
Use OnCollisionEnter (or any other method) to set the current target if you don't have one yet. In OnCollisionStay you only attack an object if it's the same as you stored as current target. This is a lock-on-target mode. You would need to add a way to clear the current target. This could be done by checking the distance to the target object. If the target moves too far away (checked in Update) you simply set the current target to null so it can pick a new one.
Both ways could be done without any collision checks. It depends on what targetting behaviour you want. Usually you would use either Physics.OverlapSphere or a large sphere trigger on your unit to get a list of possible targets which are in range and to pick one of them based on some targetting criteria. The most common one is picking the nearest enemy unit. The actual attack procedure is usually as follows: Once you picked a target you move towards the target. Once the distance to the target is smaller or equal to the attack range you stop moving and attack the enemy. After that you start a cooldown to wait for the next attack. If the enemy moved out of the attack range start moving again.
In the end there are endless behaviour possibilities and how you could implement those. For the attack sequence you could use a Coroutine however it's not necessary.
Answer by pankrac2 · Feb 25, 2016 at 02:56 PM
Maybe test if one is moving or performing an attack, can't really say because i don't know how you do it :)
Pavel
Your answer
Follow this Question
Related Questions
Trying to make object turn red OnTriggerEnter 0 Answers
Does OnTriggerStay don't detect a collision with a non-trigger collider? 1 Answer
How do I use colliders and/or triggers to end the game? 1 Answer
changing gravity OnTriggerEnter 1 Answer
How to single out specific colliders from another object 1 Answer