first of all, i am new to xna. Trying to craete blackjack game. And i have created 2 lists to add random card to the list. But i cannot understand why doesnt it add pics to the list tekstuur2
Heres code :
public class Kaart
{
public Vector2 asukoht = new Vector2(0, 0);
public List<Texture2D> tekstuur = new List<Texture2D>();
public List<Texture2D> tekstuur2 = new List<Texture2D>();
Random rand = new Random();
public void loadContent2(ContentManager manager2)
{
for (int x = 3; x < 7; x++)
tekstuur2.Add(manager2.Load<Texture2D>("Risti" + x.ToString()));
}
public void loadContent(ContentManager manager)
{
for (int j = 3; j < 7; j++)
tekstuur.Add(manager.Load<Texture2D>("Risti" + j.ToString()));
}
public void Draw(SpriteBatch sprite)
{
sprite.Draw(tekstuur[rand.Next(tekstuur.Count)], asukoht, Color.White);
sprite.Draw(tekstuur2[rand.Next(tekstuur2.Count)], asukoht, Color.White);
// an error occurs (ArgumentOutofRangeException) , tekstuur2.count = 0 at that point, but at the tekstuur.Count it is 4.
}
}
}
Heres another class where these methods are called :
namespace WindowsGame1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Vector2 koht = new Vector2(0,0);
Kaart yks;
Kaart kaks;
public Game1()
{
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
yks = new Kaart();
kaks = new Kaart();
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);
//kaardi laadimine
yks.loadContent(this.Content);
kaks.loadContent2(this.Content);
// yhe kaarti asukoht
yks.asukoht.X = 100;
yks.asukoht.Y = 300;
// teise kaardi asukoht
kaks.asukoht.X = 200;
kaks.asukoht.Y = 400;
// 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();
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)
{
// kaartide joonistamine
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
yks.Draw(this.spriteBatch);
kaks.Draw(this.spriteBatch);
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
}
ok the problem is you should call for every instance of Kaart (in your case yks and kaks) loadContent AND loadContent2
this in your method LoadContent:
//kaardi laadimine
yks.loadContent(this.Content);
kaks.loadContent2(this.Content);
become:
//kaardi laadimine
yks.loadContent(this.Content);
yks.loadContent2(this.Content);
kaks.loadContent2(this.Content);
kaks.loadContent(this.Content);
note that since the texture are the same there's no need to use two different list for containing them, you can do this in your Kaart Draw method:
sprite.Draw(tekstuur[rand.Next(tekstuur.Count)], asukoht, Color.White);
sprite.Draw(tekstuur[rand.Next(tekstuur.Count)], asukoht, Color.White);
this way you have to only call LoadContent.
Another note:
at the moment you're instantiating a Random rand; the problem with that is that sequential instantiation of this class (in a short time) is not recommended and your two KArt are going to use the same random texture. To resolve this make the Random rand a static variable:
private static Random rand = new Random();
Related
for my university, we have to start with learning Monogame/XNA on VisualStudio 2015. We have to make a Sprite which rotate in a circle and makes a soundeffect by clicking on it abd a soundeffect by missing it. But i can't figure it out how to make it.
Everything else just works fine (after hours of work).
I would be very thankful for any help.
Thank you in advance.
best regards
Alex.
PS: Sorry for my english :)
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);
}
}
}
Maybe try something like this? (NOTE: this is only a fragment for collision logic, not everything you might need.)
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);
}
}
I'm trying to learn how to implement physics in games, so I chose Farseer Physics. I'm trying to implement the falling round object till the obstacle(ground in my case). Here's my code:
using FarseerPhysics;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
namespace TestFarseer
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
World world;
Texture2D buttonTexture, groundTexture;
Body buttonBody, groundBody;
public Game1()
{
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
world = new World(new Vector2(0, 1f));
ConvertUnits.SetDisplayUnitToSimUnitRatio(102f);
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);
buttonTexture = Content.Load<Texture2D>("pause");
groundTexture = Content.Load<Texture2D>("Panel");
groundBody = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(groundTexture.Width), ConvertUnits.ToSimUnits(groundTexture.Height), 1f);
groundBody.BodyType = BodyType.Static;
groundBody.Position = new Vector2(ConvertUnits.ToSimUnits(groundTexture.Width/2f), ConvertUnits.ToSimUnits(GraphicsDevice.Viewport.Height-groundTexture.Height));
CircleShape buttonShape = new CircleShape(0.5f, 0.8f);
buttonBody = new Body(world);
buttonBody.Mass = 10f;
buttonBody.CreateFixture(buttonShape);
buttonBody.BodyType = BodyType.Dynamic;
buttonBody.Position = new Vector2(ConvertUnits.ToSimUnits(51f), ConvertUnits.ToSimUnits(51f));
// TODO: use this.Content to load your game content here
}
/// <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)
{
// TODO: Add your update logic here
world.Step((float)gameTime.ElapsedGameTime.TotalSeconds);
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(buttonTexture, ConvertUnits.ToDisplayUnits(buttonBody.Position), null, Color.White, buttonBody.Rotation, new Vector2(buttonTexture.Width/2, buttonTexture.Height/2), 1f, SpriteEffects.None, 0);
spriteBatch.Draw(groundTexture, ConvertUnits.ToDisplayUnits(groundBody.Position), null, Color.White, groundBody.Rotation, new Vector2(groundTexture.Width/2, groundTexture.Height/2), 1f, SpriteEffects.None, 0);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
And the collision occur, but I can't set ground to be at bottom. Here's the screenshot:
In Farseer the origin of a body is at the center, so :
groundBody.Position = new Vector2(ConvertUnits.ToSimUnits(groundTexture.Width/2f), ConvertUnits.ToSimUnits(GraphicsDevice.Viewport.Height-(groundTexture.Height / 2)));`
Groover,
Im trying to build a break out game using C# and the XNA framework. I've placed the brick into a seperate class and created an array for 10 bricks to load. However, when I run the game, no bricks are actually appearing and I can't seem to find the error as Visual Studio isn't flagging anything.
Brick class:
class bricks
{
Texture2D brickimg;
Rectangle rectangle;
int[] brickXPos = new int[50];
int[] brickYPos = new int[50];
public bricks(Texture2D NewTexture, Rectangle newRectangle)
{
brickimg = NewTexture;
rectangle = newRectangle;
}
public void Initialize()
{
for (int i = 0; i < 50; i++)
{
brickXPos[i] = 300 + i * 60;
brickYPos[i] = 100;
}
}
public void Update()
{
}
public void Draw(SpriteBatch spritebatch)
{
for (int i = 0; i < 50; i++)
{
spritebatch.Draw(brickimg, new Vector2(brickXPos[i], brickYPos[i]), rectangle, Color.White);
}
}
}
Main program:
/// <summary>
/// This is the main type for your game
/// </summary>
public class Breakout : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D BackgroundImg;
bricks bricks;
public Breakout()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 1024;
graphics.PreferredBackBufferHeight = 768;
graphics.ApplyChanges();
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);
BackgroundImg = Content.Load<Texture2D>("starfield");
bricks = new bricks(Content.Load<Texture2D>("redbrick"),new Rectangle());
// 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
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
base.Draw(gameTime);
spriteBatch.Begin();
spriteBatch.Draw(BackgroundImg, Vector2.Zero, Color.White);
bricks.Draw(spriteBatch);
spriteBatch.End();
}
}
You never Initialise the bricks object.
You need to call bricks.Initialise(); function somewhere (preferably in the initialise function of the Breakout class).
I would also recommend you to use a bit cleaner code standard.
Class names usually start with upper case, ie: Bricks instead of bricks, in your case, the class and the instance of the class have the same name (bricks) which could create confusion and even should create a compiler error (I think?).
(The 'NewTexture' variable in the constructor of the brick class also suffer from bad naming, should probably rather be named newTexture, especially due to the fact that the Rect is called newRectangle, - but this is not a code-review site, so ill leave that issue for now!).
Try passing null into the sourceRectangle parameter of spriteBatch.Draw in your bricks class. I think the rectangle you're passing in is no good.
spritebatch.Draw(brickimg, new Vector2(brickXPos[i], brickYPos[i]), null, Color.White);
Hey guys I really need some help here my spriteBatch keeps returning a NullReference Exception and I don't know what I am doing wrong!? (I am making a brickbreaker game) and whenever my bricks are created inside Game1.cs it works fine but when I move it to Wall.cs (which is where I want to display a pattern of bricks) the game just crashes and gives a NullReference exception. Heres my code:
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 BrickBreaker
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private Paddle paddle;
private Ball ball;
private Texture2D background;
private static int screenWidth = 750;
private static int screenHeight = 600;
private int leftBorder = 20;
private int rightBorder = 28;
private int topBorder = 20;
private readonly int normalBrickResist = 2;
private readonly int normalBrickPoints = 10;
private Wall wall;
//DELETE this shit
private Brick brick;
/// <summary>
/// Contructor for the Game1 class.
/// </summary>
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Read only property for the screen height.
/// </summary>
public static int ScreenHeight
{
get { return screenHeight; }
}
/// <summary>
/// Read only property for the screen width.
/// </summary>
public static int ScreenWidth
{
get { return screenWidth; }
}
/// <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()
{
graphics.PreferredBackBufferHeight = screenHeight;
graphics.PreferredBackBufferWidth = screenWidth;
graphics.ApplyChanges();
paddle = new Paddle(this);
Components.Add(paddle);
wall = new Wall(this);
Components.Add(wall);
ball = new Ball(this, paddle, leftBorder, rightBorder, topBorder, brick);
Components.Add(ball);
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()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
background = Content.Load<Texture2D>("background");
}
/// <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();
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();
Vector2 position = new Vector2(0, 0);
spriteBatch.Draw(background, position, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
public void RemoveComponent(IGameComponent obj)
{
this.Components.Remove(obj);
}
}
}
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 BrickBreaker
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class Wall : Microsoft.Xna.Framework.DrawableGameComponent
{
private Brick brick;
private Brick[,] brickLayout = new Brick[5, 8];
private Game game;
SpriteBatch spriteBatch;
private Texture2D brickImg;
public Wall(Game game)
: base(game)
{
this.game = game;
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Draw(GameTime gameTime)
{
foreach (var item in brickLayout)
{
if (item != null)
{
item.Draw(gameTime);
}
}
base.Draw(gameTime);
}
/// <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)
{
foreach (Brick item in brickLayout)
{
item.Update(gameTime);
}
base.Update(gameTime);
}
/// <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
foreach (var item in brickLayout)
{
if (item != null)
{
item.Initialize();
}
}
base.Initialize();
}
protected override void LoadContent()
{
int x = 0;
int y = 0;
Vector2 startPosition;
for (int i = 0; i < brickLayout.GetLength(0); i++)
{
for (int j = 0; j < brickLayout.GetLength(1); j++)
{
startPosition = new Vector2(x, y);
brickLayout[i, j] = new Brick(game, 20, 1, startPosition);
x += 20;
}
y += 20;
}
base.LoadContent();
}
}
}
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 BrickBreaker
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class Brick : Microsoft.Xna.Framework.DrawableGameComponent
{
enum brickType
{
Regular1,
Regular2,
Regular3,
Regular4,
Regular5,
PowerUp,
Unbreakable
}
private Texture2D brick;
private SpriteBatch spriteBatch;
private Game game;
private int brickValue;
private Vector2 startPosition, position;
private Rectangle collisionBox;
private int brickWidth;
private bool isBroken = false;
private int resistance;
public Brick(Game game, int brickValue, int resistance, Vector2 startPosition)
: base(game)
{
this.brickValue = brickValue;
this.game = game;
this.resistance = resistance;
this.startPosition = startPosition;
}
public Boolean IsBroken
{
get
{
return this.isBroken;
}
set
{
this.isBroken = value;
}
}
/// <summary>
/// Property for the paddle collision box.
/// </summary>
public Rectangle CollisionBox
{
get { return collisionBox; }
}
/// <summary>
/// Read only property for the paddle width.
/// </summary>
public int BrickWidth
{
get { return brickWidth; }
}
/// <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)
{
// TODO: Add your update code here
base.Update(gameTime);
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Draw(GameTime gameTime)
{
if (isBroken == false)
{
spriteBatch.Begin();
spriteBatch.Draw(brick, this.position, Color.White);
spriteBatch.End();
}
base.Draw(gameTime);
}
/// <summary>
/// Comment
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
brick = game.Content.Load<Texture2D>("brick");
collisionBox = new Rectangle(0, 0, brick.Width, brick.Height);
position = startPosition;
collisionBox.X = (int)position.X;
collisionBox.Y = (int)position.Y;
base.LoadContent();
}
public void TakeHit()
{
resistance--;
if (resistance == 0)
IsBroken = true;
}
}
}
Edit: Fixed the old problem by adding this in wall.cs
for (int i = 0; i < brickLayout.GetLength(0); i++)
{
for (int j = 0; j < brickLayout.GetLength(1); j++)
{
startPosition = new Vector2(x, y);
brickLayout[i, j] = new Brick(game, 20, 1, startPosition);
//Added this line:
brickLayout[i, j].Initialize();
x += 45;
}
x = 150;
y += 25;
}
BUT now the collision box isn't working at all.
Look closer at your Brick class. In your wall class you're not initializing spriteBatch, and you're not calling Begin and End
Your LoadContent method needs this:
spriteBatch = new SpriteBatch(GraphicsDevice);
And you need to be sure to call this is your Draw method:
spriteBatch.Begin();
and
spriteBatch.End();
EDIT: You're never calling LoadContent on your brick class which is why spriteBatch never gets initialized. Try:
protected override void LoadContent()
{
int x = 0;
int y = 0;
Vector2 startPosition;
for (int i = 0; i < brickLayout.GetLength(0); i++)
{
for (int j = 0; j < brickLayout.GetLength(1); j++)
{
startPosition = new Vector2(x, y);
brickLayout[i, j] = new Brick(game, 20, 1, startPosition);
// This new line...
brickLayout[i, j].LoadContent();
x += 20;
}
y += 20;
}
base.LoadContent();
}
It's giving NullReferenceException in the Brick class at the SpriteBatch.Begin() line in the Draw method.
I am creating a simple XNA game in which you can move the block around. But the block is not moving on keypress I don't why.
Here's my overall Code:
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D ball;
Texture2D bar;
Vector2 ballPos;
Vector2 barPos;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
// Extend battery life under lock.
InactiveSleepTime = TimeSpan.FromSeconds(1);
}
/// <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
ballPos = new Vector2(10, 10);
barPos=new Vector2(10,GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width - 20);
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()
{
ball = Content.Load<Texture2D>("ball");
bar = Content.Load<Texture2D>("bar");
// 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();
UpdateBarLocation();
// TODO: Add your update logic here
base.Update(gameTime);
}
private void UpdateBarLocation()
{
KeyboardState newState = Keyboard.GetState();
if (newState.IsKeyDown(Keys.Right) && (barPos.Y < GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height))
barPos.Y = barPos.Y + 5;
else if (newState.IsKeyDown(Keys.Left) && (barPos.Y > 2))
barPos.Y = barPos.Y - 5;
}
/// <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(ball,ballPos, Color.White);
spriteBatch.Draw(bar, barPos, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
You can see that in the updateBarLocation function i am trying to move the bar but it is not working.
What is the resolution of screen?
This is line is ambiguous
barPos=new Vector2(10,GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width - 20);
First parameter is x axis and second is y axis.
So Width is usually dealt in x-axis.
Are you sure what you are assigning is alright?
If yes then where on the screen is bar located initially?
But the block is not moving on keypress I don't why.
you are not even updating the Block's position