- Home /
how to check if an game object had been collided with another game object form its left or right side?
hii . i have 2 game objects one as a player and the other as an enemy . now i want to check if they colide on their left or right side , or if they colide when one is on top of the other one . but i dont know what kind of function or code should i use . appreciate in advance for your help ... let me give u an example to understand what i mean : in super mario game , the player could jump on top of an enemy and then he would die . but if the player hit the enemy from left or right , then he ( player ) would die . so i need to check from which position and where two objects had been collided with each other . tnx alot
Answer by WilliamLeu · Aug 23, 2012 at 08:19 PM
In the Transform object that every MonoBehavior has, there are 3 global direction vectors, forward, right and up. When you click on GameObjects in the scene, you can see what directions they points. Red is right, Green is up, and Blue is forward - unless the assets are exported differently.
So if you wanted to check if the player is in the above hemisphere of the enemy's origin,
bool IsPlayerAboveEnemy( GameObject player, GameObject enemy, float Theta)
{
Vector3 EnemyToPlayer = player.transform.position - enemy.transform.position;
float AngleFromEnemyUp = Vector3.Angle( enemy.transform.up, EnemyToPlayer);
return AngleFromEnemyUp <= Theta;
}
with a Theta of 180.0 degrees.
Although something else you can do instead is put a trigger below your player's feet, below the player's main collider that detects if he gets hit. Then detect when an enemy enters the trigger - and if the player is moving downward at that time (compare the angle between the player's rigidbody velocity and Vector3.down/gravity), kill the enemy.
Your answer
Follow this Question
Related Questions
Trouble with collisions 1 Answer
OnCollisionEnter Collision not detected? 1 Answer
Check if collider is colliding with anything non specific? 1 Answer
Jump on the ground 2 Answers