Detect Successful Landing (146319)

I’m trying to detect if a ship’s left and right landing gear are on the landing pad, indicating a success or landing failure (if one landing gear collides but not the other).

Each landing gear is its own game object and they both have their own box colliders -all within a prefab

Problem is both conditions (landing success and landing failure) end up evaluating to true regardless if both landing gear are on the pad or only one.

The following code is attached to the landing platform:

usingUnityEngine;
usingSystem.Collections;
usingSystem.Collections.Generic;

public classCollision : MonoBehaviour {

boollandingGearLeftOnPad = false;
boollandingGearRightOnPad = false;


void Start () {}


void Update () {

}


voidOnCollisionEnter2D (Collision2Dcoll) {

if (coll.gameObject.tag == "LandingGearLeft"){
landingGearLeftOnPad = true;
//Debug.Log("LeftLandingGearonPad");
}

if (coll.gameObject.tag == "LandingGearRight"){
landingGearRightOnPad = true;

}

if (landingGearLeftOnPad && landingGearRightOnPad){
Debug.Log("Landed Successfully");
}

if (landingGearLeftOnPad && !landingGearRightOnPad){
Debug.Log("You missed the landing pad");
}

if (!landingGearLeftOnPad && landingGearRightOnPad){
Debug.Log("You missed the landing pad");
}




}

voidOnCollisionExit2D (Collision2Dcoll){

landingGearLeftOnPad = false;
landingGearRightOnPad = false;

}
}

There’s a lot of weird spaces missing in your code, but I’m assuming that’s correct in your source. I’d also make a couple of changes to your logic. Firstly:

 voidOnCollisionExit2D (Collision2Dcoll){

 landingGearLeftOnPad = false;
 landingGearRightOnPad = false;

 }

Why are you setting both to false any time any object leaves the collider? You should check which gear left the pad, and only set that to false (mirroring the logic on OnCollisionEnter).

if (landingGearLeftOnPad && landingGearRightOnPad){
 Debug.Log("Landed Successfully");
 }
 
 if (landingGearLeftOnPad && !landingGearRightOnPad){
 Debug.Log("You missed the landing pad");
 }
 
 if (!landingGearLeftOnPad && landingGearRightOnPad){
 Debug.Log("You missed the landing pad");
 }

I would move this whole section into Update() so that you test for win conditions on every frame. You could also change your code to use OnCollisionStay(), which may be preferable.