So I’m trying to convert my tile-based game into a mobile game, and I need to change the controls from keyboard keys to GUI buttons. I have my player moving in 4 directions: up, down, left and right. I need each of these directions to have it’s own buttons. I’ve watched a lot a of videos and look at lots of other answers, but I can’t figure out how to do it. I know that I need to use the OnGUI function, and I’ve tried, but it says that I cant use “&&.”
Here is my current player script for the keyboard, but how would I integrate the OnGUI function into this to have touch controls?
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
Vector3 pos; // For movement
float speed = 2.0f; // Speed of movement
static bool[] moving;
void Start () {
moving = new bool[5];
pos = transform.position; // Take the initial position
GetComponent<BoxCollider2D>().enabled = false;
}
void FixedUpdate () {
if (gameObject.tag == "Player") {
moving[4] = !(Vector2.Distance(transform.position, pos) < 0.01f);
}
else {
moving[GetComponent<CollectFruit>().ID] = !(Vector2.Distance(transform.position, pos) < 0.01f);
}
bool doneMoving = DoneMoving ();
if (doneMoving) {
GetComponent<BoxCollider2D>().enabled = true;
}
if(Input.GetKey(KeyCode.A) && doneMoving && transform.position.x > -1.9f) { // Left
pos += Vector3.left;
}
if(Input.GetKey(KeyCode.D) && doneMoving && transform.position.x < 1.9f) { // Right
pos += Vector3.right;
}
if(Input.GetKey(KeyCode.W) && doneMoving && transform.position.y < 1.9f) { // Up
pos += Vector3.up;
}
if(Input.GetKey(KeyCode.S) && doneMoving && transform.position.y > -1.9f) { // Down
pos += Vector3.down;
}
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed); // Move there
}
public bool DoneMoving() {
return !moving[0] && !moving[1] && !moving[2] && !moving[3] && !moving[4];
}
}