首页 > 解决方案 > 在每次触摸之间更改 X 的值

问题描述

我正在学习 C#,帮帮我,我正在尝试传递用于使键盘发出声音的代码,但是当我使用触摸时,有时它会停止检测或增加值,并且我已经在某些设备上尝试过,同样的事情发生了,我希望有人告诉我如何让它在没有故障的情况下发挥作用。

这是我在 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);
         }

这是我试图用于手机的代码。

 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);
         }

标签: c#unity3dinputtouch

解决方案


设置好之后

direct = true;

下一个

if(direct == true)

将永远如此。

一般来说,而不是使用计数器等只是做例如

private int direction = 5;

然后只交替做标志

if (touch.phase == TouchPhase.Began)
{
     direccion *= -1;
}

但总的来说:

您的第一个代码没问题,因为它使用连续输入GetKey,每帧都是如此。

但是,无论何时您使用单个事件输入,例如GetKeyDown或在您的情况下TouchPhase.Began,它们true仅在一个帧内,您都应该输入Update

由于FixedUpdate可能不会在每一帧都被调用,因此您可能只是在FixedUpdate未调用的帧内点击 => 您会错过此触摸输入。

所以宁愿使用

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);
     }
}

推荐阅读