- Home /
Swapping Horizontal Input for Mobile
Hello,
I'm trying to port my game to mobile devices but keep running into a problem with getting my player to move at all. I have only done "runners" on mobile before and didn't have to worry about using the screen to move the player, so this is different and can't seem to see what I'm doing wrong.
I've tried several different optional I've found while searching, however none seem to work with my scripting. I don't want to have to add buttons just to move left or right and would rather just have the player swipe left/right or just be able to hold down one side or the other - either will work fine. I think at this point I just want to player to move.
The code below is the codes I have been using for my player on PC to test and not any of my attempts to move with touch controls.
Thank you for your time.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour {
public bool alive;
//Speed of the Player
public float speed = 10.0f;
//Bounds of Player
public float leftBound = -5f;
public float rightBound = 5f;
// Use this for initialization
void Start () {
alive = true;
}
// Update is called once per frame
void Update () {
//Horizontal Speed
float movementSpeedX = Time.deltaTime * Input.GetAxis("Horizontal") * speed;
//Player Movement
transform.Translate(movementSpeedX, 0, 0);
//Creates bounds around player
if (transform.position.x > rightBound)
{
transform.position = new Vector3(rightBound, transform.position.y, 0);
}
else if (transform.position.x < leftBound)
{
transform.position = new Vector3(leftBound, transform.position.y, 0);
}
}
}
What you could do is detect a touch and its position on the screen. If the touch is on the left side of the screen then move left, if it is on the right side then go right.
Pseudocode:
if touches.Count > 0:
Touch t = GetTouch(0)
screenCenter = screenWidth / 2 //This would be in pixels
if t.position.x > screenCenter:
$$anonymous$$oveRight
else:
$$anonymous$$oveLeft
Your answer
