How do you create a Button (As an Object in a 2D Level) Where you can only press it from the top?

I am remaking a game I made a while back in GDevelop, in Unity now. I have no idea how to create a button as an object in a 2D level where you jump on the top of it and it reacts, but not if you collide on the sides of it. My idea is like a P-Switch from Super Mario Bros, or from the game I'm remaking (The GIF shown)m9tkK8R8DxiRuHNu5y

you could check the velocity of the player on contact and if its not a -y value, then its not from above?

I didn't end up doing that but that gave me an Idea and i was able to figure it out. What I ended up doing is checking if the player collided with the button, and additionally if the player's y value was higher than the buttons y value (plus 0.5 for a bit of room) I'll post the code and a gif of it working right now!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ButtonScript : MonoBehaviour
{
    // Start is called before the first frame update
    public PLAYER pla;
    public Color newColor;
    private SpriteRenderer rend;
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Player") && pla.transform.position.y > transform.position.y + 0.5)
        {
            rend = GetComponent<SpriteRenderer>();
            rend.color = newColor;
        }
    }

}

9inkS9XTQeVwBjFcls

You are provided the contacts; in the test above, any collision normal pointing upwards means you're contacting it from above.

You can also ask for contacts anytime and even filter them with a ContactFilter2D asking for only contacts with normals pointing up/upwards.

You can see that being used in this example to only allow jumping when the angle of the slope below it is within a certain range.

Also, wouldn't it be best to limit those "buttons" to only contact the player layer so you're not having to do string/tag comparisons?

https://docs.unity3d.com/ScriptReference/ContactPoint2D.html
https://docs.unity3d.com/ScriptReference/ContactFilter2D.html

https://www.youtube.com/watch?v=ZgsrAHGU-mA

1 Like