- Home /
Using collider to gameobject detect attack or not
I am using collider to detect the monster in player attack area or not.
And also, to detect the player in monster attack area or not.
But the problem is that will also triggering the monster "OnTrigerEnter2D" when monster going in player collider area. (player is not in monster collider area)
it mean the trigger will be triggered by other gameobject collider?
How can i fix that? Or i should not use collider to do that?
Answer by cinan032 · Aug 09, 2016 at 03:19 PM
I already fix the problem.
The first point is as @Cence99 said, I need to use OnCollisionEnter2D instead of using OnTriggerEnter2D. Thanks a lot, @Cence99.
And, I changed the structure of the Player and Monster GameObject:
Player/Monster GameObject:
Body (RigidBody and Collider)
AttackArea (Kinematic RigidBody and Collider to detect monster target)
Last, using layer collision matrix to make both of the Collider in Body and AttackArea will not effecting the other one.
Answer by Cence99 · Aug 07, 2016 at 10:37 PM
If you really want to do that with colliders, you would need to go with 2 colliders per entity. So the player has a small collider which can be detected by the monster's big radius collider, and the monster has a small collider that can be detected by the player's big radius collider.
I would recommend using Vector3.Distance though and checking if the monster is in the player's attack range and vica versa.
Example::
public class Player : MonoBehaviour
{
public Transform monster;
public float attackRange = 3;
void Update()
{
if(Mathf.Abs(Vector3.Distance(transform.position, monster.position)) < attackRange)
{
// Monster is in attack range of player, do your stuff
}
}
}
I use collider to detect monster because the game will have many monster.
So, i think it may use more resources than using collider if use "update" to loop to check all of the monster"s" in range or not.
I don't know about that, it could eventually be true. Create a child object for player and monster then which you call "AttackRadius". At this object you add a big radius trigger collider and a script that uses OnCollisionEnter to detect if player/monster is in attack range. On the player/monster itself, add a much smaller collider that is non-trigger.