c# - 在每次触摸之间更改 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);
}
解决方案
设置好之后
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);
}
}
推荐阅读
- domain-driven-design - 如何在 DDD 模式中识别特定项目的实体、值对象和聚合?
- angular - 角材料中垫子进度条内的文本
- git - Git Flow应该从发布分支或主/主干分支完成发布到生产
- ios - RealmSwift 查询中带有内部对象引用的谓词问题
- ruby - 安装 pg 时出错 - 使用 activerecord 设置 postgresql(没有 rails)
- c# - 如何使用 for 循环将选定单选按钮的结果显示到一个文本框中?
- javascript - 使用 Puppeteer 滚动页面的侧边栏
- acumatica - 如何在 Acumatica 中将日期时间解释为用户的本地时区
- javascript - 每次在特定屏幕中打开反应导航应用程序
- wordpress - 在 wordpress 中可点击或激活父菜单