Home > Mobile >  How too add left right touch controls c# unity
How too add left right touch controls c# unity

Time:05-03

So I created a really basic game for pc with a and d as left and right, however I want to port it to android installed the android pakage in unity and I don't know how to make it ti where when you touch the left side of the screen the object goes left and touch the right of the screen it goes right. current code from pc port

using UnityEngine;

public class player : MonoBehaviour
{
   public Rigidbody rb;
   public float force = 200f;
   public float left = -100f;
   public float right = 100f;
   
   
    void FixedUpdate()
    {
        //Makes the ball move forward
        rb.AddForce(0, 0, force * Time.deltaTime);
        //Makes the ball move right and left
        if (Input.GetKey("d"))
        {
            rb.AddForce(right * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

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


    }
}

CodePudding user response:

You can get the extents of the left side by using Screen.width / 2. Left side is found by checking that the x value of your screen touch is below that half width value.

eg.

var halfWidth = Screen.width / 2;

var touch = Input.GetTouch(0);
var touchPos = touch.position;

if (touchPos.x < halfWidth)
{
    Debug.Log("Left touched!");
}
else
{
    Debug.Log("Right touched!");
}

CodePudding user response:

Calculating touch position like @hijinxbassist's answer is the best way i think.

But you can use another solution like below either.

  • Create Two Buttons and resize it to fill half of screen.

  • Set button's anchor to each size of your screen. (In this case left and right side)

  • Add button's onclick listener, and target to your code.

  • Related