- Home /
Touch Buttons
I'm making a game for Windows Phone and it is almost ready. Except for the on screen controls. How do touch buttons work? I have four buttons on the screen, one for forward, one for backward, one for turn right and one for turn left. If the player touches one, the car should move forward. The game is also top down pseudo 2D (textures on quads etc. which are placed on different layers. For example cars are on placed on Y .5 height) When I try the game on my phone, the buttons do not work.
Small part from player movement script, the backward/forward/left/right are retrieved from PlayerPrefs.GetInt("Forward") etc., which is found earlier on the FixedUpdate() like this is
if(backward == 1) { if(forward == 0) { moveDirection = Input.GetAxis("Vertical") * reverseSpeed; rigidbody.AddRelativeForce(0, 0, moveDirection); } }
This one has the base touch logic.
using UnityEngine;
using System.Collections;
public class TouchButton : MonoBehaviour {
// Update is called once per frame
void Update () {
if(Input.touches.Length <= 0) {
}
else {
for(int i = 0; i < Input.touchCount; i++) {
if(this.guiTexture.HitTest(Input.GetTouch(i).position)) {
if(Input.GetTouch(i).phase == TouchPhase.Began) {
Debug.Log("The touch has begun on " + this.name);
this.SendMessage("OnTouchBegan");
}
if(Input.GetTouch(i).phase == TouchPhase.Ended) {
Debug.Log("The touch has ended on " + this.name);
this.SendMessage("OnTouchEnded");
}
}
}
}
}
}
And every button on screen has a seperate script like this
using UnityEngine;
using System.Collections;
public class TouchButtonForward : TouchButton {
void OnTouchBegan() {
PlayerPrefs.SetInt("Forward", 1);
}
void OnTouchEnded() {
PlayerPrefs.SetInt("Forward", 0);
}
}