简体   繁体   English

通过麦克风输入进行C#Pong游戏桨运动

[英]C# Pong Game Paddle Movement via Microphone input

im trying to build Pong Game with Microphone Input as controls for the paddles. 我正在尝试使用麦克风输入来构建Pong游戏,以用作球拍的控件。 the following part of the code (c#) is moving the paddle. 代码(c#)的以下部分正在移动拨片。

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

shouldn´t this code below do the job? 下面的这段代码不应该做这项工作吗? however its not working 但是它不起作用

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

Its obviously an easy problem but im kinda stuck in here with this noob question Thanks in advance 这显然是一个简单的问题,但我对这个菜鸟问题还停留在这里

EDIT// what i want to do: 编辑//我想做什么:

Move the paddle up when the microphone receives Sound and drop back down if there is no sound, just like an value from an visual amp. 当麦克风接收到声音时,将操纵杆向上移动;如果没有声音,则将操纵杆向下滑动,就像来自视觉放大器的值一样。

Daniel 丹尼尔

Given that Update () is called correctly and GetAveragedVolume() returns meaningful values, it would have to look like this: 鉴于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);
    }
}

Your mistakes: 您的错误:

  • else (...) is invalid. else (...)无效。 Use else if(...) . 使用else if(...)
  • You used this.GetComponent<Rigidbody2D>().velocity.y instead of this.GetComponent<Rigidbody2D>().velocity.x for the x -component of the two new vectors. 您使用this.GetComponent<Rigidbody2D>().velocity.y而不是this.GetComponent<Rigidbody2D>().velocity.x作为两个新向量的x分量。

Some tips: 一些技巧:

  • Wether you use >= or > does not really matter for floating point numbers in most cases, and definitely not in your one. 在大多数情况下,是否使用>=>对浮点数并不重要,并且绝对不是您所用的。
  • else is sufficient here. else在这里就足够了。 You don't need to check else if (loudness <= 8) , because if it isn't > 8 , then it is always <= 8 . 您无需检查else if (loudness <= 8) ,因为如果不是> 8 ,则始终为<= 8
  • Conventionally, you write a = b; 按照惯例,您写a = b; / a, b and not a=b; / a, b而不是a=b; / a,b , to make your code more readable. / a,b ,使您的代码更具可读性。

I hope that works for you! 希望对您有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM