I'm building a 2D platformer and I want to have different colour backgrounds for each level. I've made an object that when collided with, it places the character onto the next level by changing the player.Position, like so...
protected override void Update(GameTime gameTime){
if (player.Bounds.Intersects(teleportObj.Bounds))
{
GraphicsDevice.Clear(Color.SlateGray); // fails to change bg color
player.Position = new Vector2(172, 0); // successfully changes character position
MediaPlayer.Play(dungeonSong); // successfully plays new song
MediaPlayer.IsRepeating = true; // successfully repeats new song
}
}
I have already set a background for the first level to begin with in the Game1's Draw() function like this:
GraphicsDevice.Clear(Color.CornflowerBlue);
But when my player collides with teleportObj, the background color doesn't change.
GraphicsDevice.Clear(Color.SlateGray); is used in Draw function. Try creating new Color variable, and change that variable in Update method, and when using GraphicsDevice.Clear(name of the variable);, use it in Draw function.
Code for that would look like this:
Color backgroundColor = Color.CornflowerBlue;
protected override void Update(GameTime gameTime)
{
if (player.Bounds.Intersects(teleportObj.Bounds))
{
backgroundColor = Color.SlateGray;
player.Position = new Vector2(172, 0);
MediaPlayer.Play(dungeonSong);
MediaPlayer.IsRepeating = true;
}
else backgroundColor = Color.CornflowerBlue;
}
protected override void Draw(SpriteBatch spriteBatch)
{
GraphicsDevice.Clear(backgroundColor);
*draw other stuff*
}
Related
This is a simple project created from MonoGame Cross-Platform Desktop template. I created a ball Texture2D and tried to make it move.So I added some code to the Update function.
position.X += 3;
And then in the Draw function
_spriteBatch.Begin();
_spriteBatch.Draw(ballTexture, position, Color.White);
_spriteBatch.End();
I can see the ball flashing sometimes.
Why is that and what can I do to make it not skip frames?
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace SimpleTest
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private Texture2D dirtTexture;
private Vector2 position;
private int direction = 1;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
dirtTexture = Content.Load<Texture2D>("dirt");
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// TODO: Add your update logic here
base.Update(gameTime);
if (position.X > 600)
direction = -1;
else if (position.X < 100)
direction = 1;
position.X = position.X + direction * 3;
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
_spriteBatch.Begin();
_spriteBatch.Draw(dirtTexture, position, Color.White);
_spriteBatch.End();
base.Draw(gameTime);
}
}
}
I think base.Update(gameTime); should only be placed at the very end of the Update() Method, Just like base.Draw(gameTime);. That way it won't skip any lines.
I guess your PC might be running slowly which is the problem, and not your code. To test it, you can replace your Draw method as follows:
protected override void Draw(GameTime gameTime)
{
Color color=gameTime.IsRunningSlowly?Color.Red:Color.CornflowerBlue;
GraphicsDevice.Clear(color);
// TODO: Add your drawing code here
_spriteBatch.Begin();
_spriteBatch.Draw(dirtTexture, position, Color.White);
_spriteBatch.End();
base.Draw(gameTime);
}
Everything is the same, except now we are colouring the screen as Red instead of the usual blue only if the game is in fact running slow (Which is due to your PC). We can know this by the gameTime variable as shown in the first two lines of the method. Test it out and see if you can see the game background going red when the "frame-skipping" happens.
I did test your exact code in my PC and it was working fine. Needless to say, I did use some other png I had instead of the "dirt" Texture2D you used but I don't think that it should be necessary.
Perhaps it's due to GC. You could use my -almost- garbage free build to verify.
You can install the updated SDK from here or the nuget package.
I'm creating a game in monogame, and I've loaded tiles in my game inside the Draw() function like so:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(danChar, charPosition, Color.White);
// loop below loads the 'grass' tiles only
// assuming gameworld size of 770x450
for (int i = 0; i < 770; i += 31) // adds 31 to i (per tile)
{
position = new Vector2(i, 392); // places incrementation into vector position
spriteBatch.Draw(gameTile, position, Color.White); // draws the tile each time
if (i == 744)
{
i = i + 26; // fills last space between 744 and 770
position = new Vector2(i, 392);
}
spriteBatch.Draw(gameTile, position, Color.White);
}
// loop below loads the brick tiles only (ones without grass)
spriteBatch.End(); // ends the spriteBatch call
base.Draw(gameTime);
}
However I would prefer that this was a separate class rather than being placed directly into the draw function, however I'm not too sure how to do this and would appreciate any help given.
Thanks in advance!
If you just want to move the code as is to another class, create your class (e.g. something like GameWorld seems to appropriate for your code)
public class GameWorld
{
// You may wish to move your gameTile definition into this class if it is the only
// class that uses it, and handle the content loading for it in here.
// e.g. if you're currently loading the texture in the LoadContent method in your game
// class, create a LoadContent method here and pass in ContentManger as a parameter.
// I've passed in the texture as a parameter to the Draw method in this example to
// simplify as I'm not sure how you're managing your textures.
public void Draw(SpriteBatch spriteBatch, GameTime gameTime, Texture2D gameTile)
{
// loop below loads the 'grass' tiles only
// assuming gameworld size of 770x450
for (int i = 0; i < 770; i += 31) // adds 31 to i (per tile)
{
Vector2 position = new Vector2(i, 392); // places incrementation into vector position
spriteBatch.Draw(gameTile, position, Color.White); // draws the tile each time
if (i == 744)
{
i = i + 26; // fills last space between 744 and 770
position = new Vector2(i, 392);
}
spriteBatch.Draw(gameTile, position, Color.White);
}
// loop below loads the brick tiles only (ones without grass)
}
}
Then the Draw method in your Game class would look like
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(danChar, charPosition, Color.White);
// Assuming you've created/loaded an instance of the GameWorld class
// called gameWorld in Initialize/LoadContent
gameWorld.Draw(spriteBatch, gameTime, gameTile);
spriteBatch.End(); // ends the spriteBatch call
base.Draw(gameTime);
}
Just make sure you're calling the Draw methods in the correct order. e.g. you want your player to appear above any background tiles.
I believe the default SpriteSortMode is Deferred which draws in the order the calls are made (i.e. from the back to the front).
You can specify a different SpriteSortMode in your call to spriteBatch.Begin() if you need to but for a simple game just move the Draw calls around.
More info on SpriteSortMode at MSDN if needed.
Similarly you can chain your Update, LoadContent methods into these classes if you wish, making sure to pass in anything you need as arguments.
Update:
To define gameWorld as an instance of the GameWorld class, you define it near the top of your game class, then typically initialize it in the Initialize method.
So your game class will look something like
public class MyGameName : Microsoft.Xna.Framework.Game
{
private SpriteBatch spriteBatch;
// other variable declarations
// Add a declaration for gameWorld
private GameWorld gameWorld;
protected override Initialize()
{
// Add the following line to initialize your gameWorld instance
gameWorld = new GameWorld();
}
// other existing code - your LoadContent, Update, Draw methods etc.
}
I'm a little noob with XNA and I've encountered a problem. I have one texture called "dot", that I use to draw a line across the screen. Then I have a texture that I call "tool", that I want to move around when I touch it with my finger. The problem I have is that for the tool to be cleared and redrawn I call the graphicsDevice.Clear-method in XNA. But when I do that, my lines also disappears. So my question is how can i move around the tool, without causing my lines to disappear? Is there a way to only redraw the tool, without redrawing the lines? Heres a snippet of my code, first update-method:
protected override void Update (GameTime gameTime)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
TouchCollection touchCollection = TouchPanel.GetState ();
foreach (TouchLocation tl in touchCollection) {
if ((tl.State == TouchLocationState.Pressed) || (tl.State == TouchLocationState.Moved)) {
toolPos = touchCollection [0].Position;
}
}
base.Update (gameTime);
}
And the draw-method:
protected override void Draw (GameTime gameTime)
{
graphics.GraphicsDevice.Clear (Color.Black);
newVector = nextVector (oldVector);
spriteBatch.Begin ();
DrawEvenlySpacedSprites (dot, oldVector, newVector, 0.9f);
spriteBatch.Draw (tool, toolPos, Color.White);
spriteBatch.End ();
oldVector = new Vector2 (newVector.X, newVector.Y);
base.Draw (gameTime);
}
Try using a RenderTarget2D with RenderTargetUsage.PreserveContents. If you didn't use render targets yet, here's a tutorial: http://rbwhitaker.wikidot.com/render-to-texture
All you have to do is to specify RenderTargetUsage.PreserveContents in target's constructor, draw dots to it, and draw the target and tool to the screen. It should look like this:
protected override void Draw (GameTime gameTime)
{
graphics.GraphicsDevice.Clear (Color.Black);
newVector = nextVector (oldVector);
GraphicsDevice.SetRenderTarget(renderTarget);
spriteBatch.Begin ();
DrawEvenlySpacedSprites (dot, oldVector, newVector, 0.9f);
spriteBatch.End ();
GraphicsDevice.SetRenderTarget(null);
spriteBatch.Begin();
spriteBatch.Draw(renderTarget, new Vector2(), Color.White);
spriteBatch.Draw (tool, toolPos, Color.White);
spriteBatch.End()
oldVector = new Vector2 (newVector.X, newVector.Y);
base.Draw (gameTime);
}
I am having a problem retrieving touch input on my XNA game. Here is my starting code:
TouchCollection touchPositions;
List<Vector2> touchReleases = new List<Vector2>();
Then this is my update code:
protected override void Update(GameTime gameTime)
{
// Other update logic here
touchReleases.Clear();
foreach (TouchLocation tl in touchPositions)
{
if (tl.State == TouchLocationState.Released)
touchReleases.Add(tl.Position);
}
base.Update(gameTime);
}
The idea is to load all of the releases into a Vector2 list. Then (during the draw code) a function checks for a release to do stuff.
EDIT: I tested this using Guide.BeginShowMessageBox() during the foreach loop. It popped up every time I released.
bool released = false;
foreach (TouchLocation tl in touchPositions)
{
// checks to see if the button is being hovered on
}
foreach (Vector2 tr in touchReleases)
{
if (PointInArea(tr, new Rectangle((int)position.X, (int)position.Y, buttonimage[0].Width, buttonimage[0].Height)))
{
released = true;
break;
}
}
return released;
The PointInArea function checks to see if a Vector2 is in a Rectangle. I know this function is working right.
What's funny is that the buttons respond to releases about once every 4 taps. Does anyone know why this is?
I'm writing basic graphic editor in WPF using InkCanvas. I've made some custom shapes (inherited from Stroke). When I draw line wen on InkCanvas, I take first and last point and make a line. That works fine, but now I don't like the default "pen stroke" so i decided to rewrite DynamicRenderer to render line in real time.
Problem is, that DynamicRenderer draws line from origin point to every point of stroke and i obviously don't want that, becouse it makes "fan" insted of line.
There is my custom code and I'm looking for solution to draw line from origin point to last point only, if it is possible.
class LineRenderer : DynamicRenderer
{
private Point firstPoint;
private Pen pen = new Pen(new SolidColorBrush(Colors.Gray),1);
public LineRenderer()
{
firstPoint = new Point(double.PositiveInfinity, double.PositiveInfinity);
}
protected override void OnStylusDown(RawStylusInput rawStylusInput)
{
firstPoint = new Point(rawStylusInput.GetStylusPoints().First().ToPoint().X, rawStylusInput.GetStylusPoints().First().ToPoint().Y);
base.OnStylusDown(rawStylusInput);
}
protected override void OnDraw(DrawingContext drawingContext,
StylusPointCollection stylusPoints,
Geometry geometry, Brush fillBrush)
{
drawingContext.DrawLine(pen, firstPoint, stylusPoints.First().ToPoint());
}
protected override void OnStylusUp(RawStylusInput rawStylusInput)
{
firstPoint = new Point(double.PositiveInfinity, double.PositiveInfinity);
base.OnStylusUp(rawStylusInput);
}
}
This is very much late. In order to avoid the "fan" while the stroke is being drawn, try this:
protected override void OnDraw(DrawingContext drawingContext,
StylusPointCollection stylusPoints,
Geometry geometry, Brush fillBrush)
{
if (!_isManipulating)
{
_isManipulating = true;
StylusDevice currentStylus = Stylus.CurrentStylusDevice;
this.Reset(currentStylus, stylusPoints);
}
_isManipulating = false;
var pen = new Pen(brush, 2);
drawingContext.DrawLine(pen, startPoint,stylusPoints.First().ToPoint());
}
protected override void OnStylusDown(RawStylusInput rawStylusInput)
{
StylusPointCollection y = rawStylusInput.GetStylusPoints();
startPoint = (Point)y.First();
// Allocate memory to store the previous point to draw from.
prevPoint = new Point(double.NegativeInfinity, double.NegativeInfinity);
base.OnStylusDown(rawStylusInput);
}
The trick here is to use DynamicRenderer.Reset, which:
Clears rendering on the current stroke and redraws it.
The redraw will reenter the OnDraw method, so _isManipulating provides a simple flag to stop looping.
what i think in your ondraw function your first point is fixed so it always take it as origin so you can try this for continous drawing.
protected override void OnDraw(DrawingContext drawingContext,
StylusPointCollection stylusPoints,
Geometry geometry, Brush fillBrush)
{
drawingContext.DrawLine(pen, firstPoint, stylusPoints.First().ToPoint());
firstPoint = stylusPoints.First().ToPoint();
}
it will update your firstpoint if you get same point exception put a check on it ( or you can define anew point name as previous point and initially make it equal to first point and keep it updating in your ondraw method as i did with first point..
and if you want direct line from first point to last point you can called you on draw method after getting last point from onstylusup method ..hope this might help you..