- Home /
Help detecting when object is grounded
I am unsure how to make it so I can jump only when my character is on the ground I assume it has to do with OnCollisionEnter and OnCollisionExit but am unsure what to put in.
Here is my Script
using UnityEngine;
using System.Collections;
public class Runner : MonoBehaviour
{
public float Speed =1;
public Vector3 JumpHeight = new Vector3();
public bool IsOnGround = true;
public float DeathHeight =-10;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (!IsOnGround)
{
rigidbody.AddForce (new Vector3 (Speed, 0, 0), ForceMode.Acceleration);
}
if (gameObject.transform.position.y < DeathHeight)
{
rigidbody.velocity = new Vector3();
gameObject.transform.position = new Vector3(1,1,0);
}
if (Input.GetMouseButtonDown (0))
{
IsOnGround = false;
rigidbody.AddForce(JumpHeight,ForceMode.Impulse);
}
}
void OnCollisionEnter()
{
IsOnGround = true;
}
void OnCollisionStay()
{
IsOnGround = true;
}
void OnCollisionExit()
{
IsOnGround = false;
}
I am unsure what to put in the script to make it so the jump only works when I am on an object. (This is for an endless runner if that helps at all)
There are many posts on UA about grounding. Do some searching. Consider using Raycasting rather than collisions for detecting the ground.
I feel I should point out that you've tagged this with "Javascript", but your code is C#.
Answer by DajBuzi · Feb 10, 2014 at 07:50 AM
You have many different ways to check if character is grounded and i'll describe 2 of them. These should help you to figure out you own check method.
You can check rigidbody.velocity.y to check if he's not moving verticaly and use colliders to check for ground:
if(rigidbody.velocity.y != 0.0f && !touchingGround) isGrounded = false;
void OnCollisionEnter(Collision col){ if(col.tag == "ground") touchingGround = true; }
You can use empty game object and place it under your characters feet. Add collider to this empty object and set to be a trigger then :
void OnCollisionEnter(Collision col){ PlayerMovement.isGrounded = true; } void OnCollisionExit(Collision col){ PlayerMovement.isGrounded = false; }
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Impact Sound When Jumping? (JavaScript) 1 Answer
Ball jumping mechanic, scrip errors. 1 Answer