- Home /
How to touch specific objects?
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?
Answer by HarshadK · Dec 01, 2014 at 08:57 AM
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.
You got this a bit wrong, bool is a Boolean to deter$$anonymous$$e when to call the move function, so it has nothing to do with the problem. I looked in the docs and saw that input.getmousebuttondown or touch count only works with touching anywhere on the screen. I tried raycast(by the way it's a 2d game) but it didn't work properly. Can you give me an example how to use ray cast in this case with touch count?
Not a tested code but get the logic:
if(Input.GetTouch(0).phase == TouchPhase.Began){
// Get the position of touch in world position
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(Touch.position);
RaycastHit hit;
// Raycast forward form that position
if(Physics.Raycast(touchPosition, Vector3.forward, out hit, 10))
{
if(hit.collider.name == "$$anonymous$$oveButton")
{
GetComponent(SpriteRenderer).sprite = after;
bool = true;
}
}
}