That's a good question! Side-scrollers are relatively easy: Use a Proximity Selector, and add a trigger collider to the player that's slightly offset in front of the player. This will it will detect things in front of the player but not behind. When you flip the player's GameObject to turn, the trigger will flip with it, so it will properly detect only in the front regardless of which direction the player is facing.
4-direction / 8-direction top down is a little more complicated.
If you're using a framework such as More Mountains' TopDown Engine, it's probably easiest to use the framework's interaction system. This also makes all of your interaction feel consistent to the player, instead of having different interaction systems for different types of interaction.
If you're doing it from scratch, one solution is to use a Proximity Selector with 3 trigger colliders: beside the player (like the side-scroller setup), above, and below. In your movement code:
- If the player is moving left/right, enable the side trigger and disable the above & below triggers. Assuming you flip the player GameObject to turn left/right, this one side trigger will handle both left & right directions.
- If the player is moving up, enable the above trigger and disable the other two.
- If the player is moving down, enable the below trigger and disable the other two.
Then there's one last fine-tuning thing. When you change directions, also tell the Proximity Selector to deselect whatever had been selected in the previous direction (if anything). Here's some code to do this, which you can adapt to fit your script:
Code: Select all
// When changing directions, before changing triggers deselect the current selection:
var proximitySelector = GetComponent<ProximitySelector>();
proximitySelector.RemoveUsableFromDetectedList(proximitySelector.CurrentUsable);