Hello!
I’m developing a touch-sensitive button to control the movement of the character, as in the following example:
!(http://
How do I add the script just tap the button above?
I have this code:
public class Char : MonoBehaviour
{
public GameObject player; // Main character
private float speed = 2f; // speed of locomotion of the character
void Update()
{
if (Input.touchCount > 0)
{
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
player.transform.Translate(Vector2.right * speed * Time.deltaTime);
}
}
}
}
But this code has a problem, anywhere on the screen that the player press the finger will activate the script, in fact I want the script only activate on the TouchButton Sprite, how make?
One more detail!
I don’t want the player take your finger off the screen to be pressing the left and right buttons, just the player keep your finger pressed and slide to the left and right without taking your finger off the screen of the device, how do I?
There’s loads of ways to do it. You can either do a raycast to the images as sprites and call a method on each one as you need to.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Clicked");
Vector2 pos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
RaycastHit2D hitInfo = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(pos), Vector2.zero);
// RaycastHit2D can be either true or null, but has an implicit conversion to bool, so we can use it like this
if (hitInfo)
{
Debug.Log(hitInfo.transform.gameObject.name);
// Here you can check hitInfo to see which collider has been hit, and act appropriately.
}
}
}
The way of doing it I’d prefer probably would be to make a Canvas and add each one as a button. Then on each button just add a component: Click ‘Add Component’, and go choose ‘Event Trigger’ in the ‘Event’ tab. Then you can just add ‘OnPointerUp’, and ‘OnPointerDown’, for each, and just have them access a script like this:
public GameObject player; // Main character
private float speed = 2f; // speed of locomotion of the character
public void MoveLeft()
{
player.transform.Translate(-Vector2.right * speed * Time.deltaTime);
}
public void MoveRight()
{
player.transform.Translate(Vector2.right * speed * Time.deltaTime);
}
public void MoveUp()
{
player.transform.Translate(Vector2.up * speed * Time.deltaTime);
}
public void MoveDown()
{
player.transform.Translate(Vector2.down * speed * Time.deltaTime);
}