- Home /
Detect if ball is on a platform or if it fell
I have a game where a ball goes on a series of tiles. The tiles are all tagged "tile" and I'm using a raycast to detect if the ball is still on the platform.
However, that raycast starts at the center of ball, and if i'm going on the edge of the platform(gravity won't affect the ball) the raycast no longer collides with the tile.
Is there a better way of checking if the ball is still on the platform?
Answer by ThisGuyThatsHere · Feb 16, 2017 at 03:06 PM
If you don't use meshcolliders for platforms, just normal box, sphere or capsule colliders you should be fine with raycasting on the right layer, but anyway OnCollisionEnter() and OnCollisionExit() seems a lot better, just need slightly more thinking to be done.
Example (keep in mind that syntax might be a little off as I'm not testing this in editor)
public LayerMask platformLayer;
int occurances; //This will prevent fake change if it collides with 2 platforms and leaves one of them
bool onPlatform;
void OnCollisionEnter(Collision other) {
if (other.gameObject.Layer == platformLayer) {
occurances++;
onPlatform = true;
}
}
void OnCollisionExit(Collision other) {
if (other.gameObject.Layer == platformLayer) {
occurances--;
if (occurances == 0) onPlatform = false;
}
}
Works like a charm! Thanks !
However, I feel like it's little heavy on the CPU...
Not really, until you do this on platform's side (a lot of rigidbodies). Rigidbody does it as it works, e.g. it's just a little line added to 2 actions that rigidbody notices either it required or not and there is no "OnCollisionStay()" which makes it a little faster, but overall it's fast anyway.
Answer by Kossuranta · Feb 16, 2017 at 02:20 PM
I would probably add collider on top of that tile as trigger. OnTriggerEnter happens when ball enters the area of the tile and OnTriggerExit happens when the ball isn't on the tile anymore.
Answer by gameplay4all · Feb 16, 2017 at 02:46 PM
If you insist on using a raycast sort of approach, you can use Physics.SphereCast()
which also gives you information on the angle of the hit which you could use for jumping directions etc. Eteeski (or Master Indie) has a great tutorial on this. But performace wise OnCollisionStay()
, as Raresh suggested, would be the better option I believe.