- Home /
How can I make a non-player character (rigidbody) move when they touch the ground?
Sorry if something similar is explained in another question already, but I have been searching for a while and have not been able to find an answer. I'm very new to Unity and scripting so please bear with my ignorance.
I'm making a 2D game where the player does not control a character directly, but guides multiple characters by interacting with the environment. Therefore I need the characters to move on their own. For starters, I would just like them to start moving to the right as soon as they hit the ground, but am not sure what the best way to do this is. I can't seem to find code to tell an object to constantly move in one direction or how to tell if two rigidbodies (the character and the ground) are colliding. Would it be better to use several CharacterControllers or am I better off keeping them all as rigidbodies? Any help is appreciated.
Answer by MikeNewall · May 24, 2013 at 07:15 PM
Cast a ray at the floor to see if there is a collider below your character and if there is then add a force to your character.
public float moveForce = 0.5f;
private float characterHeight = 0;
void Start()
{
// Cache the characters height
characterHeight = renderer.bounds.size.y;
}
void FixedUpdate()
{
if(isGrounded())
{
rigidbody.AddForce(Vector3.right * moveForce);
}
}
bool isGrounded()
{
if(Physics.Raycast(transform.position, Vector3.down, characterHeight /2))
{
Debug.Log("Grounded");
return true;
}
else return false;
}
please Tick an answer, to close out the question. thanks. Round button with Tick.