I'm using C# and XNA and I would like to make a scrolling background in my game.
I'm trying to figure out what the best way to implement a scrolling texture that moves in some direction indefinitely. Let's say a space background with stars. So, when ship moves do does the texture, but in opposite direction. Kinda like in "tiling" mode.
My only guess so far is to render two textures which are, let's say moving left, and then just make the most left one jump to right when it's beyond visibility or something similar to this.
So, I was wondering is there some simple way to do it in XNA, maybe some render mode, or is the way I described it is good enough? I just don't want to overcomplicate things. I obviously tried to google first, but found pretty much nothing, but it is strange considering that many games use similar techniques too.
Theory
A scrolling background image is easy to implement with the XNA SpriteBatch class. There are several overloads of the Draw method which let the caller specify a source rectangle. This source rectangle defines the section of the texture that is drawn to the specified destination rectangle on screen:
Changing the position of the source rectangle will change the section of the texture displayed in the destination rectangle.
In order to have the sprite cover the whole screen use the following destination rectangle:
var destination = new Rectangle(0, 0, screenWidth, screenHeight);
If the whole texture should be displayed use the following destination rectangle:
var source = new Rectangle(0, 0, textureWidth, textureHeight);
Than all you have to do is animate the source rectangle's X and Y coordinates and you are done.
Well, almost done. The texture should start again even if the source rectangle moves out of the texture area. To do that you have to set a SamplerState that uses texture wrap. Fortunately the Begin method of the SpriteBatch allows the usage of a custom SamplerState. You can use one of the following:
// Either one of the three is fine, the only difference is the filter quality
SamplerState sampler;
sampler = SamplerState.PointWrap;
sampler = SamplerState.LinearWrap;
sampler = SamplerState.AnisotropicWrap;
Example
// Begin drawing with the default states
// Except the SamplerState should be set to PointWrap, LinearWrap or AnisotropicWrap
spriteBatch.Begin(
SpriteSortMode.Deferred,
BlendState.Opaque,
SamplerState.AnisotropicWrap, // Make the texture wrap
DepthStencilState.Default,
RasterizerState.CullCounterClockwise
);
// Rectangle over the whole game screen
var screenArea = new Rectangle(0, 0, 800, 600);
// Calculate the current offset of the texture
// For this example I use the game time
var offset = (int)gameTime.TotalGameTime.TotalMilliseconds;
// Offset increases over time, so the texture moves from the bottom to the top of the screen
var destination = new Rectangle(0, offset, texture.Width, texture.Height);
// Draw the texture
spriteBatch.Draw(
texture,
screenArea,
destination,
Color.White
);
Microsoft has a XNA tutorial that does exactly this, you can grab the source code and read up on the actual programming logic behind a scrolling background. Bonus points they do parallax scrolling for a nice effect.
Link: http://xbox.create.msdn.com/en-US/education/tutorial/2dgame/getting_started
Related
Hello Stack Overflow users, I have a fun problem that I have in my XNA Game.
So basically I have an asteroid, 80x80, and I set the origin as imageW / 2, imageH / 2 (If order would matter, it wouldn't, the asteroid is a square).
Here is an image, explaining the problem! Visualization FTW :D
http://i.imgur.com/dsawS.png
So, any ideas on what is causing this? I spend 1 hour, I looked at examples, I found out it is supposed to rotate like this:
http://www.riemers.net/images/Tutorials/XNA/Csharp/Series2D/rotation.jpg
But it's not.
Here is a code sample. I have a object named Drawable that has properties which hold the vector position, etc.
Vector2 asteroidOrigin = new Vector2(asteroidImgs[asteroid.asteroidType].Width / 2, asteroidImgs[asteroid.asteroidType].Height / 2);
drawableList.Add(new Drawable(asteroidImgs[asteroid.asteroidType], asteroid.asteroidPos, asteroid.angle, asteroidOrigin));
Here is the Draw Method:
foreach (Drawable drawable in renderManager.getRenderList)
{
spriteBatch.Draw(drawable.image, drawable.position, drawable.sourceRectangle, drawable.tint, drawable.angle, drawable.origin, drawable.imageScale, drawable.spriteEffects, drawable.depth);
}
And yes, the Drawable Class has multiple constructors and they assign default values.
When you define an Origin in SpriteBatch.Draw, you are defining the new point on your texture which will draw at the Position argument. Obviously this affects translation as well as your desired rotation. When you set the origin to the center of the image, the image is translated so that the center is at your Position, then rotated around that point. When you set the origin to Vector2.Zero, the translation is not changed, but the image rotates around its top left corner.
The solution is to either redefine what you mean as "Position" for sprites to be where the CENTER of the image draws on screen (I recommend this, makes things nice) or perform a bit of work before drawing by adding the Origin to the Position before calling Draw.
I, again, recommend the first solution, because then when you want to draw a circle in the center of the screen you can just set its position to be the center of the screen and be done. You won't need to take its size into account. And so on.
I got some problem with texture transparency, I hope ya can help.
Details:
XNA 4.0
Texture source is BMP, what I make transparent by code:
public void Feketealapú(string Azonosító)
{
//textúra megállapítása
Texture2D Textúra = Textúrák[TextúraSzáma(Azonosító)];
//adatok lekérése
Color[] buffer = new Color[Textúra.Width * Textúra.Height];
Textúra.GetData<Color>(buffer);
//adatok módosítása
for (int i = 0; i < buffer.Length; i++)
{
Color szín = buffer[i];
szín.A = ((byte)((szín.R + szín.B + szín.G) / 3));
buffer[i] = szín;
}
//adatok visszaírása
Textúra.SetData<Color>(buffer);
}
I use the following before I start drawing 3d stuff:
public void Rajzolj()
{
GStatic.Játék.GrafikaiCsatorna.BlendState = BlendState.AlphaBlend;
GStatic.Játék.GrafikaiCsatorna.DepthStencilState = DepthStencilState.Default;
GStatic.Játék.GrafikaiCsatorna.RasterizerState = RasterizerState.CullCounterClockwise;
GStatic.Játék.GrafikaiCsatorna.SamplerStates[0] = SamplerState.LinearWrap;
..etc.
If I use BlendState.Opaque I get no transparent textures.
I get into the following trouble: http://youtu.be/ZiPzyk7AWu8
Edit: Bit more detail about the problem is: the problem is with the transparent texture, what simulates a fire effect. The fire is from several rectangles with these transparent textures. If I see the fire from an angle, I should see another fire effect's rectangle through the transparent texture, what is also transparent. The problem is that instead of this, I see the floor's texture behind the model instead.
So could someone help me out a bit?
Thanks in advance:
Péter
Never mind I don't think the transparency is the issue. I think that whats happening is the first thing in the Z-Buffer is being draw and nothing else behind it.
http://blogs.msdn.com/b/shawnhar/archive/2009/02/18/depth-sorting-alpha-blended-objects.aspx
The most import part being the where he specifies how best to order your scene and manipulate the DepthBuffer.
Set DepthBufferEnable and DepthBufferWriteEnable to true
Draw all opaque geometry
Leave DepthBufferEnable set to true, but change DepthBufferWriteEnable to false
Sort alpha blended objects by distance from the camera, then draw them in order from back to front
This is neither a transparency issue or an ordering issue that you can solve.
The nature of your layout has all 4 quads overlapping each other so that each quad needs to be both in front of and behind another quad at the same time.
So setting draw order won't help because half of quad A needs to be drawn before quad B and the other half of quad A needs to be drawn after quad B.
It may get a little bit better if you divide it into 8 quads that all meet in the middle and sort/draw by depth from the camera. But if you go this route, 3 quads may be sufficient.
I've written out a detailed description of my problem here:
http://www.codebot.org/articles/?doc=9574
The basic gist of my question is what is the best way to get XNA to behave like my OpenGL apps, in that I want content stretched to fill a window based on my designed proportions rather than the actual window size.
Further information, this problem relates to varying window or viewport size. In my previous OpenGL apps I would allow uses to switch between windowed and fullscreen mode, and I'd also allow windows to be resized. The problem I am running into with XNA is handling different fullscreen and windowed sizes. In OpenGL I'd detect a when window was resized and adjust the viewport so that the field of view was always fixed to a resolution aspect ratio. I would also create a 2D projection drawing, using the glOrtho function, to a fixed resolution.
The XNA examples I've worked through using SpriteBatch and SpriteFont, text and sprites seem to render in screen pixels. That is, all 2D output is rendered with square pixels and no stretching. In my XNA apps I'd rather they stretch to fill a window in the proportions I've designed. My question is, how can 2D and 3D stretching and filling, like I've done in OpenGL, best be done in XNA?
For 3D content using BasicEffect (and other effects that implement IEffectMatrices as explained here) you can use the appropriate members to set your World, View and Projection matrices as you like.
So where in your OpenGL code you have this:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(FieldOfView, Width / Height, 1, 1000);
The equivalent in XNA is to set a projection matrix on the effect, like so:
effect.Projection = Matrix.CreatePerspectiveFieldOfView(
FieldOfView, Width / Height, 1, 1000);
Now, for 2D. Here's what you might have in OpenGL:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, height, 0, 0, 1);
If you're using an effect (even with SpriteBatch, as explained here), the basic idea is the same as with 3D:
effect.Projection = Matrix.CreateOrthographicOffCenter(
0, width, height, 0, 0, 1);
Now, if you're using SpriteBatch without a custom effect (and I would recommend this, if you don't actually need a custom effect), you have to bare in mind that, by default, SpriteBatch uses an projection equivalent to:
effect.Projection = Matrix.CreateTranslation(-0.5f, -0.5f, 0)
* Matrix.CreateOrthographicOffCenter(0,
GraphicsDevice.Viewport.Width,
GraphicsDevice.Viewport.Height, 0, 0, 1);
Which gives a "client space" (top left is (0,0)) coordinate system, aligned to pixel centres.
If you want to adjust that space, you may pass in a transformation matrix to SpriteBatch.Begin (this overload).
So to get the effect you are after (where a fixed number of world units appear on screen, no matter the screen size), you can to counter-act the built-in projection from client-space with this transformation:
Matrix.CreateScale(GraphicsDevice.Viewport.Width / 640f,
GraphicsDevice.Viewport.Height / 480f, 1f);
(Assuming you want your visible world space to be 640 by 480.)
I recommend having a look through the documentation for XNA's Matrix on MSDN, to see what kind of matrices you can create.
For 2D drawing I added this to my LoadContent() method, where effect is private field in my Game class ...
effect = new BasicEffect(GraphicsDevice)
{
TextureEnabled = true,
VertexColorEnabled = true
};
And then added this inside my Draw() method ...
effect.Projection = Matrix.CreateTranslation(-0.5f, -0.5f, 0) *
Matrix.CreateOrthographicOffCenter(0, 640, 480, 0, 0, 1);
batch.Begin(0, null, null, null, RasterizerState.CullNone, effect);
It seems to work fine. Now 2D images and fonts are scaled correctly when the window is resized. You recommended not using a custom effect. Is creating an instance of BasicEffect what you meant, or did you mean something else? That is I don't see how to create a custom project matrix without using an effect instance.
I'm creating an application which visualises a picture frame as the user designs it. To create the frame I am drawing 4 polygons which represent the physical bits of wood and using a TextureBrush to fill it.
This works perfectly well for the left and top edges. However, for the bottom and right edges this method isn't working. It appears to me that the TextureBrush is tiling from the point (0,0) on the image and not within the polygon I've drawn. As a result, the tile doesn't line up with the polygon. By adjusting the size of the image I can get the tile to line up perfectly.
How do I create an arbitrarily positioned polygon and fill it with a tiled image, starting from the point (0,0) within the polygon, not the canvas?
I'm not attached to FillPolygon and TextureBrush if there is a better solution.
Example
I've just found the answer. I was playing with adding a BoundingBox to the TextureBrush constructor but I kept getting OutOfMemory exceptions and thought it was me not understanding. Turns out it's a bug in the .NET framework
http://connect.microsoft.com/VisualStudio/feedback/details/90973/texturebrush-constructor-throws-out-of-memory-exception-when-providing-the-bounding-rectangle
The work around is to use a transformation to move the texture
var brush = new TextureBrush(new Bitmap(imagefile));
Matrix mtx = brush.Transform;
mtx.Translate(xoffset, 0);
brush.Transform = mtx;
I need to draw a large set of cubes, all with (possibly) unique textures on each side. Some of the textures also have parts of transparency. The cubes that are behind ones with transparent textures should show through the transparent texture. However, it seems that the order in which I draw the cubes decides if the transparency works or not, which is something I want to avoid. Look here:
cubeEffect.CurrentTechnique = cubeEffect.Techniques["Textured"];
Block[] cubes = new Block[4];
cubes[0] = new Block(BlockType.leaves, new Vector3(0, 0, 3));
cubes[1] = new Block(BlockType.dirt, new Vector3(0, 1, 3));
cubes[2] = new Block(BlockType.log, new Vector3(0, 0, 4));
cubes[3] = new Block(BlockType.gold, new Vector3(0, 1, 4));
foreach(Block b in cubes) {
b.shape.RenderShape(GraphicsDevice, cubeEffect);
}
This is the code in the Draw method. It produces this result:
As you can see, the textures behind the leaf cube are not visible on the other side. When i reverse index 3 and 0 on in the array, I get this:
It is clear that the order of drawing is affecting the cubes. I suspect it may have to do with the blend mode, but I have no idea where to start with that.
You are relying on depth buffering to achieve occlusion. This technique only works for opaque objects.
To achieve correct occlusion for a scene containing transparent objects:
Set DepthBufferEnable and
DepthBufferWriteEnable to true
Draw all opaque geometry
Leave DepthBufferEnable set to true,
but change DepthBufferWriteEnable to
false
Sort alpha blended objects by
distance from the camera, then draw
them in order from back to front
Extract from Depth sorting alpha blended objects by Shawn Hargreaves
Drawing transparent objects properly is harder than regular ones. The reason is when face is rendered by default it marks all pixels as drawn at certain depth and as result pixels that are behind will not be drawn at all. I'd recommend getting a book on 3d rendering and look through for more details.
The easiest approach you already found - draw transparent objects AFTER non-transparent ones. Works for transpreant and semi-transparent objects. Note that transparent objects need to be sorted to be drawn correctly (unlike non-transparent ones).
In your particular case (non-semitransparent) you can change texture renreding to NOT render anything for transparent parts.
You may be able to use this if you don't have semi-transparent pixels on the objects. It'll either render completely solid or won't write to the Z-Buffer.
As in Riemers Alpha Testing.
XNA (and DirectX and all major 3D libraries) take in consideration something called culling. Although from your code I cannot tell for sure, from the images I think this is your problem. The polygons that you don't see have the vertices in the wrong order. If this is the problem, you have two solutions:
either turn culling off (device.RenderState.CullMode = CullMode.None; if I remember correctly)
apply your texture twice, with the points of the polygon both in clockwise order and counter clockwise