Left/Right Button Movement for iOS

Hi there! I’m a new to coding and have been trying out some tutorials. I have been working on Brackey’s How to make a video game tutorial

and need some help with controls for iOS. I want to add 2 transparent buttons 50/50 of the screen to make my cube move left and right. Below is the current PlayerMovement script for the PC controls. How can I add in the movement for the touch controls as well? I have been watching many videos and reading different articles, but am not sure what the best method would be. Thanks in advance.

using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    public Rigidbody rb;

    public float forwardForce = 2000f;
    public float sidewaysForce = 500f;


    // Update is called once per frame
    void FixedUpdate ()
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if (Input.GetKey("d") )
        {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (rb.position.y < -1F)
        {
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

Do you know how to add an OnClick event to a Button (say for your 50/50 screen split)?
Video on buttons from Unity: UI Components - Unity Learn

Then create 1 or 2 methods to move, depending on which half of the screen was touched.

The actual movement could of course be the same as the ‘AddForce’ code you have, but just in the method(s), instead.

I have very little experience as I just started trying to code a couple weeks ago, but I will check out the link you posted and see if I can get this to work. I appreciate you taking the time to help!

Sure, well the link will show you the basics about buttons. Part of the video will show you how to access scripts that you can call when the button is clicked.
A very simple design that meets your criteria would be 2 buttons, 1 on each side, and left side makes you move left, right to the right … when clicked.

You could, in fact, have a script that reads the mouse button down (or touch), and based on the position relative to the screen, move left or right, also. They don’t even have to be buttons, but rather just based on ‘math’ I suppose you could call it.

Welcome to Unity… take your time to have fun and learn. :slight_smile:

Thanks. Yeah A LOT to learn. It’s been very fun and very frustrating so far. However, it is pretty rewarding when you finally get something to work. Again, appreciate the help. The video helped with understanding the OnClick event. Now on to learning about how to write a touch script.

With the exception of multi-touch, you can imagine most of the mouse click/touch things work interchangeably.
For instance, clicking a button… the click doesn’t care if it came from a touch or a mouse.

Enjoy yourself. :slight_smile: