I'm writing a bit of code where I animate a hundred copies of the same sprite onto the screen by creating a sprite class. I want the sprites, an animation of four-ring interlocking rings spinning within each other, to be drawn at a certain height, drop down on the screen, and bounce like a ball, with each bounce being progressively less until it they stop completely. I have managed to get this part done; however, I can't seem to find a way to randomize the acceleration and animation speed of each different sprite. Can someone provide some suggestions to my code?
Game 1.cs
namespace lab_6
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Sprite rings;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferWidth = 800;
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Texture2D rings_texture = Content.Load<Texture2D>("Images/threerings");
//animation
Point frameSize = new Point(75, 75);
Point currentFrame = new Point(0, 0);
Point sheetSize = new Point(6, 8);
int millisecondsPerFrame = 50;
rings = new Sprite(rings_texture, ringsPos,
frameSize, 0, currentFrame, sheetSize, ringsSpeed, millisecondsPerFrame);
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <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();
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
this.Exit();
// TODO: Add your update logic here
rings.Update(gameTime, Window.ClientBounds);
base.Update(gameTime);
}
/// <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();
rings.Draw(gameTime, spriteBatch);
spriteBatch.End();
}
}
}
Sprite.cs
namespace lab_6
{
public class Sprite
{
//basics
protected Texture2D rings;
protected Vector2 ringsPos = new Vector2(0,0);
protected Color tint = Color.White;
protected Vector2 ringsSpeed = new Vector2(0,0);
protected Vector2 ringsAccel = new Vector2(0, 1);
//animation
protected Point frameSize = new Point(75,75);
protected Point currentFrame = new Point(0, 0);
protected Point sheetSize = new Point(6,8);
//animation timing
protected int timeSinceLastFrame = 0;
protected int millisecondsPerFrame = 50;
const int defaultMillisecondsPerFrame = 16;
//bounding box offset
protected int collisionOffset;
Random r = new Random(DateTime.Now.Millisecond);
public Sprite(Texture2D rings, Vector2 ringsPos, Point frameSize,
int collisionOffset, Point currentFrame, Point sheetSize, Vector2 ringsSpeed,
int millisecondsPerFrame)
{
this.rings = rings;
this.ringsPos = ringsPos;
this.frameSize = frameSize;
this.collisionOffset = collisionOffset;
this.currentFrame = currentFrame;
this.sheetSize = sheetSize;
this.ringsSpeed = ringsSpeed;
this.millisecondsPerFrame = millisecondsPerFrame;
}
public virtual void Update(GameTime gameTime, Rectangle clientBounds)
{
int maxY = (600 - frameSize.Y );
ringsAccel.Y += (byte)r.Next((1 / 10), 1);
ringsSpeed.Y += ringsAccel.Y;
ringsPos.Y += ringsSpeed.Y;
if (ringsPos.Y > maxY)
{
ringsSpeed *= -0.8f;
ringsPos.Y = maxY;
}
//Update animation frame
millisecondsPerFrame = 50;
millisecondsPerFrame *= ((byte)r.Next(1, 10));
timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
if (timeSinceLastFrame > millisecondsPerFrame)
{
timeSinceLastFrame = 0;
++currentFrame.X;
if (currentFrame.X >= sheetSize.X)
{
currentFrame.X = 0;
++currentFrame.Y;
if (currentFrame.Y >= sheetSize.Y)
currentFrame.Y = 0;
}
}
}
public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
for(int i = 0; i < 100; )
{
Vector2 newPos = ringsPos + new Vector2((10 * i), (1 * (byte)r.Next((1/10), 1)));
spriteBatch.Draw(rings, newPos,
new Rectangle(currentFrame.X * frameSize.X,
currentFrame.Y * frameSize.Y,
frameSize.X, frameSize.Y),
tint, 0, Vector2.Zero, 1f, SpriteEffects.None, 0);
i++;
r = new Random(DateTime.Now.Second);
}
}
}
}
Move the constructor for ringSpeed and ringAccel to the constructor and randomize them there.
Related
First, sorry for my bad English, English is not my native language.
I have a problem when I draw a Texture2D in screen. When I move a Texture in screen,
colors in border of the texture flickers. This is my code:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using SharpDX.Direct2D1.Effects;
using System;
using System.Collections.Generic;
namespace PixelTest
{
public class Drawable
{
public Texture2D Image;
public Point Position;
public Point Size;
public Rectangle Source;
}
public class MainGame : Game
{
//PRIVATE READ-ONLY VARIABLES
private readonly GraphicsDeviceManager _graphics;
private readonly List<Drawable> _sprites;
//VARIABLES
private Texture2D _screen;
private Texture2D _tiles;
private SpriteBatch _spriteBatch;
private Point _camera;
private Point _scale;
private bool _byRect;
private KeyboardState _previousKeyState;
private BlendState _state;
private RasterizerState _rState;
//CONSTRUCTOR
public MainGame()
{
_graphics = new GraphicsDeviceManager(this);
_sprites = new List<Drawable>();
_tiles = null;
_spriteBatch = null;
_camera = Point.Zero;
_scale = new Point(1, 1);
Content.RootDirectory = "Content";
IsMouseVisible = true;
IsFixedTimeStep = true;
//_graphics.PreferHalfPixelOffset = true;
_graphics.PreferMultiSampling= true;
//_graphics.SynchronizeWithVerticalRetrace = false;
_state = new BlendState()
{
AlphaBlendFunction = BlendFunction.Add,
AlphaSourceBlend = Microsoft.Xna.Framework.Graphics.Blend.Zero,
AlphaDestinationBlend = Microsoft.Xna.Framework.Graphics.Blend.Zero,
ColorBlendFunction= BlendFunction.Add,
ColorDestinationBlend = Microsoft.Xna.Framework.Graphics.Blend.Zero,
ColorSourceBlend = Microsoft.Xna.Framework.Graphics.Blend.One,
};
_rState = new RasterizerState()
{
MultiSampleAntiAlias = false
};
}
protected override void Initialize()
{
base.Initialize();
_sprites.Add(new Drawable
{
Image = _tiles,
Position = new Point(32, 64),
Size = new Point(8, 8),
Source = new Rectangle(0, 0, 8, 8)
});
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_tiles = Content.Load<Texture2D>("i001_tiles");
_screen = new Texture2D(GraphicsDevice, _graphics.PreferredBackBufferWidth, _graphics.PreferredBackBufferHeight);
var colors = new Color[_graphics.PreferredBackBufferWidth * _graphics.PreferredBackBufferHeight];
for (var i = 0; i < _graphics.PreferredBackBufferWidth * _graphics.PreferredBackBufferHeight; i++)
colors[i] = Color.Black;
_screen.SetData(colors);
}
protected override void UnloadContent()
{
base.UnloadContent();
_tiles.Dispose();
_screen.Dispose();
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
var sKey = Keyboard.GetState();
var translateUnit = Point.Zero;
var scaleUnit = 0;
if (sKey.IsKeyDown(Keys.A))
translateUnit.X = -1;
else if (sKey.IsKeyDown(Keys.D))
translateUnit.X = 1;
else
translateUnit.X = 0;
if (sKey.IsKeyDown(Keys.W))
translateUnit.Y = -1;
else if (sKey.IsKeyDown(Keys.S))
translateUnit.Y = 1;
else
translateUnit.Y = 0;
if (sKey.IsKeyDown(Keys.F))
scaleUnit = -1;
else if (sKey.IsKeyDown(Keys.G))
scaleUnit = 1;
else
scaleUnit = 0;
if (sKey.IsKeyDown(Keys.U) && _previousKeyState.IsKeyUp(Keys.U))
_byRect = !_byRect;
var speed = translateUnit;// * 1;
_camera += speed;// RoundVec(speed);
_scale = new Point(4, 4);
_previousKeyState = sKey;
}
protected override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
GraphicsDevice.Clear(Color.Blue);
_spriteBatch.Begin(SpriteSortMode.Deferred, _state, SamplerState.PointClamp, null, _rState, null, null);
//_spriteBatch.Draw(_screen, Vector2.Zero, Color.White);
foreach (var item in _sprites)
{
if (true)
{
var pos = item.Position;
var size = item.Size;
pos += _camera;
pos *= _scale;
size *= _scale;
var rect = new Rectangle(
(int)pos.X,
(int)pos.Y,
(int)size.X,
(int)size.Y);
_spriteBatch.Draw(
item.Image,
rect,
item.Source,
Color.White,
0F,
Vector2.Zero,
SpriteEffects.None,
0F);
}
else
{
var pos = item.Position;
//pos = RoundVec(pos * _scale) / _scale;
pos += _camera;
pos *= _scale;
_spriteBatch.Draw(
item.Image,
pos.ToVector2(),
item.Source,
Color.White,
0F,
Vector2.Zero,
_scale.ToVector2(),
SpriteEffects.None,
0F);
}
}
_spriteBatch.End();
}
}
}
I dont use floats values for camera position in this test and the flickers continue to happens. I dont know what is happen.
I tried various things, but nothing work.
Resources:
i001_tiles.png (no alpha values)
PrintScreens:
Maybe is just a ottical illusion, or a monitor problem, but the green part of texture merge with the blue background on camera movement, i dont know why.
In Movement Up:
This only occour with the colors different of white, when i movement camera to right, only the one pixel in green in the right merge with blue background.
This is the code I have so far. I'm trying to get the bullet to move in the direction of where the mouse is clicked. I have a bullet Rectangle, and a Texture2D, and the same goes for the cannon from where the bullet is fired.
namespace Targeted
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
int screenWidth;
int screenHeight;
int speedX;
int speedY;
MouseState oldMouse;
Texture2D cannon;
Rectangle cannonRect;
Texture2D bullet;
Rectangle bulletRect;
KeyboardState kb;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
screenWidth = graphics.GraphicsDevice.Viewport.Width;
screenHeight = graphics.GraphicsDevice.Viewport.Height;
oldMouse = Mouse.GetState();
speedX = 0;
speedY = 0;
cannonRect = new Rectangle((screenWidth / 2) - 100, (screenHeight / 2) - 100, 100, 100);
bulletRect = new Rectangle(cannonRect.X, cannonRect.Y, 10, 10);
this.IsMouseVisible = true;
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
cannon = Content.Load<Texture2D>("Smoothed Octagon");
bullet = Content.Load<Texture2D>("White Square");
// TODO: use this.Content to load your game content here
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
bulletRect.X += speedX;
bulletRect.Y += speedY;
this.IsMouseVisible = true;
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || kb.IsKeyDown(Keys.Escape))
this.Exit();
// TODO: Add your update logic here
MouseState mouse = Mouse.GetState();
kb = Keyboard.GetState();
if (mouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released)
{
bulletRect.X += speedX;
bulletRect.Y += speedY;
}
oldMouse = mouse;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(bullet, bulletRect, Color.White);
spriteBatch.Draw(cannon, cannonRect, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Here's some pseudocode of how to handle bullet velocity and orientation relative to a point.
// On MouseClick
float angle = Math.Atan2(mouseClick.X - player.X, mouseClick.Y - player.Y);
bulletVelocity.X = (Math.Cos(angle) + Math.Sin(angle)) * bulletSpeed;
bulletVelocity.Y = (-Math.Sin(angle) + Math.Cos(angle)) * bulletSpeed;
// On Update Positions
bullet.X += bulletVelocity.X;
bullet.Y += bulletVelocity.Y;
For static entities like cannons, replace "player" with "cannon" and "mouseClick" with "player".
(I'm recalling the positions of Sin and Cos from memory, so hopefully someone can correct me if that's the wrong setup.)
"Rem ad Triarios redisse" Scipio Africanus
I'm programming a platformer and I'm working on the collision, but when it collides a get a stack overflow error;I can't figure it out myself and I would be thankfull if someone knew how to fix it.
The code of the class(main concern):
public class Colliding
{
Rectangle testCollide;
Vector2 playerposition, objectPosition;
Texture2D objectPic;
bool jump;
public Rectangle TestCollide
{
get { return TestCollide; }
set { testCollide = value; }
}
public Vector2 ObjectPosition
{
get { return objectPosition; }
set { objectPosition = value; }
}
public Vector2 Return
{
get { return objectPosition; }
}
public Texture2D ObjectPic
{
set { objectPic = value; }
}
public bool Bool
{
get { return jump; }
}
public void Update()
{
/*if (testCollide.Contains(new Point((int)objectPosition.X, (int)objectPosition.Y + (int)objectPic.Height)) && !
testCollide.Contains(new Point((int)objectPosition.X, (int)objectPosition.Y + (int)objectPic.Height)))
{
objectPosition = new Vector2(objectPosition.X, testCollide.Top - objectPic.Height);
jump = false;
}*/
if (testCollide.Contains(new Point((int)objectPosition.X + (int)objectPic.Width, (int)objectPosition.Y))&&
testCollide.Contains(new Point((int)objectPosition.X + (int)objectPic.Width, (int)objectPosition.Y)))
{
objectPosition = new Vector2(TestCollide.Right - objectPic.Width, ObjectPosition.Y);
jump = false;
}
if (testCollide.Contains(new Point((int)objectPosition.X , (int)objectPosition.Y)) &&
testCollide.Contains(new Point((int)objectPosition.X , (int)objectPosition.Y)))
{
objectPosition = new Vector2(TestCollide.Left +1 , ObjectPosition.Y);
jump = false;
}
The Code of my main(a little messy at the moment)
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
KeyboardState keyState;
KeyboardState prevKeyState;
Texture2D flour,nonAnimPlayer;
Rectangle ground1,ground2,playerRect;
Vector2 playerPosition;
float jumpspeed;
int screenX = 800;
int screenY=480;
float standardMoveSpeed;
bool jumping;
Colliding colGround1=new Colliding ();
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
this.graphics.PreferredBackBufferWidth = screenX;
this.graphics.PreferredBackBufferHeight = screenY;
}
protected override void Initialize()
{
keyState = Keyboard.GetState();
ground1 = new Rectangle(-100, (screenY / 5) * 4, 300,screenY);
ground2 = new Rectangle(400, (screenY / 5) * 4, 800, screenY);
playerRect = new Rectangle(0, 0, 10, 10);
standardMoveSpeed = 300;
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
flour = Content.Load<Texture2D>("background");
nonAnimPlayer = Content.Load<Texture2D>("blok");
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
prevKeyState = keyState;
keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.D))
playerPosition.X += standardMoveSpeed *(float) gameTime.ElapsedGameTime.TotalSeconds;
if (keyState.IsKeyDown(Keys.A))
playerPosition.X -= standardMoveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
if (keyState.IsKeyDown(Keys.Space)&&prevKeyState.IsKeyUp(Keys.Space ))
{
if (jumpspeed == 0)
jumpspeed = 300;
else
jumpspeed += 35;
jumping = true;
}
playerPosition.Y += standardMoveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
if(jumping)
{
playerPosition.Y -= standardMoveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds+jumpspeed*(float)gameTime.ElapsedGameTime.TotalSeconds ;
jumpspeed-=9;
if (jumpspeed <= 0)
jumping = false;
}
if (ground2.Contains(new Point((int)playerPosition.X, (int)playerPosition.Y + (int)nonAnimPlayer.Height)))
{
playerPosition.Y = ground2.Top - nonAnimPlayer.Height;
jumpspeed = 0;
}
colGround1.ObjectPosition = playerPosition;
colGround1.TestCollide = ground1;
colGround1.ObjectPic = nonAnimPlayer;
colGround1.Update();
playerPosition = colGround1.Return;
if (colGround1.Bool)
jumpspeed = 0;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(flour, ground1, Color.White);
spriteBatch.Draw(flour, ground2, Color.White);
spriteBatch.Draw(nonAnimPlayer, playerPosition, Color.White);
spriteBatch.End();
base.Draw(gameTime);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I was developing a game using XNA frame work and here is my code
I just want to generate infinite number of enemies
here is my code please help
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 fight_in_the_sky
{
/// <summary>
/// This is the main type for your game
/// </summary>
///
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spritebatch;
Texture2D anim, background1, background2, enemy;
Rectangle rect0, rect2, rectdst, srcrect, rect3, rect4, srcrect2, enemy_rect;
float elapsed;
float delay = 40f;
int frames = 0;
Random random = new Random();
public Vector2 velocity;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 600;
IsMouseVisible = true;
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
rectdst = new Rectangle(0, 250, 115, 69);
rect3 = new Rectangle(0,0,1280,720);
rect4 = new Rectangle(1280, 0, 1280, 720);
enemy_rect = new Rectangle(random.Next(800-94,800-47),random.Next(600-122,600-61),376/8,61);
velocity.X = 3f;
velocity.Y = 3f;
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spritebatch = new SpriteBatch(GraphicsDevice);
background1= Content.Load<Texture2D>("starfield006");
background2= Content.Load<Texture2D>("starfield005");
anim=Content.Load<Texture2D>("shipAnimation");
enemy =Content.Load<Texture2D>("mineAnimation");
rect0 = new Rectangle(0, 0, 800, 600);
rect2 = new Rectangle(0, 250,200, 100);
// TODO: use this.Content to load your game content here
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
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
elapsed += (float)gameTime.ElapsedGameTime.Milliseconds;
if (Keyboard.GetState().IsKeyDown(Keys.Left))
{
rectdst.X -= 12;
if (rectdst.X < 0) { rectdst.X = 0; }
}
if (Keyboard.GetState().IsKeyDown(Keys.Right))
{
rectdst.X += 12;
if (rectdst.X > 700) { rectdst.X = 700; }
}
if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
rectdst.Y -= 12;
if (rectdst.Y < 0) { rectdst.Y = 0; }
}
if (Keyboard.GetState().IsKeyDown(Keys.Down))
{ rectdst.Y += 10; if (rectdst.Y > 550) { rectdst.Y = 550; } }
base.Update(gameTime);
if (elapsed >= delay)
{
if (frames >= 7)
{ frames = 0; }
else { frames++; }
elapsed = 0;
}
srcrect = new Rectangle(115 * frames, 0, 115, 69);
srcrect2 = new Rectangle(47*frames,0,47,61);
if (rect3.X + background1.Width <= 0)
rect3.X = rect4.X + background2.Width;
if (rect4.X + background2.Width <= 0)
rect4.X = rect3.X + background1.Width;
rect3.X -= 5;
rect4.X -= 5;
enemy_rect.X +=(int) velocity.X;
enemy_rect.Y += (int)velocity.Y;
if (enemy_rect.Y >= 600 - 61 || enemy_rect.Y <= 0) velocity.Y = -velocity.Y;
if (enemy_rect.X >= 800 - 47) velocity.X = -velocity.X;
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spritebatch.Begin();
spritebatch.Draw(background1,rect3, Color.Azure);
spritebatch.Draw(background2,rect4, Color.Azure);
spritebatch.Draw(anim, rectdst, srcrect, Color.White);
spritebatch.Draw(enemy, enemy_rect, srcrect2, Color.White);
spritebatch.End();
base.Draw(gameTime);
}
}
}
and here is a shot of my current output
http://imgur.com/7y43S7O
Infinite is unpractical to build into a game, because sooner or later you would either run out of RAM or your screen would be too full to call it a game. Anyway, I can give you a basic idea to work with.
If you want your enemy count to keep increasing you can use a list and add an enemy every time you want one to appear
List<Enemy> enemies = new List<Enemy>;
In Update:
if(spawnTimer > spawnInterval && enemies.Count()<enemyLimit){
enemies.add(new Enemy([rectangle of spawn location and image size]);
spawnTimer = 0;
}
for(int i=0; i<enemies.Count();i++){
if(enemies[i].defeated){
enemies.Remove(enemies[i]);
}
spawnTimer+=gameTime.ElapsedGameTime.TotalSeconds;
in Draw:
for(int i=0; i<enemies.Count();i++){
spritebatch.Draw(enemy, enemies[i].Rect, srcrect2, Color.White);
}
class Enemy{
public Rectangle Rect{get;set;}
public bool defeated{get;set;}
public int Health{get;set;}
public Enemy(Rectangle rect){
Rect = rect;
Health = 100;
defeated = false;
}
}
I'm attempting to create an asteroids game and what I am trying to do is to get the asteroids to move down the screen themselves. The code I have loads the asteroids onto the screen however the asteroids do not move.
The code I have for the movement of the asteroids is listed below.
public class Asteroids
{
public int speed;
public Asteroids(Texture2D newTexture, Vector2 newPosition)
{
speed = 2;
}
public LoadContent()
{
while (asteroidsList.Count() < 5)
{
randX = random.Next(0, 1000) + speed;
randY = random.Next(-200, 984) + speed;
asteroidsList.Add(new Asteroids(Content.Load<Texture2D>("asteroid big"), new Vector2(randX, randY)));
}
}
public void Update (GameTime gameTime)
{
// Update Origin
if (texture != null)
{
Asteroidorigin.X = texture.Width / 2;
Asteroidorigin.Y = texture.Height / 2;
}
foreach (Asteroids a in asteroidsList)
{
position.Y = position.Y + speed;
position.X = position.X + speed;
}
if (position.X >= 1280)
{
position.X = -105;
}
if (position.Y >= 1024)
{
position.Y = -105;
}
}
}
Game1.cs
namespace AsteroidsGame
{
// Main
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Random random = new Random();
// List Of Asteroids
// Making New Objects Of These Classes
Player p = new Player();
Background bg = new Background();
Asteroids a = new Asteroids();
EnemySpaceship es = new EnemySpaceship();
// Constructor
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.IsFullScreen = false; // Fullscreen mode
graphics.PreferredBackBufferWidth = 1280; // Screen Width
graphics.PreferredBackBufferHeight = 1024; // Screen Height
this.Window.Title = "12013951 Asteroids Game";
Content.RootDirectory = "Content";
}
// Init
protected override void Initialize()
{
base.Initialize();
}
// Load Content
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
bg.LoadContent(Content);
p.LoadContent(Content);
a.LoadContent(Content);
es.LoadContent(Content);
}
// Unload Content
protected override void UnloadContent()
{
}
// Update
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
bg.Update(gameTime);
p.Update(gameTime);
a.Update(gameTime);
es.Update(gameTime);
a.CheckCollisionAsteroid();
base.Update(gameTime);
}
// Draw
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
bg.Draw(spriteBatch); //Draws The Background
p.Draw(spriteBatch); // Draws The Player
a.Draw(spriteBatch); // Draws asteroids
es.Draw(spriteBatch); // Draws enemy spaceships
spriteBatch.End();
base.Draw(gameTime);
}
// Load Asteroids
}
}
Any help with this issue would be greatly appreciated.
You are modifying the position of something, but I don't see how modifying that position property is modifying the position of each asteroid. You need each asteroid to have its own position property. You could try something like this (assuming position is a Vector2 property of the asteroid class):
public void Update (GameTime gameTime)
{
foreach (Asteroids a in asteroidsList)
{
a.position = new Vector2(
MathHelper.Clamp(a.position.X + speed, -105, 1280),
MathHelper.Clamp(a.position.Y + speed, -200, 1024));
}
}
The MathHelper.Clamp() also removes the need for the if statements you have in the update method.