Angelina
Angelina

Reputation: 21

Unity Terrain - Checking if Player is touching Terrain?

I'm making a Unity Jump and Run Game and I want to check if player touches the Terrain ground. If so, I want to make something. My Player has a Character Controller. I already tried OnCollisionEnter and OnTriggerEnter but they didn't work. My Terrain has the tag = Terrain. I know that when you use OnCollisionEnter, you need a Rigidbody but I don't know how to implement one.

Can anybody help?

Upvotes: 1

Views: 244

Answers (1)

ipodtouch0218
ipodtouch0218

Reputation: 3300

The terrain object needs to have a Terrain Collider (the hitbox)

The player must have a RigidBody of their own and a Collider (which they already do, because of your CharacterController component). Once done, inside of a script, you can use the OnCollisionEnter(Collision) function inside a script attached to your player, and check if collision.gameObject.CompareTag("Terrain") is true.

Something as simple as this should work:

public class PlayerComponent {
  //...
  public void OnCollisionEnter(Collider collider) {
    if (collider.gameObject.CompareTag("Terrain")) {
      Debug.Log("Player hit the terrain");
    }
  }
}

Upvotes: 1

Related Questions