Get an Object to Automatically Move Forward

Hello,

I’m trying to get an object to move forward automatically while being constrained by collisions. Here’s my code:

using UnityEngine;
using System.Collections;

public class MoveForward : MonoBehaviour {
	public float speed = 6.0F;
	public float jumpSpeed = 8.0F;
	public float gravity = 20.0F;
	private Vector3 moveDirection = Vector3.zero;
	
	
	// Update is called once per frame
	void Update () {
		CharacterController controller = GetComponent<CharacterController>();
		 if (controller.isGrounded) {
			moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
			moveDirection = transform.TransformDirection(moveDirection);
			moveDirection *= speed;
			 if (Input.GetButton("Jump"))
				moveDirection.y = jumpSpeed;
			
		}
		moveDirection.y -= gravity * Time.deltaTime;
		controller.Move(moveDirection * Time.deltaTime);	
	}
}

This is the exact same code from the Unity Scripting Reference in C#. You can find that here: Unity - Scripting API: CharacterController.Move

Can someone please tell me what I’m missing. I’ve been tackling this problem for, literally, weeks. Any input is appreciated. I thank you for your time.

I may be getting the wrong idea, but, it sounds like something that can be easily done with OnCollisionStay ( ) .

Check if it’s colliding with X, then move (x,y,z)

function OnCollisionStay ( collision : Collision)
{
if ( collision.collider == existingObjectToCheckFor )
{

 //do movement code

}
}

This line:

moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"))

means you will move only when there is input, due to Input.GetAxis(“Horizontal”) and Input.GetAxis(“Vertical”) being used for the x and z values of your movement direction.

To move forward automatically in a simplistic way, use hard-coded x and z values for the direction you want to move in.

If you want to still use input for movement direction but have the character continue to move forward when input has stopped, you can first check if there is input and if not use your existing direction for your movement direction.