Prevent player from jumping when clicking on an object (169306)

Does anyone know how to stop your player from jumping when you click on an object? I have a ball that can jump over obstacles and I want it to not jump when I have clicked on a door to destroy it.

Player script:

void Update() {

    grounded = Physics2D.IsTouchingLayers(col, layerGround);

    if (Input.GetMouseButton(0) && grounded && !gameOver && started) {
        if (speed > 0) {
            if (OpenDoor.instance.isDoorOpen == false) {
                rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
            }
        }
    }
}

Door script:

public class OpenDoor : MonoBehaviour {
 
    public static OpenDoor instance;
    public bool isDoorOpen;
 
    void Awake() {
        if (instance == null) {
            instance = this;
        }
    }
 
    // Use this for initialization
    void Start () {
        isDoorOpen = false;
    }
   
    // Update is called once per frame
    void Update () {
 
    }
 
    public void OnMouseDown() {
            //doorOpen.SetActive(true);
        Destroy(gameObject);
        isDoorOpen = true;
    }
}

1 Answer

1

You could set the door on a different layer and then on Input.GetMouseButton(0) check whether or not a collider with the door layer can be found when clicking.

I’m guessing you’re using 2D colliders, so Unity - Scripting API: Physics2D.OverlapPoint might help you out.

If this returns a collider (collider != null) then just get the script on the door and open it instead of jumping.

EDIT: If OverlapPoint is too precise for your needs, you could also use Unity - Scripting API: Physics2D.OverlapCircle and just make the overlap area as big as you need.