Making a character move automatically in one direction.

I want my character to move in one direction at all times (a running sidescroller game), and it still needs to use gravity.

I tried transform.Translate but that forces the character to go trough objects.
Can someone help me? I’m still quite new to Unity.

using UnityEngine;
using System.Collections;

public class scr_Player : MonoBehaviour {
    public float sspeed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector2 moveDirection = Vector2.zero;

	void Start () {
	}

	void Update () {
       // transform.Translate(0.10F, 0, 0 * Time.deltaTime);
            //Didn't work as intended.
                //Forced the character through objects.

        CharacterController player = GetComponent<CharacterController>();
        if (player.isGrounded) {
            moveDirection = new Vector2();
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= jumpSpeed;
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpSpeed;

        }
        moveDirection.y -= gravity * Time.deltaTime;
        player.Move(moveDirection * Time.deltaTime);


	}
}

If you do not want to move the character via transform you could try adding force to the rigidbody of your character:

rigidbody.AddForce (0, 0, 5);

Just make sure that your character has a rigidbody component :slight_smile:

Some nice guys at 4chan /v/ Gamedev Thread came up with a working solution, here it is:

public class scr_PlayerTest : MonoBehaviour
{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector2 moveDirection = Vector2.zero;

void Start(){
}

void Update(){
    CharacterController player = GetComponent<CharacterController>();

    if (player.isGrounded)
    {
        // if player is on the ground, we normally don't want to move him vertically
        moveDirection.y = 0;

        // but if the jump button is pressed, then we do want him moving vertically
        if (Input.GetButton("Jump"))
        {
            moveDirection.y = jumpSpeed;
        }
    }
    else
    {
        // if player is not on the ground, then apply gravity to him
        moveDirection.y -= gravity * Time.deltaTime;
    }

    // constantly move horizontally
    moveDirection.x = speed;

    // finally, we actually apply the movement to the player
    player.Move(moveDirection * Time.deltaTime);
}

}