I would like to say sorry in advance for the amount of code I will post, but I can't seem to get my collision detection to work, the player and the objects pass through each other with no effect when I play test.
I receive 0 warnings or errors, but the Player playerBot object does not seem to interact with any of the level items I have imported from GLEED2D.
One thing I did was to store the values of my item's rectangles and color arrays in lists so they could be all easily iterated through, maybe this is the source of the problem.
If you can spot why my code is not working I will be hugely grateful. I have removed any code that is definitely not relevant, and I am running VS 2010 with GLEED2D 1.3 if that helps.
Thanks again.
// Item Class ImageItem Downcast
public class ImageItem : Item
{
public Texture2D Texture;
}
// Level
Level level;
// Ints
int iNumOfItems = 0;
int iTextureDataListNum = 0;
int iRectangleListNum = 0;
// Lists
List<Color []> itemTextureDataList = new List<Color[]>();
List<Rectangle> itemRectangleList = new List<Rectangle>();
protected override void Initialize()
{
if (filename.Length > 0) level = Level.FromFile(filename, Content);
else level = Level.FromFile("level1.xml", Content);
foreach (Layer layer in level.Layers)
{
foreach (Item item in layer.Items)
{
iNumOfItems =+ 1;
}
}
// Creates Player Ship
playerBot = new Player(new Vector2(400f, 240f), new Vector2(0f, 0f));
base.Initialize();
}
protected override void LoadContent()
{
Texture2D pixel = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
pixel.SetData(new[] { Color.White });
spriteBatch = new SpriteBatch(GraphicsDevice);
// Player Bot
playerBot.LoadContent(Content, "Images/Player Bot Sprite Sheet", 40, 40, 4);
// Assigns level textures color data to array
foreach (Layer layer in level.Layers)
{
foreach (Item item in layer.Items)
{
ImageItem imageItem = item as ImageItem;
if (imageItem != null)
{
Texture2D texture = imageItem.Texture;
itemTextureDataList[iTextureDataListNum] = new Color[imageItem.Texture.Width * imageItem.Texture.Height];
imageItem.Texture.GetData(itemTextureDataList[iTextureDataListNum]);
iTextureDataListNum++;
}
}
}
// Creates a rectangle for every level texture
foreach (Layer layer in level.Layers)
{
foreach (Item item in layer.Items)
{
ImageItem imageItem = item as ImageItem;
if (imageItem != null)
{
itemRectangleList[iRectangleListNum] = new Rectangle((int)imageItem.Position.X, (int)imageItem.Position.Y, imageItem.Texture.Width, imageItem.Texture.Height);
iRectangleListNum++;
}
}
}
spriteBatch = new SpriteBatch(GraphicsDevice);
}
protected override void Update(GameTime gameTime)
{
// Player Update
playerBot.Update(gameTime);
((Sprite)playerBot).Update(gameTime);
// Check for player collisons with level
for (int i = 0; i < iNumOfItems - 1; i++)
{
if (IntersectPixels(playerBot.colRectangle, playerBot.textureDataArray, itemRectangleList[i], itemTextureDataList[i]) == true)
{
playerBot.StopMovement();
}
}
base.Update(gameTime);
}
// Level Collision Detection Method
static bool IntersectPixels(Rectangle rectangleA, Color[] dataA, Rectangle rectangleB, Color[] dataB)
{
// Find the bounds of the rectangle intersection
int top = Math.Max(rectangleA.Top, rectangleB.Top);
int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
int left = Math.Max(rectangleA.Left, rectangleB.Left);
int right = Math.Min(rectangleA.Right, rectangleB.Right);
// Check every point within the intersection bounds
for (int y = top; y < bottom; y++)
{
for (int x = left; x < right; x++)
{
// Get the color of both pixels at this point
Color colorA = dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width];
Color colorB = dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width];
// If both pixels are not completely transparent
if (colorA.A != 0 && colorB.A != 0)
{
// Then an intersection has been found
return true;
}
}
}
// No intersection fond
return false;
}
// Sprite Class
public void Update(GameTime gameTime)
{
textureDataArray = new Color[texture.Width * texture.Height];
texture.GetData(textureDataArray);
// Player Class
public void StopMovement()
{
velocity.X *= -1;
velocity.Y *= -1;
}
The first thing I'll say here is, you should aim to be more Object Oriented in your approach. Storing a list of textures and a list of rectangles alongside your list of Items is "bad" technique and going to eventually cause you some massive headaches when it comes to debugging.
So first of all, instead of having a list of Color[] and a list of Rectangle, add one Color[] and one Rectangle to your ImageItem class and work with those instead, or at least create a little class called "CollisionData" that has a Rectangle and a Color[] and store those in a single list.
Secondly, note that there is a Rectangle.Intersect(Rectangle A, Rectangle B) that gets your the rectangle of intersection. So you can tidy up your code a bit by using that.
Your color checking can be simplified to (ColorA.A * ColorB.A != 0) as either being zero will
cause the result to be zero.
Regarding not getting any errors, put a breakpoint at the start of the collision checking loop. Does the application break? If yes, what is the value of iNumItems? (you can hover over it to see the current value at point of breaking). If no, then that section of code isn't being reached. Put another breakpoint a bit further back and a bit further back until it gets hit, then figure out why the code isn't executing.
Related
Very new developer here.
In my program I have a randomly generating world map using a simplex noise library. On top of this I am attempting to draw a tilemap of transparent 4x4 tiles that appear slightly translucent when the mouse is hovering over one.
I've got this working but it takes about 3 whole seconds for the highlighted tile to update to the mouse's current position. Is there anything I could do to solve this?
This is my code for the MouseState check in the tile class:
public override void Update(GameTime gameTime)
{
_previousMouse = _currentMouse;
_currentMouse = Mouse.GetState();
var mouseRectangle = new Rectangle(_currentMouse.X, _currentMouse.Y, 1, 1);
_isHovering = false;
if (mouseRectangle.Intersects(Rectangle))
{
_isHovering = true;
if (_currentMouse.LeftButton == ButtonState.Released && _previousMouse.LeftButton == ButtonState.Pressed)
{
Click?.Invoke(this, new EventArgs());
}
}
}
Sorry if this is formatted wrong or badly asked, first post so still getting to grips with everything :)
Invert the logic:
Instead of checking thousands of tile objects against the mouse, apply the mouse to a single object.
Assuming you have a list or array of tile objects:
Add a new object to check for mouse hover and click:
public class MouseDetect(Tile[] tiles) // replace with List<> as needed
{
int PrevHover = -1; // used to unHover
// if (Area == Screen) make the next two lines `const`, so the compiler will remove all uses...
int AreaX = 0; //Area x offset
int AreaY = 0; //Area y offset
int AreaW = 800; //Area width
int AreaH = 480; //Area height
const int Grid = 4; // assumes square
const int GridW = AreaW / Grid;
// I Will assume the `Delegate Click` in `Tile` is public
public void Update(MouseState ms, MouseState oms), //_currentMouse = ms and _previousMouse = oms;
{
int mouseIndex = (ms.X - AreaX) % Gridw + (ms.Y - AreaY) / GridW;
tiles[PrevHover].Hover = false;
PrevHover = mouseIndex;
tiles[PrevHover].Hover = true;
//Check Release
if(tiles[PrevHover].Hover && ms.LeftButton == ms.ButtonState.Released && oms.LeftButton == ButtonState.Pressed)
tiles[PrevHover].Click(tiles[PrevHover], new EventArgs());
}
}
Remove the Update from the Tile class.
Notes for anyone reading this later:
Never call Mouse.GetState(); more than once per step.
Predefined or framework names such as Rectangle should never be used as an identifier.
i.e renamed and corrected to CollRectangle
if (CollRectangle.Contains(ms.Position))
Im a C#/XNA student and I've recently been working on an isometric tile engine and so far it works fairly well. But im having problem trying to figure out on how to do collision, this is what my tile engine does at the moment:
Draws the world from an image and place a tile depending on what color is on my image. For instance color red would draw a grass tile. (Tiles are 64x32)
Camera following player, and my draw loop only draws what the camera sees.
This is how my game looks if that would be of any help:
I don't know what sort of collision would work best. Should i do collision points, or intersects or any other sort of collision. I've read somewhere that you could do Worldtoscreen/Screentoworld but im far to inexperienced and don't know how that works nor how the code would look like.
Here is my code drawing tiles etc:
class MapRow
{
public List<MapCell> Columns = new List<MapCell>();
}
class TileMap
{
public List<MapRow> Rows = new List<MapRow>();
public static Texture2D image;
Texture2D tileset;
TileInfo[,] tileMap;
Color[] pixelColor;
public TileMap(string TextureImage, string Tileset)
{
tileset = Game1.Instance.Content.Load<Texture2D>(Tileset);
image = Game1.Instance.Content.Load<Texture2D>(TextureImage);
pixelColor = new Color[image.Width * image.Height]; // pixelColor array that is holding all pixel in the image
image.GetData<Color>(pixelColor); // Save all the pixels in image to the array pixelColor
tileMap = new TileInfo[image.Height, image.Width];
int counter = 0;
for (int y = 0; y < image.Height; y++)
{
MapRow thisRow = new MapRow();
for (int x = 0; x < image.Width; x++)
{
tileMap[y, x] = new TileInfo();
if (pixelColor[counter] == new Color(0, 166, 81))
{
tileMap[y, x].cellValue = 1;//grass
}
if (pixelColor[counter] == new Color(0, 74, 128))
{
tileMap[y, x].cellValue = 2;//water
}
if (pixelColor[counter] == new Color(255, 255, 0))
{
tileMap[y, x].cellValue = 3;//Sand
}
tileMap[y, x].LoadInfoFromCellValue();//determine what tile it should draw depending on cellvalue
thisRow.Columns.Add(new MapCell(tileMap[y, x]));
counter++;
}
Rows.Add(thisRow);
}
}
public static int printx;
public static int printy;
public static int squaresAcross = Settings.screen.X / Tile.TileWidth;
public static int squaresDown = Settings.screen.Y / Tile.TileHeight;
int baseOffsetX = -32;
int baseOffsetY = -64;
public void draw(SpriteBatch spriteBatch)
{
printx = (int)Camera.Location.X / Tile.TileWidth;
printy = (int)Camera.Location.Y / Tile.TileHeight;
squaresAcross = (int)Camera.Location.X / Tile.TileWidth + Settings.screen.X / Tile.TileWidth;
squaresDown = 2*(int)Camera.Location.Y / Tile.TileHeight + Settings.screen.Y / Tile.TileHeight + 7;
for (printy = (int)Camera.Location.Y / Tile.TileHeight; printy < squaresDown; printy++)
{
int rowOffset = 0;
if ((printy) % 2 == 1)
rowOffset = Tile.OddRowXOffset;
for (printx = (int)Camera.Location.X / Tile.TileWidth; printx < squaresAcross; printx++)
{
if (tileMap[printy, printx].Collides(MouseCursor.mousePosition))
Console.WriteLine(tileMap[printy, printx].tileRect);
foreach (TileInfo tileID in Rows[printy].Columns[printx].BaseTiles)
{
spriteBatch.Draw(
tileset,
tileMap[printy, printx].tileRect = new Rectangle(
(printx * Tile.TileStepX) + rowOffset + baseOffsetX,
(printy * Tile.TileStepY) + baseOffsetY,
Tile.TileWidth, Tile.TileHeight),
Tile.GetSourceRectangle(tileID.cellValue),
Color.White,
0.0f,
Vector2.Zero,
SpriteEffects.None,
tileID.drawDepth);
}
}
}
}
}
Why don't you just draw stuff just like in normal tile based games, and then rotate the camera with a 45degree? Of course then you'd need to make your graphics a bit odd, but would be easier to handle the tiles.
But if you prefer your way, then I'd suggest using simple math to calculate the "tile to the right", "tile to the left" , "tile to the up" and "tile to the down" ones, you know, the tiles around the player(or another tile). You can simply work with your lists, and with some math, basic math, like getting the next tile, is quite simple.
Edit:
You could get the player's next position's tile value with a code something like this:
tileMap[Math.Floor((player.y+playerVelociy.Y)/tileHeight)]
[Math.Floor((player.x+playerVelocity.X)/tileWidth)]
In this code, I assume that the first tile is at 0,0 and you're drawing to right and down. (If not, then just change the Math.Floor to Math.Ceil)
THIS link could help you get the idea, however it's in AS3.0, only the syntax is different.
I am trying to create a Tetris game in XNA to better learn to make a better game in the future. The only problem I am having is the 'deleting rows' functionality of the game. I have a integer matrix to hold all the rows count of the blocks in them. Whenever I create a new block, I increment the count by one in the specified row. Then, I check to see if any of the values in the matrix has met or exceeded 10. Then if it has, I delete all the blocks in said row. The problem I am having is that it's not reliable, and it doesn't keep track of the count as well as it should for some reason, and sometimes- it won't delete all the blocks in the row. If you need to see any other classes, let me know. Thanks, help is appreciated.
public class Main : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
//Texture for the block
public static Texture2D block;
//Font
public static SpriteFont font1;
//Which shape we're dealing with(Moving)
public static int shapeIndex;
//The next shape, the one we can see previewed
public static Shape nextShape;
//The first shape we use
public static Shape s2;
//All the shapes
public static List<Shape> shapes = new List<Shape>();
//All the blocks that have stopped moving (The shapes are converted to blocks when they stop moving to make for easier deletion)
public static List<Block> blocks = new List<Block>();
//The count of blocks in each row
public static int[] rowCount = new int[20];
public Main()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferHeight = 500;
}
protected override void Initialize()
{
this.IsMouseVisible = true;
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
block = Content.Load<Texture2D>("Sprites//TetrisBlock");
font1 = Content.Load<SpriteFont>("Fonts//GameFont");
//Creating a random shape
switch (new Random().Next(1, 3))
{
case 1:
nextShape = new Shape(Shape.Shapes.tShape, new Vector2(550, 0), false);
break;
case 2:
nextShape = new Shape(Shape.Shapes.lineShape, new Vector2(550, 0), false);
break;
}
//The current shape we're dealing with
shapeIndex = 0;
//Creating the first shape
s2 = new Shape(Shape.Shapes.lineShape, new Vector2(), true);
}
protected override void Update(GameTime gameTime)
{
//If the blocks that are still are rainbow, have them cycle through their colors
foreach (Block b in nextShape.Blocks)
{
if (b.RainbowBlock)
b.changeColor(gameTime);
}
//Update all the shapes
for (int i = 0; i < shapes.Count; i++)
{
shapes[i].Update(gameTime);
}
//If the shape has hit another shape and stopped moving
if (!shapes[shapeIndex].MoveDown)
{
//For every block that was in the shape, add it to the block list and increase that row's count by one
foreach (Block b in shapes[shapeIndex].Blocks)
{
blocks.Add(b);
rowCount[b.Row]++;
}
//Remove that shape
shapes.RemoveAt(shapeIndex);
//The current shape we need to move
Shape s3 = nextShape;
s3.Position = new Vector2();
s3.Imaginary = false;
shapes.Add(s3);
//Creating a new random shape for the next shape
switch (new Random().Next(1, 4))
{
case 1:
nextShape = new Shape(Shape.Shapes.tShape, new Vector2(550, 0), false);
break;
case 2:
nextShape = new Shape(Shape.Shapes.lineShape, new Vector2(550, 0), false);
break;
case 3:
nextShape = new Shape(Shape.Shapes.lShape, new Vector2(550, 0), false);
break;
}
}
//Testing whether or not rows have reached their maximum capacity
for (int i = 0; i < rowCount.Length; i++)
{
//If a row has reached its capacity
if (rowCount[i] >= 10)
{
//Remove that row
removeRow(i);
//Move all blocks that are above that row down one
foreach (Block b in blocks)
{
if (b.Row < i)
{
//Subtract the old rowcount by one
rowCount[b.Row]--;
b.Row++;
//Add one to the rowcount(If I remove this, it seems to work a little better but it still has issues)
rowCount[b.Row]++;
}
}
}
}
//Update all the blocks that are still
foreach (Block b in blocks)
b.Update(gameTime);
base.Update(gameTime);
}
//Remove the row specified in the parameters
public void removeRow(int row)
{
//For every block
for (int i = 0; i < blocks.Count; i++)
{
//See if it's in the row the user wants to remove
if (blocks[i].Row.Equals(row))
{
//If it is, remove it and decrement that row's rowcount
blocks.RemoveAt(i);
rowCount[row]--;
//Here was the problem, I wasn't decrementing i to check the next block
i--;
}
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
//Draws every shape in the game
foreach (Shape s in shapes)
s.Draw(spriteBatch);
//Draws all the blocks at the bottom that have stopped moving
foreach (Block b in blocks)
b.Draw(spriteBatch);
//Info for me
spriteBatch.DrawString(font1, "Next Block:", new Vector2(430, 0), Color.Black);
spriteBatch.DrawString(font1, rowCount[19].ToString() + " " + blocks.Count + " Blocks", new Vector2(300, 0), Color.Black);
//For the next shape, draw every block so we know what it looks like
foreach (Block b in nextShape.Blocks)
b.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
[EDIT]
The parts moving down works just fine, it's just deleting rows that troublesome. I also tried to comment as best I could, if you have any questions, just ask. Thanks again.
When I was iterating through the blocks that I was checking, if I deleted it, I didn't decrement the iteration variable to check the next block- so all the blocks weren't being checked.
I just started to learn XNA/MonoGame and I encountered a weird exception.
The error says: The method or operation is not implemented.
And what's even more weird that a very similar code, almost the same, works. The only difference is that the other code is run on XNA and on another computer, and my code runs on MonoGame.
The code is supposed to make an animation from a sprite sheet.
Inside of my class, Animate:
public void set_state(string name, string state)
{
this.name = name;
this.state = state;
}
public void animate(int frameIndex)
{
this.frameIndex = frameIndex;
this.animatedTexture = Game1.contentManager.Load<Texture2D>(name + '/' + state);
prepare_frames();
while (this.frameIndex > rectangles.Count )
{
frameIndex = frameIndex - rectangles.Count;
}
base.draw(animatedTexture, rectangles[frameIndex], origins[frameIndex]);
}
public void prepare_frames()
{
find_dots();
find_rectangles();
find_origins();
}
public void find_dots()
{
cols = new Color[animatedTexture.Width];
lowestRectangle = new Rectangle(0, animatedTexture.Height - 1, animatedTexture.Width, 1);
animatedTexture.GetData<Color>(0, lowestRectangle, cols, 0, animatedTexture.Width);
for (int i = 0; i < cols.Length; i++)
{
if (cols[i] == Color.Black)
{
dots.Add(new Vector2(i, animatedTexture.Height));
}
}
}
public void find_rectangles()
{
for (int i = 0; i < dots.Count-2; i+=2)
{
rectangles.Add(new Rectangle((int)dots[i].X, 0, (int)dots[i+2].X - (int)dots[i].X, animatedTexture.Height-1));
}
}
public void find_origins()
{
for (int i = 1; i < dots.Count; i++)
{
if (i%2 != 0)
{
origins.Add(dots[i]);
}
}
}
the idea behind is that there is a line of dots below the sprite sheet, with those dots i can make frames from the sprite sheet.
Here is the data of the class Animated:
#region data
Texture2D animatedTexture;
string name, state; // to determine the animated state.
Rectangle lowestRectangle; // is the rectangle of the dot's.
Color[] cols; // this array is for the colors on the dot's rectungle.
List<Vector2> dots = new List<Vector2>(); // this list is for the dot's coordinates on the dot's rectungle.
List<Rectangle> rectangles = new List<Rectangle>(); // this list is for the new rectungles, each rectungle is a diffirent frame from the sprite sheet.
List<Vector2> origins = new List<Vector2>(); // this list is for each origin point of the new retungles.
int frameIndex;
#endregion
Here is the part that summons the methods above, in the main class of the MonoGame, Game1:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
if (Keyboard.GetState().IsKeyDown(Keys.Right))
{
player.set_state("moshe", "run");
player.animate(frameIndex);
frameIndex++;
}
else
player.draw();
spriteBatch.End();
base.Draw(gameTime);
}
So the error occurs in this line:
animatedTexture.GetData<Color>(0, lowestRectangle, cols, 0, animatedTexture.Width);
in the method animate in the class Animate. ( The method or operation is not implemented.) When I press the right key. Why does that happens?
Quite honestly that is a big difference, between XNA and a port of it.
A NotImplementedException does exactly what it suggest, it is thrown when a method or operation has not been implemented.
Nothing appears to be documented much about this, but it has been reported to the MonoGame bug tracker and is assigned to a developer for the 3.x release.
Using the SharpDX version however, this error does not exist.
I am working on a space shooter game using XNA and have followed multiple tutorials to create a parallax background. So far I can get it to go along one axis, either X or Y, but not both at the same time. I have a camera class that follows the player, which the player moves (instead of the 'world'), since I figured it would be easier to just move the player versus moving everything else around the player.
So far, the background doesn't keep up with the player, and it also can't comprehend both axis at the same time. I thought about a tile engine, but that wouldn't let me parallax different layers would it?
Could anyone help me understand what I need to do, or recommend a tutorial that can do both axis at the same time? I can't seem to find the answer on my own this time.
Here is the code for my background class:
class Background
{
// Textures to hold the two background images
Texture2D spaceBackground, starsParallax;
int backgroundWidth = 2048;
int backgroundHeight = 2048;
int parallaxWidth = 2048;
int parallaxHeight = 2048;
int backgroundWidthOffset;
int backgroundHeightOffset;
int parallaxWidthOffset;
int parallaxHeightOffset;
public int BackgroundWidthOffset
{
get { return backgroundWidthOffset; }
set
{
backgroundWidthOffset = value;
if (backgroundWidthOffset < 0)
{
backgroundWidthOffset += backgroundWidth;
}
if (backgroundWidthOffset > backgroundWidth)
{
backgroundWidthOffset -= backgroundWidth;
}
}
}
public int BackgroundHeightOffset
{
get { return backgroundHeightOffset; }
set
{
backgroundHeightOffset = value;
if (backgroundHeightOffset < 0)
{
backgroundHeightOffset += backgroundHeight;
}
if (backgroundHeightOffset > backgroundHeight)
{
backgroundHeightOffset -= backgroundHeight;
}
}
}
public int ParallaxWidthOffset
{
get { return parallaxWidthOffset; }
set
{
parallaxWidthOffset = value;
if (parallaxWidthOffset < 0)
{
parallaxWidthOffset += parallaxWidth;
}
if (parallaxWidthOffset > parallaxWidth)
{
parallaxWidthOffset -= parallaxWidth;
}
}
}
public int ParallaxHeightOffset
{
get { return parallaxHeightOffset; }
set
{
parallaxHeightOffset = value;
if (parallaxHeightOffset < 0)
{
parallaxHeightOffset += parallaxHeight;
}
if (parallaxHeightOffset > parallaxHeight)
{
parallaxHeightOffset -= parallaxHeight;
}
}
}
// Constructor when passed a Content Manager and two strings
public Background(ContentManager content,
string sBackground, string sParallax)
{
spaceBackground = content.Load<Texture2D>(sBackground);
backgroundWidth = spaceBackground.Width;
backgroundHeight = spaceBackground.Height;
starsParallax = content.Load<Texture2D>(sParallax);
parallaxWidth = starsParallax.Width;
parallaxHeight = starsParallax.Height;
}
public void Draw(SpriteBatch spriteBatch)
{
// Draw the background panel, offset by the player's location
spriteBatch.Draw(
spaceBackground,
new Rectangle(-1 * backgroundWidthOffset,
-1 * backgroundHeightOffset,
backgroundWidth,
backgroundHeight),
Color.White);
// If the right edge of the background panel will end
// within the bounds of the display, draw a second copy
// of the background at that location.
if (backgroundWidthOffset > backgroundWidth)
{
spriteBatch.Draw(
spaceBackground,
new Rectangle(
(-1 * backgroundWidthOffset) + backgroundWidth, 0,
backgroundWidth, backgroundHeight),
Color.White);
}
else //(backgroundHeightOffset > backgroundHeight - viewportHeight)
{
spriteBatch.Draw(
spaceBackground,
new Rectangle(
0, (-1 * backgroundHeightOffset) + backgroundHeight,
backgroundHeight, backgroundHeight),
Color.White);
}
// Draw the parallax star field
spriteBatch.Draw(
starsParallax,
new Rectangle(-1 * parallaxWidthOffset,
0, parallaxWidth,
parallaxHeight),
Color.SlateGray);
// if the player is past the point where the star
// field will end on the active screen we need
// to draw a second copy of it to cover the
// remaining screen area.
if (parallaxWidthOffset > parallaxWidth)
{
spriteBatch.Draw(
starsParallax,
new Rectangle(
(-1 * parallaxWidthOffset) + parallaxWidth,
0,
parallaxWidth,
parallaxHeight),
Color.White);
}
}
}
The main game then has ties to move the backgrounds, along with the player.
background.BackgroundWidthOffset -= 2;
background.ParallaxWidthOffset -= 1;
Visually, the background is sort of jumpy, and seems to randomly skip or overlap background tiles.
I've used this method in the past with great results:
http://www.david-gouveia.com/scrolling-textures-with-zoom-and-rotation/
It uses a shader to accomplish the effect, resulting in a fast implementation.
There is a complete example here.