I’ve got this touch script that is for one of the buttons for a platformer game :
#pragma strict
var before : Sprite;
var after : Sprite;
var character : GameObject;
var speed : float = 10;
var bool : boolean = false;
function Update () {
if(bool == true) {
Move ();
}
if(Input.touchCount == 1) {
if(Input.GetTouch(0).phase == TouchPhase.Began){
GetComponent(SpriteRenderer).sprite = after;
bool = true;
}
if(Input.GetTouch(0).phase == TouchPhase.Ended){
GetComponent(SpriteRenderer).sprite = before;
bool = false;
}
}
}
function Move () {
character.GetComponent(Rigidbody2D).velocity.x = character.GetComponent(Rigidbody2D).velocity.x + speed * Time.deltaTime;
}
For some reason if I press any where on the screen it would move. How can I make it if I only press the button it would move?
It is accepting your touch anywhere on the screen because you are setting your bool to true on input touch began which is true for a touch anywhere on the screen.
Considering you are using the new UI from Unity 4.6, just write the function to be called Pointer Down event of that button:
function buttonDown()
{
GetComponent(SpriteRenderer).sprite = after;
bool = true;
}
Similarly add another function to your Pointer Up event for the same button:
function buttonUp()
{
GetComponent(SpriteRenderer).sprite = before;
bool = false;
}
Remember these two functions has to be public and have return type of void to add them as callback to an event for a button.
Now add a event trigger component to that button then:
- Select the appropriate event from list
- Add an event under it to the list
- Assign your game object to which the script is attahced.
- Select the function to be called based on event.
Do it for both pointer down and pointer up events for that component.
Note: Understand the concept and you can do it for even immediate mode GUI or for even GUITexture button. If you are using a 3D object as button use RayCast to detect a touch. Let me know if anything is unclear.