I just want to add a background image in my c# monogame main menu. I already have a main menu with buttons and a working game. Just the background is missing.
This is a part of my code:
public void LoadAssets()
{
background = ScreenManager.Texture("background");
[...] //unimportant stuff for this problem
}
public void Draw(GameTime gameTime)
{
SpriteBatch spriteBatch= new SpriteBatch();
spriteBatch.Begin();
spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.White);
spriteBatch.End();
foreach (var button in mButtons)
{
button.Draw(ScreenManager.mSprites);
}
}
I get the following error CS7036 C# There is no argument given that corresponds to the required formal parameter of "graphicsDevice" from "SpriteBatch.SpriteBatch(GraphicsDevice).
I included the image in content. I don't know where is my error.
Thanks, for help!
First, you do NOT create a new SpriteBatch instance each draw call. That would be like 60 new instances per second (at 60fps)
Instead, you create it in your LoadContent() method and use it all the way in your Draw()
method:
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
[...]
}
Second, GraphicsDevice is definetly available in your Draw-Call as long as you have not messed something up really bad ;)
Related
I am trying to make a very simple game for learning purposes, but i am struggling with SharpDX.
Basically what i'm trying to achieve is: Take several bitmap images and display them in a window on certain x y coordinates. After that, i will clear the window a display those images again, but on different x y coordinates (a very basic game loop basically, which means the images will be re-displayed many times per second).
I have this code:
using SharpDX;
using SharpDX.Toolkit;
internal sealed class MyGame : Game
{
private readonly GraphicsDeviceManager _graphicsDeviceManager;
public MyGame()
{
_graphicsDeviceManager = new GraphicsDeviceManager(this);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
base.Draw(gameTime);
}
}
-------
public partial class MainWindow : Window
{
public MainWindow()
{
using (var game = new MyGame())
game.Run();
}
}
When compiled, it simply opens a window with a blue background.
Then, I have two images:
var img = new BitmapImage(new Uri("C:/img/pic1.png"));
var img1 = new BitmapImage(new Uri("C:/img/pic2.png"));
And this is where the problem lies, i am unable to figure out, how to take these two images and actually display them in the window. img should be displayed at x10 y50 coordinates (or in other words, 10 pixels from the left side of the window, and 50 pixels from the top) and img1 at x200 y150 coordinates.
I'm sure the solution is something easy, but I just can't figure it out.
Inside MyGame.
Firstly, in LoadContent method load the texture:
private Texture2D myTexture;
protected override void LoadContent()
{
this.myTexture = this.Content.Load<Texture2D>("Path to img");
}
then in Draw;
protected override void Draw(GameTime gameTime)
{
var sprite = new SpriteBatch(this.GraphicsDevice);
sprite.Begin();
sprite.Draw(this.myTexture,
new Rectangle(10, 50, // position: x and y coordiantes in pixels
/* width and height below
- do not remeber order: */
25, 25),
Color.White);
sprite.End();
base.Draw(gameTime);
}
This is the basic way to draw anything with SharpDX.
I'm running into an issue where I cannot seem to get any of my textures to be recognized anywhere outside of the loadContent method.
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Texture2D tileStart = Content.Load<Texture2D>("tile_start");
Texture2D tileCrossJunction = Content.Load<Texture2D>("tile_crossjunction");
Texture2D tileTJunction = Content.Load<Texture2D>("tile_t-junction");
Texture2D tileCorner = Content.Load<Texture2D>("tile_corner");
Texture2D tileHallway = Content.Load<Texture2D>("tile_hallway");
Texture2D tileDeadEnd = Content.Load<Texture2D>("tile_deadend");
Texture2D sqrPlayer = Content.Load<Texture2D>("sqr_player");
Texture2D sqrBaddieSmall = Content.Load<Texture2D>("sqr_baddie_small");
Texture2D sqrBaddie = Content.Load<Texture2D>("sqr_baddie");
Texture2D sqrBaddieLarge = Content.Load<Texture2D>("sqr_baddie_large");
}
No problems in this method, but when I try to reference any of these textures in my Draw method...
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.DarkGray);
base.Draw(gameTime);
spriteBatch.Begin();
spriteBatch.Draw(tileStart, new Vector2(0,0), Color.White);
spriteBatch.End();
}
I get the error "tileStart does not exist in the current context."
Normally, I would say that it isn't being recognized because tileStart is a variable being declared within the LoadContent method and therefore wouldn't be usable anywhere else. The reason I'm confused is that every tutorial I've read shows this exact syntax and it seems to work fine in those cases, so clearly there's something else going on here that I don't understand.
Any help you guys can provide would be greatly appreciated, thanks.
In C#, the "scope" of variables is well defined. In your code, the textures are created within the scope of the method "LoadContent" and then are deleted once the method is done. What you need to do is place the textures at a "class" level like so:
//outside of the method, and in general, should be placed near the top of the class
Texture2D tileStart;
Texture2D tileCrossJunction;
Texture2D tileTJunction;
Texture2D tileCorner;
Texture2D tileHallway;
Texture2D tileDeadEnd;
Texture2D sqrPlayer;
Texture2D sqrBaddieSmall;
Texture2D sqrBaddie;
Texture2D sqrBaddieLarge;
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
//be sure to remove Texture2D from these
//this will insure that the "class" level variables are called
tileStart = Content.Load<Texture2D>("tile_start");
tileCrossJunction = Content.Load<Texture2D>("tile_crossjunction");
tileTJunction = Content.Load<Texture2D>("tile_t-junction");
tileCorner = Content.Load<Texture2D>("tile_corner");
tileHallway = Content.Load<Texture2D>("tile_hallway");
tileDeadEnd = Content.Load<Texture2D>("tile_deadend");
sqrPlayer = Content.Load<Texture2D>("sqr_player");
sqrBaddieSmall = Content.Load<Texture2D>("sqr_baddie_small");
sqrBaddie = Content.Load<Texture2D>("sqr_baddie");
sqrBaddieLarge = Content.Load<Texture2D>("sqr_baddie_large");
}
Once you have done that, the "scope" of the variables will be at the class level, and you will be able to use them from other methods within the class.
In other words, there is no way to access a variable that is declared within a method from outside of that method (without passing it as a parameter to another method of course), the tutorials you are looking at might just be short hand, and expecting you to do it "properly".
I've been fighting with this problems for days now, browsing through the net, yet nothing helped me solve it: I'm creating a MonoGame application on Visual Studio 2012, yet when trying to load a texture I get the following problem:
Could not load Menu/btnPlay asset!
I have set content directory: Content.RootDirectory = "Assets"; Also the file btnPlay.png has properties set: Build Action: Content and Copy to Output directory: Copy if newer.
My constructor and LoadContent functions are totally empty, but have a look yourself:
public WizardGame()
{
Window.Title = "Just another Wizard game";
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Assets";
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
_spriteBatch = new SpriteBatch(GraphicsDevice);
Texture2D texture = Content.Load<Texture2D>("Menu/btnPlay");
_graphics.IsFullScreen = true;
_graphics.ApplyChanges();
}
I would be glad for any help! I'm totally desperate about the problem....
Under VS2012, Windows 8 64-bits and latest MonoGame as of today (3.0.1) :
create a subfolder named Assets
set Copy to Output to anything else than Do not copy
prepend assets to your texture path when loading it
namespace GameName2
{
public class Game1 : Game
{
private Texture2D _texture2D;
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
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
_texture2D = Content.Load<Texture2D>("assets/snap0009");
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(_texture2D, Vector2.Zero, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Here's your texture drawn :D
Note:
By convenience I kept the original value that the content's root directory points to : Content.
However, you can also directly specify Assets in the path:
Content.RootDirectory = #"Content\Assets";
Then load your texture without prepending Assets to its path:
_texture2D = Content.Load<Texture2D>("snap0009");
I know this question has been asked many times before. However, all solutions I have found after over an hour of googling are essentially the same thing. Everyone says that in order to resize a window in XNA you simply add the following lines of code(or some slight variation of these lines of code) to your Initiate() method in the Game1 class:
//A lot of people say that the ApplyChanges() call is not necessary,
//and equally as many say that it is.
graphics.IsFullScreen = false;
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 600;
graphics.ApplyChanges();
This does not work for me. The code compiles, and runs, but absolutely nothing changes. I've been scouring the documentation for the GraphicsDevice and GraphicsDeviceManager classes, but I have been unable to find any information indicating that I need to do anything other than the above.
I am also fairly sure my graphics card is sufficient(ATI HD 5870), although it appears that the wiki entry on XNA graphics card compatibility has not been updated for a while.
I'm running on Windows 7, with the above graphics card, Visual C# 2010 Express, and the latest version of XNA.
So I'm just hoping that someone can help me find where I am messing up. I will post my entire Game1 class(I renamed it MainApp) below. If anyone would like to see any of the other classes that are called on, ask and I'll post them.
public class MainApp : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player player;
public MainApp()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
player = new Player();
//This does not do ANYTHING
graphics.IsFullScreen = false;
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 600;
graphics.ApplyChanges();
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X,
GraphicsDevice.Viewport.TitleSafeArea.Y
+ 2*(graphics.GraphicsDevice.Viewport.TitleSafeArea.Height / 3));
player.Initialize(Content.Load<Texture2D>("basePlayerTexture"),
playerPosition);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
player.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
P.S. This is my second day with C#, so if this is due to a really stupid error I apologize for wasting your time.
It is frustrating that (as you say) "A lot of people say that the ApplyChanges() call is not necessary, and equally as many say that it is" -- the fact of the matter is that it depends on what you are doing and where you are doing it!
(How do I know all this? I've implemented it. See also: this answer.)
When you are setting the initial resolution when your game starts up:
Do this in your constructor (obviously if you rename Game1, do it in your renamed constructor!)
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferWidth = 800;
}
// ...
}
And do not touch it during Initialize()! And do not call ApplyChanges().
When Game.Run() gets called (the default template project calls it in Program.cs), it will call GraphicsDeviceManager.CreateDevice to set up the initial display before Initialize() is called! This is why you must create the GraphicsDeviceManager and set your desired settings in the constructor of your game class (which is called before Game.Run()).
If you try to set the resolution in Initialize, you cause the graphics device to be set up twice. Bad.
(To be honest I'm surprised that this causes such confusion. This is the code that is provided in the default project template!)
When you are modifying the resolution while the game is running:
If you present a "resolution selection" menu somewhere in your game, and you want to respond to a user (for example) clicking an option in that menu - then (and only then) should you use ApplyChanges. You should only call it from within Update. For example:
public class Game1 : Microsoft.Xna.Framework.Game
{
protected override void Update(GameTime gameTime)
{
if(userClickedTheResolutionChangeButton)
{
graphics.IsFullScreen = userRequestedFullScreen;
graphics.PreferredBackBufferHeight = userRequestedHeight;
graphics.PreferredBackBufferWidth = userRequestedWidth;
graphics.ApplyChanges();
}
// ...
}
// ...
}
Finally, note that ToggleFullScreen() is the same as doing:
graphics.IsFullScreen = !graphics.IsFullScreen;
graphics.ApplyChanges();
The GraphicsDevice.Viewport width and height by default on my computer is 800x480, try setting a size above that that will be noticeable - like 1024x768.
graphics.PreferredBackBufferHeight = 768;
graphics.PreferredBackBufferWidth = 1024;
graphics.ApplyChanges();
The above code in Initialize was sufficient to expand the window for me.
I'm a c++ programmer trying out c#. I've done a lot with box2d in c++, but this is my first time with c#. So, I'm trying to make a simple game with farseer physics engine. When I try to compile my code (I'm using visual studio c# 2010 express and xna game studio 4.0), it stops in body.cs at IBroadPhase broadPhase = World.ContactManager.BroadPhase; With this error: nullreferenceexception was unhandled. I believe the problem is in my Player class, so here's the code for that:
public class Player : Entity
{
Vector2 position;
SpriteBatch spriteBatch;
Texture2D texture;
Rectangle rectangle;
Body body;
CircleShape shape;
Fixture fixture;
public Player()
{
// TODO: Construct any child components here
}
///
/// 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.
///
public override void Initialize(World world, SpriteBatch spriteBatch, Texture2D texture)
{
// TODO: Add your initialization code here
this.spriteBatch = spriteBatch;
this.texture = texture;
rectangle = new Rectangle(0, 0, 11, 14);
body = BodyFactory.CreateBody(world);
body.BodyType = BodyType.Dynamic;
body.Position = new Vector2(0, 0);
shape = new CircleShape(1.0f, 1.0f);
fixture = body.CreateFixture(shape);
base.Initialize(world, spriteBatch, texture);
}
///
/// Allows the game component to update itself.
///
/// <param name="gameTime" />Provides a snapshot of timing values.
public override void Update(GameTime gameTime)
{
// TODO: Add your update code here
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
spriteBatch.Draw(texture, new Vector2(body.WorldCenter.X * 10, body.WorldCenter.Y * 10), rectangle, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
The farseer testbed runs fine, so I'm pretty sure my code is the problem, and not farseer. Let me know if you need to see more of my code. I've also posted this in the farseer forums, so If I get an answer there, I'll let you guys know. Thanks in advance.
Someone asked me to show the code of Game1.cs, and found the problem. The problem was that I had never constructed the world before initializing my player. It was fixed by adding world = new World(Vector2.Zero); before I initialized the player.