I am learning C #, help me, I am trying to pass the code that I use to make the keyboard sound but when I use the touch sometimes it stops detecting or increases the value and I already tried it on some devices and the same thing happens and I would like someone to tell me say how I could make it functional without that glitch.
This is the code I use on the PC
private void FixedUpdate()
{
if (Input.GetKey(KeyCode.D))
{
direccion = 5;
}
else if (Input.GetKey(KeyCode.A))
{
direccion = -5;
}
if (run2 == true)
{
gameObject.transform.Translate(direccion * Time.deltaTime, velocidad * Time.deltaTime, 0);
}
This is the code I am trying to use for phones.
private void FixedUpdate()
{
foreach (Touch touch in Input.touches)
if (touch.phase == TouchPhase.Began)
{
direct = true;
if (direct == true)
{
getTouch++;
direct = false;
}
if (getTouch ==1)
{
direccion = 5;
}
else if (getTouch >= 2)
{
direccion = -5;
getTouch = 0;
direct = true;
}
}
if (run2 == true)
{
gameObject.transform.Translate(direccion * Time.deltaTime, velocidad * Time.deltaTime, 0);
}
Well after you set
direct = true;
the next
if(direct == true)
will always be the case.
In general instead of using a counter etc simply do e.g.
private int direction = 5;
and then later only alternate the sign doing
if (touch.phase == TouchPhase.Began)
{
direccion *= -1;
}
In general though:
You first code is ok since it uses continous input GetKey
which is true every frame.
But whenever you use single event input like GetKeyDown
or in your case the TouchPhase.Began
which are true
only within one single frame you should rather get your input in Update
!
Since FixedUpdate
might not be called every frame you might be tapping just within a frame where FixedUpdate
is not called => you miss this touch input.
So rather use
private int direction = 5;
private void Update()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
direccion *= -1;
}
}
}
private void FixedUpdate ()
{
if (run2)
{
transform.Translate(direccion * Time.deltaTime, velocidad * Time.deltaTime, 0);
}
}