Hey guys^^
I’m working on a 2D topdown game with a 8-way movement. And now I want to check if the collisioning object that touches my player is in front of him or not. (Thats for stop movement and so on)
I wrote the following script. It’s query the direction in which the player look and increase it. Than it compares the new value with the old and compares the oldposition and the position of the colliding object.
It works but sometimes it gives the false value. Is there an logic error or something I don’t see?^^
Thank you so much for your help ![]()
void OnCollisionStay2D(Collision2D obj) {
Vector2 objPos;
Vector2 myPos;
Vector2 dirVec;
float newX;
float newY;
objPos = obj.transform.position;
myPos = transform.position;
dirVec = new Vector2(0,0);
switch (movement.direction) {
//(1=Down, 2=Up, 3=Left, 4=Right, 5=UpRight, 6=DownRight,7=DownLeft and 8= UpLeft)
case 1:
dirVec = new Vector2(0,-1);
break;
case 2:
dirVec = new Vector2(0, 1);
break;
case 3:
dirVec = new Vector2(-1, 0);
break;
case 4:
dirVec = new Vector2(1, 0);
break;
case 5:
dirVec = new Vector2(1, 1);
break;
case 6:
dirVec = new Vector2(1,-1);
break;
case 7:
dirVec = new Vector2(-1,-1);
break;
case 8:
dirVec = new Vector2(-1, 1);
break;
}
newX = (myPos.x + dirVec.x);
newY = (myPos.y + dirVec.y);
if (((myPos.x < newX) && (myPos.x > objPos.x)) ||
((myPos.x > newX) && (myPos.x < objPos.x)) ||
((myPos.y < newY) && (myPos.y > objPos.y)) ||
((myPos.y > newY) && (myPos.y < objPos.y))) {
Debug.Log ("Object is in front");
} else {
Debug.Log ("Object is NOT in front");
}
}
EDIT:
I edited the script a bit so it works better, but still is a logic error in the query.