Monogame: SoundEffect, нажав на спрайт

Для моего университета мы должны начать с изучения Monogame/XNA на VisualStudio 2015. Мы должны сделать Sprite, который вращается по кругу и производит звуковой эффект, щелкая по нему и звуковой эффект, пропуская его. Но я не могу понять, как это сделать.

Все остальное просто отлично работает (после нескольких часов работы). Я был бы очень благодарен за любую помощь. Заранее спасибо.

С наилучшими пожеланиями Алекс.

PS: простите за мой английский:)

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Hausaufgabe_Uni_Logo
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
    GraphicsDeviceManager mGraphics;
    SpriteBatch mSpriteBatch;
    private Texture2D mBackground;
    private Texture2D mUniLogo;
    private Vector2 mPos = Vector2.Zero;
    private SoundEffect mHit;
    private SoundEffect mMiss;
    private MouseState mPreviousMouseState;
    private MouseState mCurrentMouseState;
    private double mAngle;
    private Vector2 mPosition = new Vector2(640, 512);



    private float mX = 0;
    private float mY = 0;

    public Game1()
    {
        mGraphics = new GraphicsDeviceManager(this)
        {
            // Change the windows size into 1280x1024
            PreferredBackBufferWidth = 1280,
            PreferredBackBufferHeight = 1024
        };

        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // Set mouse visible
        IsMouseVisible = true;
        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        mSpriteBatch = new SpriteBatch(GraphicsDevice);

        // Load sprites
        mBackground = Content.Load<Texture2D>("Background");
        mUniLogo = Content.Load<Texture2D>("Unilogo");

        mHit = Content.Load<SoundEffect>("Logo_hit");
        mMiss = Content.Load<SoundEffect>("Logo_miss");
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// game-specific content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        mPreviousMouseState = mCurrentMouseState;
        mCurrentMouseState = Mouse.GetState();
       if (mCurrentMouseState.LeftButton == ButtonState.Pressed && mPreviousMouseState.LeftButton != ButtonState.Pressed)
        {
            if (Mouse.GetState().Position.X >= mX && Mouse.GetState().Position.X <= mX + 300 &&
                Mouse.GetState().Position.Y >= mY && Mouse.GetState().Position.Y <= mY + 300)
            {
                mHit.Play();
            }
            else if (new Rectangle(0,0,1280,1024).Contains(Mouse.GetState().X, Mouse.GetState().Y) == true)
            {
                mMiss.Play();
            }
        }


        mAngle -= 0.01;
        mX = (float)Math.Sin(mAngle) * 350;
        mY = (float)Math.Cos(mAngle) * 250;


        base.Update(gameTime);

    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        var viewport = mGraphics.GraphicsDevice.Viewport;
        // Draw our sprites
        mSpriteBatch.Begin();
        mSpriteBatch.Draw(mBackground, new Rectangle(0,0,1280,1024), Color.White);
        mSpriteBatch.Draw(mUniLogo, new Vector2(mX,mY), null, Color.White, 0, new Vector2(512, 512), 0.33f, SpriteEffects.None, 0);
        mSpriteBatch.End();

        base.Draw(gameTime);
    }
}
}

1 ответ

Может быть попробовать что-то подобное? (ПРИМЕЧАНИЕ: это только фрагмент логики столкновений, а не все, что вам может понадобиться.)

Rectangle spriteRect;
MouseState ms, oldms;

protected override void Initialize()
{
    // Set mouse visible
    IsMouseVisible = true;
    spriteRect= new Rectangle(/*foo*/);
    base.Initialize();
}

/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    mSpriteBatch = new SpriteBatch(GraphicsDevice);

}

/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
    // TODO: Unload any non ContentManager content here
}

/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
        Exit();
    ms=Mouse.GetState();
    Rectangle mouseRect= new Rectangle((int)ms.X,(int)ms.Y,1,1);

   if(ms.LeftButton==ButtonState.Pressed && oldms.LeftButton!=ButtonState.Pressed){
if(mouseRect.Intersects(spriteRect))
        {
           //play a sound
        }
else{
//play a different sound
}

    }





    base.Update(gameTime);
    }
}
Другие вопросы по тегам