Making my player move left/right on android

Hey guys! I recently finished a very simplistic game that is basically, avoid the oncoming vehicles. Now on windows I have it set so that I simply use the left and right arrow keys to make the player (believe it or not) move left or right. My question is what would be the best way to implement a set of controls for my android phone so that I could move on that too.

This is the current code I am using for windows :)!

using UnityEngine;
using System.Collections;

public class vehicleController : MonoBehaviour {

    public float carSpeed;
    public float maxPos = 3.6f;
    public bool hasAddedSpeed = false;
    Vector3 position;
    public uiManager ui;



    void Start ()
    {
        //ui = GetComponent<uiManager> ();
        position = transform.position;
   
   
    }
   
    void Update ()
    {
        if(!hasAddedSpeed)
        {
            if(ui.score >= 10)
            {
                carSpeed = carSpeed + 2;
                hasAddedSpeed = true;
            }

        }

        position.x += Input.GetAxis ("Horizontal") * carSpeed * Time.deltaTime;

        position.x = Mathf.Clamp (position.x,-maxPos,maxPos);

        transform.position = position;





    }
        void OnCollisionEnter(Collision col)
        {
            if(col.gameObject.tag == "Enemy Car")

                ui.Dead();
               

               
        }
    }

You can for example create two GUI buttons, and set them up so that when pressed they call a function MoveLeft or MoveRight in your code.

Pretty simple and can’t believe I never thought of it :')! I know how to add functions and call them from my Canvas ect ect but what would the code be to move my vehicle left and right separately??

An easy way to do it is to just set a bool in the functions, something like this

private bool m_MoveLeft = false;
private bool m_MoveRight = false;

public void MoveLeft()
{ 
    m_MoveLeft = true; 
}

public void MoveRight()
{ 
    m_MoveRight = true; 
}

void Update()
{
    if (m_MoveLeft)
    {
        // Move left here
    }
    if (m_MoveRight)
    {
        // Move right here
    }
    // Reset variables to keep from moving forever
    m_MoveLeft = false;
    m_MoveRight = false;
}

The bit I couldn’t get to work was the code that has to be inserted where You’ve wrote //Move right/left here :slight_smile:

Just do the same as you did before, but instead of Input.GetAxis (“Horizontal”) just use a value of -1 or 1 depending on direction.

That should get you started anyway, you might want to add some damping to this value depending on your gameplay.