Hi, I have git a problem with a player game object going through a wall(clone) game object. Both have a collider and both have a rigidbody2D. What happens is that like it should the player game object moves back and forth but sometimes the player prefab will go into the wall, anyone have any ideas as to why this is? My code is below for the oncollision which is attached onto the player game object:
void FixedUpdate()
{
if (Input.GetKey("down") == true)
{
transform.position = new Vector2(transform.position.x, (transform.position.y - 2));
}
else if (Input.GetKey("up") == true)
{
transform.position = new Vector2(transform.position.x, (transform.position.y + 2));
}
else if (Input.GetKey("left") == true)
{
transform.position = new Vector2(transform.position.x - 2, (transform.position.y));
}
else if (Input.GetKey("right") == true)
{
transform.position = new Vector2(transform.position.x + 2, (transform.position.y));
}
}
void OnTriggerEnter2D(Collider2D col)
{
Debug.Log("eerrrrrr");
if (col.gameObject.tag == "WallTag")
{
if (Input.GetKey("down") == true || Input.GetKeyDown("down") == true)
{
transform.position = new Vector2(transform.position.x, (transform.position.y + 5));
Debug.Log("down");
}
else if (Input.GetKey("up") == true || Input.GetKeyDown("up") == true)
{
transform.position = new Vector2(transform.position.x, (transform.position.y - 5));
Debug.Log("up");
}
else if (Input.GetKey("left") == true || Input.GetKeyDown("left") == true)
{
transform.position = new Vector2(transform.position.x + 5, (transform.position.y));
Debug.Log("left");
}
else if (Input.GetKey("right") == true || Input.GetKeyDown("right") == true)
{
transform.position = new Vector2(transform.position.x - 5, (transform.position.y));
Debug.Log("right");
}
}
}
EDIT: So I have found out that the player game object moves back and forth using my new code because it touches multiple game objects at once e.g. the corners of two walls next to each other. Does anyone know of a way to solve this problem so that it detects only once then the on trigger is activated and then it repeats this process.