Sound Buttons don't play sound - c#

I'm making a program where one clicks buttons to create sound, like those instant button apps. But when I click the button, it won't play any sound. I don't know why either.
All my "Build" debugs are succeeding too.
These are my classes:
Game1.cs:
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D Background;
Button button;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
this.Window.Title = "Bengt Slår På Knappar";
graphics.PreferredBackBufferHeight = 720;
graphics.PreferredBackBufferWidth = 1280;
IsMouseVisible = true;
}
/// <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()
{
// TODO: Add your initialization logic here
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()
{
Background = Content.Load<Texture2D>("bengtbakgrund");
Texture2D Btexture = Content.Load<Texture2D>("Button");
SoundEffect dundundun = Content.Load<SoundEffect>("DUN DUN DUN");
button = new Button(dundundun, Btexture);
spriteBatch = new SpriteBatch(GraphicsDevice);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all 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)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
Rectangle mouseRect = new Rectangle(Mouse.GetState().X, Mouse.GetState().Y, 10, 10);
MouseState mouseState = Mouse.GetState();
if (mouseRect.Intersects(button.rect) && mouseState.LeftButton == ButtonState.Pressed)
{
button.MySound.Play();
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(Background, new Vector2(0,0), Color.White);
button.Draw(spriteBatch, new Vector2(300, 300));
spriteBatch.End();
base.Draw(gameTime);
}
}
Button.cs:
public class Button
{
Texture2D Texture { get; set; }
public SoundEffect MySound { get; set; }
public Rectangle rect;
public Button(SoundEffect mySound, Texture2D texture)
{
MySound = mySound;
Texture = texture;
}
public void LoadContent(ContentManager Content)
{
}
public void Update(GameTime gameTime)
{
}
public void Draw(SpriteBatch spriteBatch, Vector2 location)
{
Rectangle rect = new Rectangle((int)0, (int)0, Texture.Width, Texture.Height);
spriteBatch.Draw(Texture, location, Color.White);
}
}
What I'm trying to do is have one base button class, so if you want to add a new button with a sound, you just write: button = new Button(//sound effect, //texture);
But I can't get it to work. Any help would be appreciated.

The way you are handling your buttons position is incorrect, and I am not sure how it compiles. In your draw method you define a local variable rect that already exists. And even if it did, you are not taking into account the actual position of the button.
I think you could also move your button update logic into the class, so I will propose what I think you need to do.
public class Button
{
//Properties
private Texture2D Texture { get; set; }
private SoundEffect Sound { get; set; }
private Rectangle Rectangle { get; set; }
public Button(SoundEffect sound, Texture2D texture, Rectangle position)
{
Sound = sound;
Texture = texture;
Rectangle = position;
}
public void Update(GameTime gameTime, MouseState mouseState)
{
//If mouse is down and the rectangle contains the mouse point (Better for points than Intersect())
if (mouseState.LeftButton == ButtonState.Pressed && Rectangle.Contains(new Point(mouseState.X,mouseState.Y))
{
Sound.Play()
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, rectangle, Color.White);
}
}
You can then just do button.Update(Mouse.GetState()) (Or use another MouseState if you have one already)
It appears there was some confusion with the drawing position, vs the actual position of the button (in the draw method)
You need to make sure the button is aware of its position on the screen, as well as it's width and height.
button = new Button(dundundun, Btexture, new Rectangle(300, 300, Btexture.Width, Btexture.Height);
That will make the button at 300,500 and be the default size for the texture, now your sound button is done done done :)
I would also recommend learning and using event handlers, so you can add events for the button such as button.Click += //Do something easily

Related

XNA objects not drawing

So I have a problem that I cant figure out, and that is drawing objects into my main Game1 class from a class of drawablegamecomponent.
I'v been playing around with it for a bit and looking at other examples, but can't figure out the issue. There isn't much code as it is, so I'll just post the two classes I have, the main class Game1 and the class I want to draw, Balloon.
The error is in the draw method I get this...
An unhandled exception of type 'System.NullReferenceException' occurred in Burst.exe
Additional information: Object reference not set to an instance of an object.
Main Class.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Burst
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Rectangle bounds;
Balloon ball;
Diamond dia;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 1152;
graphics.PreferredBackBufferHeight = 648;
Content.RootDirectory = "Content";
bounds = new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
ball = new Balloon(bounds, 1, this, spriteBatch);
dia = new Diamond(bounds, new Vector2(200, 200), this, spriteBatch);
}
/// <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()
{
// TODO: Add your initialization logic here
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.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all 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)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
ball.Update();
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);
spriteBatch.Begin();
// TODO: Add your drawing code here
ball.Draw(gameTime);
dia.Draw(gameTime);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Balloon Class:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Burst
{
public class Balloon : Microsoft.Xna.Framework.DrawableGameComponent
{
Vector2 position;
Vector2 motion;
Texture2D texture;
Rectangle bounds;
Rectangle screenBounds;
Game game;
SpriteBatch spriteBatch;
float balloonSpeed = 4;
int colour = 0;
public Balloon(Rectangle screenBounds, int colour, Game game, SpriteBatch spriteBatch) : base (game)
{
this.colour = colour;
this.game = game;
this.spriteBatch = spriteBatch;
this.screenBounds = screenBounds;
this.position = new Vector2(200,200);
}
protected override void LoadContent()
{
switch (colour)
{
case 1: texture = Game.Content.Load<Texture2D>("Images/BlueBalloon");
break;
case 2: texture = Game.Content.Load<Texture2D>("Images/GreenBalloon");
break;
case 3: texture = Game.Content.Load<Texture2D>("Images/RedBalloon");
break;
case 4: texture = Game.Content.Load<Texture2D>("Images/YellowBalloon");
break;
case 5: texture = Game.Content.Load<Texture2D>("Images/PurpleBalloon");
break;
}
}
public Rectangle Bounds
{
get
{
bounds.X = (int)position.X;
bounds.Y = (int)position.Y;
return bounds;
}
}
public void Update()
{
position += motion * balloonSpeed;
}
private void CheckWallColision()
{
if (position.X < 0)
{
position.X = 0;
motion.X *= -1;
}
if (position.X + texture.Width > screenBounds.Width)
{
position.X = screenBounds.Width - texture.Width;
motion.X *= -1;
}
if (position.Y < 0)
{
position.Y = 0;
motion.Y *= -1;
}
if (position.Y + texture.Height > screenBounds.Height)
{
position.Y = screenBounds.Height - texture.Height;
motion.Y *= -1;
}
}
public void SetStartPosition()
{
Random rand = new Random();
motion = new Vector2(rand.Next(2, 6), -rand.Next(2, 6));
motion.Normalize();
position = new Vector2(200, 300);
}
public void Draw()
{
spriteBatch.Draw(texture, position, Color.White);
}
}
}
"spriteBatch" == null when you create objects "ball" and "dia".
You need move this code:
bounds = new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
ball = new Balloon(bounds, 1, this, spriteBatch);
dia = new Diamond(bounds, new Vector2(200, 200), this, spriteBatch);
to method "LoadContent". After creating "spriteBatch".

