C# 乒乓球游戏桨通过麦克风输入移动



>im 尝试使用麦克风输入作为球拍控件来构建乒乓球游戏。 代码 (C#( 的以下部分是移动球拍。

void Update () 
{
loudness=GetAveragedVolume() * sensitivty;
if (loudness>=8)
{
this.GetComponent<Rigidbody2D>().velocity=new Vector2(this.GetComponent<Rigidbody2D>().velocity.y,4);
}

下面的这段代码不应该完成这项工作吗? 但是它不起作用

else (loudness<=8) 
{
this.GetComponent<Rigidbody2D>().velocity=new Vector2(this.GetComponent<Rigidbody2D>().velocity.y,-4);
}

这显然是一个简单的问题,但我有点被这个菜鸟问题困在这里 提前致谢

编辑//我想做什么:

当麦克风收到声音时向上移动拨片,如果没有声音,则向下移动,就像来自视觉放大器的值一样。

丹尼尔

假设正确调用了Update ()并且GetAveragedVolume()返回有意义的值,它必须如下所示:

void Update () {
loudness = GetAveragedVolume() * sensitivty;
if (loudness > 8) {
this.GetComponent<Rigidbody2D>().velocity = new Vector2(this.GetComponent<Rigidbody2D>().velocity.x, 4);
}
else {
this.GetComponent<Rigidbody2D>().velocity = new Vector2(this.GetComponent<Rigidbody2D>().velocity.x, -4);
}
}

你的错误:

  • else (...)无效。使用else if(...).
  • 您对两个新向量的x-分量使用了this.GetComponent<Rigidbody2D>().velocity.y而不是this.GetComponent<Rigidbody2D>().velocity.x

一些提示:

  • 在大多数情况下,无论您使用>=还是>对于浮点数都无关紧要,在您的浮点数中绝对无关紧要。
  • else在这里就足够了。你不需要检查else if (loudness <= 8),因为如果它不是> 8,那么它总是<= 8
  • 通常,您编写a = b;/a, b而不是a=b;/a,b,以使您的代码更具可读性。

我希望这对你有用!

最新更新