I’m attempting to make a (very simple to begin with) top-down game in 2D wherein the player (using arrow keys) is able to move around an enclosed polygonal area of the game. I’m having trouble ensuring that all parts of the area’s perimeter (made of a polygonal collider) are impenetrable (areas near corners tend not to be for some reason). Code below:
public float speed = 40f;
public bool heTouchedTheButt = false; //test whether the player is colliding with the perimeter
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.name == "Perimeter")
heTouchedTheButt = true;
}
void OnCollisionExit2D(Collision2D coll) {
if (coll.gameObject.name == "Perimeter")
heTouchedTheButt = false;
}
void FixedUpdate (){
if (!heTouchedTheButt) {
if (Input.GetKey (KeyCode.LeftArrow)) {
transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Input.GetKey (KeyCode.RightArrow)) {
transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKey (KeyCode.UpArrow)) {
transform.position += Vector3.up * speed * Time.deltaTime;
}
if (Input.GetKey (KeyCode.DownArrow)) {
transform.position += Vector3.down * speed * Time.deltaTime;
}
} else if (heTouchedTheButt) {
if (Input.GetKey (KeyCode.RightArrow)) {
transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Input.GetKey (KeyCode.LeftArrow)) {
transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKey (KeyCode.DownArrow)) {
transform.position += Vector3.up * speed * Time.deltaTime;
}
if (Input.GetKey (KeyCode.UpArrow)) {
transform.position += Vector3.down * speed * Time.deltaTime;
}
}
}
I figured setting the keys to be inversed when the player is in contact with the perimeter would allow them to come out of contact, but this appears to work only some of the time. Other times, the controls get stuck in the inverse and others allow the player to go right past the boundary as if it weren’t there. I feel like there’s a more efficient way to set up this boundary, and I appreciate any insight on how to make this easier.