C# Monogame snake game

Well first i must say i am a complete noob, I just started with 2d graphics and i experiment on a snake game, in the Update method i call snakeUpdate which updates the position according the keystate the thing is it never updates the position, someone explain a bit please.
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Utilities;
namespace SnakeGame1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private Texture2D background;
private Texture2D shuttle;
private Texture2D earth;
KeyboardState newState = new KeyboardState();
KeyboardState oldState = new KeyboardState();
private float angle = 0;
public Vector2 position= new Vector2(480,240);
public Vector2 velocity;
public Game1()
: base()
{
graphics = new GraphicsDeviceManager(this);
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()
{
// TODO: Add your initialization logic here
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.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
background = Content.Load<Texture2D>("stars.jpg"); // change these names to the names of your images
shuttle = Content.Load<Texture2D>("shuttle.png"); // if you are using your own images.
earth = Content.Load<Texture2D>("earth.png");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all 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();
listener();
snakeUp();
// TODO: Add your update logic here
//angle += 0.01f;
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);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.White);
spriteBatch.Draw(earth, new Vector2(400, 240), Color.WhiteSmoke);
Vector2 origin = new Vector2(0, 0);
spriteBatch.Draw(shuttle, position, new Rectangle(0,0, shuttle.Width, shuttle.Height), Color.White, angle, origin, 0.5f, SpriteEffects.None, 1);
spriteBatch.End();
base.Draw(gameTime);
}
public void listener()
{
if (newState.IsKeyDown(Keys.Right) && (oldState.IsKeyUp(Keys.Right)))
velocity = new Vector2(3, 0);
if (newState.IsKeyDown(Keys.Left) && (oldState.IsKeyUp(Keys.Left)))
velocity = new Vector2(-3, 0);
if (newState.IsKeyDown(Keys.Down) && (oldState.IsKeyUp(Keys.Down)))
velocity = new Vector2(0, 3);
if (newState.IsKeyDown(Keys.Up) && (oldState.IsKeyUp(Keys.Up)))
velocity = new Vector2(0, -3);
}
public void snakeUp() {
position += velocity;
}
}
}
You're not assigning oldState and newState correctly: you're initializing those variables (incorrectly) only one time when Game1 is instantiated. You'll need something like this:
public class Game1 : Game {
KeyboardState oldState = Keyboard.GetState();
KeyboardState newState = Keyboard.GetState();
// ...
protected override void Update(GameTime gameTime) {
oldState = newState;
newState = Keyboard.GetState();
// ...
}
}
You are not updating your keyboard state. Write something like this inside your Update method (before listener):
oldState = newState;
newState = Keyboard.GetState();

