Search code examples
unity-game-engineuibuttontouch

how to code player to move on mobile device touch screen input using ui button


I was wondering how to make my player move when I click a UI button in unity 2D. I am more confused on how to code the UI button to receive the input and move the player until the UI button is not pressed but would still be happy if someone could help with the movement as well but the button is more important. I am coding in c#

I want it to work something like this but obviously this is just shoddy pseudocode:

public void whenClicked();
{
if (leftButton is clicked)
move player left

if (rightButton is clicked)
move player right

if (upButton is clicked)
move player jump
}


Solution

  • To move a character there is 2 main ways: moving by Transform component (since you have 2D game you have most likely RectTransform on character) and by Rigidbody component.

    TRANSFORM: script on your button should look so:

    public GameObject character; // The link to the character you want to move
    private bool doMove; // whether the character must move or not
    public float speed;
    
    private void OnMouseDown () {
        doMove = true;
    }
    private void Update () {
        if (doMove) {
            character.transform.Translate(Vector3.right * Time.deltaTime * speed);
        }
    }
    

    It is moving right. You can also use Vector3.up, Vector3.left, Vector3.down, Vector3.forward, Vector3.back Experiment with the variable speed and you'll get what you want.

    But here I have a question. I have just seen that in your question you write that you use UI button. Do you mean an Image with BoxCollider or literally GameObject with Button component. If it is the second, I recommend you to delete component Button from your button_objects because just a script with OnMouseDown function is enough. This script must be added to all your buttons (up, right...). Also you should add next strings to your code:

    public Vector3 direction;
    
    // and also edit Update function this way:
        if (doMove) {
            character.transform.Translate(direction * Time.deltaTime * speed);
        }
    

    Then in Unity set the next parameters in this script:

    For button up direction = x=0, y=1, z=0
    For button down direction = x=0, y=-1, z=0
    For button right direction = x=1, y=1, z=0
    For button left direction = x=-1, y=1, z=0

    Thus, every button will move character in its own direction;

    What about rigidBody. If you use it, you can make the same thing, but replace the function transform.Translate by GetComponent().AddForce(Vector3.right*speed, ForceMode2D.Impulse); But personally I think that moveing by Transform is easier