# Automatic Left/Right movement

First 2d game in Unity. Started Character controller in C#.

Tried to get the character to move constantly right then once it hits the wall move left without needing any input from the player. Looked at a couple infinite runner character controller examples, but they seem to trick the character into thinking the player is holding down the right button in order to make the character run right infinitely "character.Move( 1, false , jump );".

Question: How to make the character start moving right automatically?

## 1 Answer

Flip a switch depending on the walls' collision face:

bool runForwards = true;

public void WallCollsionHandler(Collider collider){
if(collider.tag == "Left Facing Wall")
{
runForwards = false;

// Or
// JumpBackwards()
}
else if(collider.tag == "Right Facing Wall")
{
runForwards = true;

// Or
// JumpForwards()
}
}


This will stop you getting stuck in a wall as well as switch your direction depending on the wall face you contacted. What you'll need to do is put 2 collision triggers on a wall to differentiate the direction you jump or run.

To make your character constantly move you can apply a constant velocity or position update on each Update, the below is very crude but will get you started:

float movementSpeed = 5f;

void Update(){
oPos = transform.position;
transform.position = new Vector3(oPos.x + movementSpeed, oPos.y, oPos.z)
}


Altogether:

public class RunningCharacter : MonoBehaviour {

float movementSpeed = 5f;

bool runForwards = true;

void Update(){
UpdatePosition();
}

void UpdatePosition(){

Vector3 oPos = transform.position;
float calculatedPosition;

if(runForwards){
calculatedPosition = oPos.x + movementSpeed;
} else {
calculatedPosition = oPos.x - movementSpeed;
}

transform.position = new Vector3(oPos.x + movementSpeed, oPos.y, oPos.z)
}

void OnCollsionEnter(Collider collider){
WallCollisionHandler(collider);
}

void WallCollsionHandler(Collider collider){
if(collider.tag == "Left Facing Wall")
{
runForwards = false;

// Or
// JumpBackwards()
}
else if(collider.tag == "Right Facing Wall")
{
runForwards = true;

// Or
// JumpForwards()
}
}
}

• Nice explanation. Jul 22, 2014 at 15:22
• keep getting error CS1041: Identifier expected, here "public void WallCollsionHandler(collider){" Jul 23, 2014 at 3:41
• Argh, my pseudo code typing has gotten to me. It's exactly what the error says, it needs to be Identified: public void WallCollsionHandler(Collider collider){ Jul 23, 2014 at 8:33
• Thanks! Seems that did the trick, but my character still just sits there. It doesn't move at all. Jul 23, 2014 at 8:57
• Well you need to make it move yourself.. Have you implemented the running yet? Jul 23, 2014 at 9:36