Hey guys, Unity noob here. I’m trying to implement touch input into my mobile game and have been having trouble wrapping my head around some things.
I’ve currently got a cloud character that has animations that I want to have played depending on the touch phase. To detect whether the cloud has been touched I am using RaycastHit2D and I am wanting the first animation to play when the player first touches the cloud, and the next to play when the player releases their finger. The second animation should play regardless of where the finger is on the screen at the time of release (does not have to release finger from the cloud itself).
So basically what I am trying to do is track if the initial touch that began on the cloud object ends, regardless of where it has moved on the screen since beginning the touch on the cloud. Here is what I have got so far:
Vector3 touchPosWorld;
public GameObject thePlayer;
GameObject cloudGuy;
Touch currentTouch;
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
touchPosWorld = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
Vector2 touchPosWorld2D = new Vector2(touchPosWorld.x, touchPosWorld.y);
RaycastHit2D hitInformation = Physics2D.Raycast(touchPosWorld2D, Camera.main.transform.forward);
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
if (hitInformation.collider.name == "CloudGuy")
{
currentTouch = Input.GetTouch(0);
cloudGuy = hitInformation.transform.gameObject;
cloudGuy.GetComponent<Animator>().SetBool("isTouching", true);
}
}
if (currentTouch.phase == TouchPhase.Ended)
{
cloudGuy.GetComponent<Animator>().SetBool("isTouching", false);
thePlayer.SetActive(true);
}
}
}
I have tried assigning the Input.GetTouch(0) that was used when the touch began on the cloud object to a variable which I am referencing in the TouchPhase.Ended if statement, however the if statement never seems to be called and the first animation just keeps playing. I have also tried putting the TouchPhase.Ended if statement outside the Input.touchCount > 0 if statement but it makes no difference.