简体   繁体   中英

C# Pong Game Paddle Movement via Microphone input

im trying to build Pong Game with Microphone Input as controls for the paddles. the following part of the code (c#) is moving the paddle.

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:

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. Use 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.

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. You don't need to check else if (loudness <= 8) , because if it isn't > 8 , then it is always <= 8 .
  • Conventionally, you write a = b; / a, b and not a=b; / a,b , to make your code more readable.

I hope that works for you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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