If you move your finger off the button, gusInput + = 1 continues to add. How to fix?
foreach(Touch touch in Input.touches){
if(touch.phase == TouchPhase.Began gusButton.HitTest(touch.position)){
gusInput += 1;
}else{
if(touch.phase == TouchPhase.Ended gusButton.HitTest(touch.position))
gusInput -= 1;
}
}
foreach(Touch touch in Input.touches){
if(touch.phase == TouchPhase.Began gusButton.HitTest(touch.position)){
gusInput += 1;
}else{
if(touch.phase == TouchPhase.Ended gusButton.HitTest(touch.position))
gusInput -= 1;
}
}
Maybe add a bool check?
if(touch.phase == TouchPhase.Began gusButton.HitTest(touch.position) !myTouch){
myTouch = true;
}
if(touch.phase != TouchPhase.Began gusButton.HitTest(touch.position)){
MyTouch = false;
}
I haven’t worked with touch in unity much so I’m not all that sure.
you should save touchId on press and don’t check gusButton.HitTest(touch.position) on release.
class YourClass
{
public int fingerId = -1;
void YourMethod()
{
foreach(Touch touch in Input.touches)
{
if(touch.phase == TouchPhase.Began gusButton.HitTest(touch.position) fingerId == -1)
{
gusInput += 1;
fingerId = touch.fingerId;
}
else if(touch.phase == TouchPhase.Ended fingerId == touch.fingerId)
{
gusInput -= 1;
fingerId = -1;
}
}
}
}
public class Button{
public int trackedFingerId = -1;
public Rect HitRect;
public void UpdateHits()
{
if (trackedFingerId == -1)
{
foreach(var touch in Input.touches)
{
if (touch.phase == TouchPhase.Began HitRect.Contains(touch.position))
{
trackedFingerId = touch.fingerId;
OnDown();
}
}
}
else
{
foreach(var touch in Input.touches)
{
if (touch.fingerId != trackedFingerId)
continue;
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
{
trackedFingerId = -1;
OnUp();
if (HitRect.Contains(touch.position))
OnClick();
}
}
}
}
public virtual void OnUp()
{
//Do Something on up
}
public virtual void OnClick()
{
//Do Something on click
}
public virtual void OnDown()
{
//Do Something on down
}
}