简体   繁体   中英

XNA 2D sound effect mouse hovering

Working on a game here and I've so far made a menu system for my game. I added three different buttons. I have everything sorted out except one thing.

So, I am using a normal if intersects method to see if the mouse and the button rectangle is colliding to play a sound effect. However, I don't know how to stop this sound and it's just looping itself all the time, until I remove the mouse from the button. I want to make it so that it only plays one time.

public void Update(MouseState mouse, GraphicsDevice graphics, SoundEffect soundEffect)
{
    rectangle = new Rectangle((int)position.X, (int)position.Y, (int)size.X, (int)size.Y);

    Rectangle mouseRectangle = new Rectangle(mouse.X, mouse.Y, 1, 1);

    if(mouseRectangle.Intersects(rectangle))
    {
        if (mouse.LeftButton == ButtonState.Pressed) isClicked = true;
        size = new Vector2(graphics.Viewport.Width / 9, graphics.Viewport.Height / 13);
        soundEffect.Play();
    }

    else
    {
        size = new Vector2(graphics.Viewport.Width / 10, graphics.Viewport.Height / 14);
        isClicked = false;
    }

Any help would be apreciated.

BTW: This is not neccesary, but I got another "problem" when I hover over the buttons, they get bigger which is intended. But it doesn't get bigger from the center. It's kind of hard to explain but it gets bigger in x and y position, not -x and -y. It has the same positon.

You're going to have to employ some status fields or events to do what you want. Something simple might be to track when the mouse enters and leaves the rectangle:

private bool _mouseIsIntersecting;

public void Update(...)
{
    rectangle = new Rectangle(...);

    Rectangle mouseRectangle = new Rectangle(...);

    if(mouseRectangle.Intersects(rectangle))
    {
        // Handle click and size stuff

        // Only play the sound if mouse was not previously intersecting
        if (!_mouseIsIntersecting)
            soundEffect.Play();
        _mouseIsIntersecting = true;
    }
    else
    {
        _mouseIsIntersecting = false;

        // Handle other stuff
    }
}

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