- Home /
This question was
closed Mar 11, 2015 at 01:57 PM by
Sindorej for the following reason:
Outdated
Touch controls
I want to have a button to move my character for touch controls.
Like that on the bottom left corner of the image
I have the following code but it does not move the button at all. It works ok when i use mouse input instead of touch. What do i do wrong?
using UnityEngine;
using System.Collections;
public class mobile_control : MonoBehaviour {
private int initx = 100;
private int inity = Screen.height-70;
Rect buttonRect;
bool buttonPressed = false;
private int MaxClampX;
private int MinClampX;
private int MaxClampY;
private int MinClampY;
void Start(){
buttonRect = new Rect (initx,inity, 40, 40);
MaxClampX = initx + 80;
MinClampX = initx - 60;
MinClampY = inity;
MaxClampY = inity - 60;
}
void OnGUI()
{
if(Input.touchCount > 0){
if(Input.GetTouch(0).position.x<200 && Input.GetTouch(0).position.y > Screen.height - 200)
{
buttonPressed = true;
} else {
buttonPressed = false;
if(buttonRect.y<inity) buttonRect.y +=2;
if(buttonRect.y>=inity) buttonRect.y = inity;
if(buttonRect.x>initx+6) buttonRect.x -=2;
if(buttonRect.x<initx-6) buttonRect.x +=2;
}
if(buttonPressed && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector2 tdelta = Input.GetTouch(0).deltaPosition;
if(!(buttonRect.x+tdelta.x>=MaxClampX || buttonRect.x+tdelta.x<=MinClampX))
buttonRect.x += tdelta.x;
if(!(buttonRect.y+tdelta.y<=MaxClampY || buttonRect.y+tdelta.y>=MinClampY))
buttonRect.y += tdelta.y;
if(buttonRect.x>initx+10){
Debug.Log("Forward");
if(buttonRect.x>initx+60){
Debug.Log("Run");
}
}
if(buttonRect.x<initx-10){
Debug.Log("Backward");
}
if(buttonRect.y<inity-30){
Debug.Log("Jump");
}
}
} else {
if(buttonRect.y<inity) buttonRect.y +=2;
if(buttonRect.y>=inity) buttonRect.y = inity;
if(buttonRect.x>initx+6) buttonRect.x -=2;
if(buttonRect.x<initx-6) buttonRect.x +=2;
}
GUI.Button(buttonRect, "X");
}
}
Comment