Error with constructor when inheriting using a base class

Hey im new to c# and XNA. My goal is to inherit from a Sprite class and make classes such as pongSprite, paddleSprite etc... Im getting an error on my constructor. I have extended the sprite class and i have put the variables and objects from the Sprite class into the :base()
Here is my code:
**
Sprite.cs
**
namespace SimplePong
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class Sprite : DrawableGameComponent
{
protected string id;
protected Texture2D texture;
//bounding box
//protected Rectangle sourceRectangle;
protected Rectangle destinationRectangle;
protected Color color;
protected Main game;
private Sprite pongBall;
public Sprite(Main game, string id, Texture2D texture,
Rectangle destinationRectangle, Color color)
: base(game)
{
this.game = game;
this.id = id;
this.texture = texture;
this.destinationRectangle = destinationRectangle;
this.color = color;
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
// TODO: Add your initialization code here
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
game.spriteBatch.Begin();
game.spriteBatch.Draw(texture, destinationRectangle, color);
game.spriteBatch.End();
base.Draw(gameTime);
}
}
}
**
ballSprite.cs
**
using Microsoft.Xna.Framework;
namespace SimplePong
{
public class BallSprite : Sprite
{
// public Main game;
public Sprite pongBall;
public BallSprite()
: base(Main game, string id, Texture2D texture,
Rectangle destinationRectangle, Color color)
{
}
public override void Initialize()
{
base.Initialize();
}
public override void Update(GameTime gameTime)
{
destinationRectangle.X += 2;
destinationRectangle.Y += 2;
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
}
}
}
The syntax of the constructor your inherited class is wrong. I suspect you want:
public BallSprite(Main game, string id, Texture2D texture,
Rectangle destinationRectangle, Color color)
: base(game, id, texture, destinationRectangle, color)
{
}
If you want a parameterless constructor then you're going to have to come up with the values for the parameters yourself (or not call the base constructor).

XNA - The name 'ball' does not exist in the current context

I'm working on a pong game since I'm pretty new to XNA, and I've ran into a problem...
i have 3 classes, "Game1.cs", "Ball.cs", and "GreenPaddle.cs".
The GreenPaddle.cs contains Rectangle gpRect, Texture2D gPtexture, Vector2 position.
I have movement and such, and in the ball class I have an intersect boolean.
But when i try to initialize it in game1.cs i get errors. Here are the classes:
GreenPaddle.cs:
public class GreenPaddle
{
Texture2D gPtexture;
public Vector2 position;
public Rectangle gpRect;
public Vector2 origin;
public int speed = 2;
public GreenPaddle()
{
}
public void LoadContent(ContentManager Content)
{
gPtexture = Content.Load<Texture2D>("greenpaddle");
position = new Vector2(20, 200);
gpRect = new Rectangle((int)position.X, (int)position.Y,
gPtexture.Width, gPtexture.Height);
}
public void Update(GameTime gameTime)
{
KeyboardState keyState = Keyboard.GetState();
//Movement
PaddleMovement();
//Border Collision
isCollidingWithBorders();
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(gPtexture, position, gpRect, Color.LawnGreen);
}
public Boolean isCollidingWithBorders()
{
if (position.Y < 83 && gpRect.Y < 83)
{
position.Y = 83;
gpRect.Y = 83;
return true;
}
if (position.Y > 400 && gpRect.Y > 400)
{
position.Y = 400;
gpRect.Y = 400;
return true;
}
else { return false; }
}
public void PaddleMovement()
{
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.W))
{
position.Y -= speed;
gpRect.Y -= speed;
}
if (keyState.IsKeyDown(Keys.S))
{
position.Y += speed;
gpRect.Y += speed;
}
}
}
Ball.cs:
public class Ball
{
GreenPaddle gPaddle;
Texture2D ballTexture;
Vector2 ballPosition;
Rectangle ballRect;
int speed = 2;
bool movingUp, movingLeft;
public Ball(GreenPaddle paddle)
{
this.gPaddle = paddle;
movingLeft = true;
movingUp = true;
}
public void LoadContent(ContentManager Content)
{
ballTexture = Content.Load<Texture2D>("ball");
ballPosition = new Vector2(380, 225);
ballRect = new Rectangle((int)ballPosition.X, (int)ballPosition.Y,
ballTexture.Width, ballTexture.Height);
}
public void Update(GameTime gameTime)
{
BallMovement();
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(ballTexture, ballPosition, ballRect, Color.White);
}
public void BallMovement()
{
if (movingUp) { ballPosition.Y -= speed; }
if (!movingUp) { ballPosition.Y += speed; }
if (movingLeft) { ballPosition.X -= speed; }
if (!movingLeft) { ballPosition.X += speed; }
if (ballRect.Intersects(gPaddle.gpRect))
movingLeft = !movingLeft;
movingUp = !movingUp;
if (ballPosition.Y < 85)
{
movingUp = false;
}
}
}
Game1.cs:
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
GreenPaddle gPaddle = new GreenPaddle();
Texture2D BackGround;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferHeight = 500;
}
protected override void Initialize()
{
Ball ball = new Ball(gPaddle);
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.
spriteBatch = new SpriteBatch(GraphicsDevice);
BackGround = Content.Load<Texture2D>("pongBG");
gPaddle.LoadContent(Content);
//ball.LoadContent(Content);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all 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)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
gPaddle.Update(gameTime);
ball.Update(gameTime);//Error Line
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);
spriteBatch.Begin();
spriteBatch.Draw(BackGround, new Vector2(0f, 0f), Color.White);
gPaddle.Draw(spriteBatch);
ball.Draw(spriteBatch);//Error Line
spriteBatch.End();
base.Draw(gameTime);
}
}
Thats it, I don't know what to do with the initialize part :/
Look carefully how you initialize your ball, you declare it in the scope of the method (Between the braces). This means you cannot access it anywhere else, which you are trying to do in the Update and Draw methods.
protected override void Initialize()
{
Ball ball = new Ball(gPaddle);
base.Initialize();
}
Additionally, as soon as the function ends your Ball object is deleted.
This can be fixed by putting Ball ball into your class scope so that it is available to all members of the class, like so:
Ball ball; //In the class scope
protected override void Initialize()
{
ball = new Ball(gPaddle);
base.Initialize();
}
If your not familiar with scopes, check out this article (Nothing really good on MSDN)

