- Home /
Using isGrounded with a RigidBody
So I needed my PlayerCharacter to have a rigidbody, and when using the built in character controller with a rigidbody it creates weird results. So I set out to create a charactercontroller around a rigidbody. This is what I have so far in C#:
using UnityEngine;
using System.Collections;
public class PlayerCharacter : MonoBehaviour {
public CharacterController contoller;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.W)){
ForwardMovement ();
}
if(Input.GetKey(KeyCode.S)){
BackwardMovement ();
}
if(Input.GetKey(KeyCode.D)){
MovingRight ();
}
if(Input.GetKey(KeyCode.A)){
MovingLeft ();
}
if(Input.GetKey (KeyCode.Space)){
Jump ();
}
}
void ForwardMovement (){
rigidbody.AddForce(transform.forward * 100);
}
void BackwardMovement (){
rigidbody.AddForce(-transform.forward * 100);
}
void MovingRight (){
rigidbody.AddForce(transform.right * 100);
}
void MovingLeft (){
rigidbody.AddForce(-transform.right * 100);
}
void Jump (){
rigidbody.AddForce(transform.up * 100);
}
}
Moving forward, backward, left, and right are all working fine. Using the MouseLook script that on the original charactercontroller works just fine for looking around with the mouse. The problem i'm having is the jump. It goes up just fine and comes down just fine but I can press spacebar whenever and it'll move up. Is there a way to use charactercontroller variable and then use isGrounded or do I need to do it a different way since it's a rigidbody? Thanks for any and all help!
Answer by aldonaletto · Apr 24, 2013 at 12:46 AM
You could use a short raycast downwards: take a look at this question.
Will said raycast still work regardless? For example if the player started at 0 on the y axis but walks up a hill and is at 20 on the y axis then jumps will it still register as grounded?
Yes, the raycast is done from the player position in the down direction with a limited range: if nothing is hit inside this range, the rigidbody is considered ungrounded. The range is defined so that it goes only a little below the player's feet, thus the absolute Y of the player doesn't matter.
but remember, because you are racasting from the rigidbody, it may be hitting the character controller. You shouldn't have a rigidbody and character controller on the same gameobject, this is why you are seeing unpredictable results as my original answer suggested in a shorter way.
Answer by ZorNiFieD · Apr 24, 2013 at 02:21 AM
I thought you weren't supposed to use a rigidbody with a CharacterController?
Your answer
Follow this Question
Related Questions
How to change CC script to Rigidbody script 1 Answer
controller.Move doesn't stay grounded when walking down slope 3 Answers
Fly Mode 2D + Rigid Body vs CharacterController problems 0 Answers
How do I make my Rigidbody player not get stuck on walls? 2 Answers
attached.Rigidbody isn't working with a ChactacterController? -1 Answers