lander of game, not landing on the landing pad but passing through

i want to get the lander of this xna game to successfully touchdown on the landing pad, and then play the sound, however, it passes right through and the sound still plays. the complete code for this is:
namespace MoonLander
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class BasicLunarLander : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SoundEffectInstance EndGameSoundInstance;
Texture2D BackgroundImage;
Texture2D LandingImage;
SoundEffect EndGameSound;
int LanderPosX;
int LanderPosY;
Texture2D LandingPadImage;
public BasicLunarLander()
{
graphics = new GraphicsDeviceManager(this);
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()
{
// TODO: Add your initialization logic here
LanderPosX = 100;
LanderPosY = 0;
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.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
BackgroundImage = Content.Load<Texture2D>("background");
LandingImage = Content.Load<Texture2D>("lander");
LandingPadImage = Content.Load<Texture2D>("landingpad");
EndGameSound = Content.Load<SoundEffect>("crowdcheer");
EndGameSoundInstance = EndGameSound.CreateInstance();
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all 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)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if (Keyboard.GetState().IsKeyDown(Keys.Down))
{
LanderPosY = LanderPosY + 2;
}
if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
LanderPosY = LanderPosY - 2;
}
if (Keyboard.GetState().IsKeyDown(Keys.Left))
{
LanderPosX = LanderPosX - 2;
}
if (Keyboard.GetState().IsKeyDown(Keys.Right))
{
LanderPosX = LanderPosX + 2;
}
// TODO: Add your update logic here
Rectangle rectLander = new Rectangle(LanderPosX, LanderPosY, LandingImage.Width, LandingImage.Height);
Rectangle rectLandingPad = new Rectangle(350, 500, LandingPadImage.Width, LandingPadImage.Height);
if (rectLander.Intersects(rectLandingPad))
{
EndGameSoundInstance.Play();
}
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)
{
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(BackgroundImage, Vector2.Zero, Color.White);
spriteBatch.Draw(LandingImage, new Vector2(LanderPosX, LanderPosY), Color.White);
spriteBatch.Draw(LandingPadImage, new Vector2(350,500), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Hope you can help me with this issue, thank you all for your time.
Its because you're not doing anything about preventing movement after the lander has landed (the condition has been met). The sound plays of course, because that is what you did code.
Add a variable detecting if it has landed and declare it inside your class
bool _hasLanded = false;
then wrap the key detection in your update method (for up, down, left and right keys) inside and if:
if(!_hasLanded)
{
//keypresses go here
}
and finally, inside your if where you check to see if the rectangles intersect, add
_hasLanded = true;
That should prevent you from being able to move the lander once it has touched the landing pad.

Categories