Newly loaded sprites not behaving properly in XNA 4.0 - xna

Here is the code for a project im working on, where an enemy moves back and forth at the bottom of the screen.
class enemy1
{
Texture2D texture;
public Vector2 position;
bool isAlive = false;
Random rand;
int whichSide;
public enemy1(Texture2D texture, Vector2 position)
{
this.texture = texture;
this.position = position;
}
public void Update()
{
if (isAlive)
{
if (whichSide == 1)
{
position.X += 4;
if (position.X > 1000 + texture.Width)
isAlive = false;
}
if (whichSide == 2)
{
position.X -= 4;
if (position.X < 0)
isAlive = false;
}
}
else
{
rand = new Random();
whichSide = rand.Next(1, 3);
SetInStartPosition();
}
}
private void SetInStartPosition()
{
isAlive = true;
if (whichSide == 1)
position = new Vector2(0 - texture.Width, 563 - texture.Height);
if (whichSide == 2)
position = new Vector2(1000 + texture.Width, 563 - texture.Height);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
}
Now i want there to be a few enemys going back and forth but they start at differant positions so it looks like there is a few enemys going back and forth at the bottom of the screen. I have managed to draw a few other enemies on the screen, except they do not behave like the first enemy. They just are pictures on a screen not moving anywhere. So now all i have is the hero moving around and one enemy at the bottom of the screen, along with 5 other enemys sitting at the top of the screen doing nothing. How do i easily add a new sprite from a class that has the same behavior, at any time, while not making a billion variables to store them in?

Generally it's a good idea to have similar logic contained within the proper class, so if all Sprites where to do the same thing, then all you would need to do is put your movement code inside a public method and then call that method inside Update().
So, if your Sprite class looks something like this:
public class Sprite
{
private Vector2 Position;
public Sprite(Texture2D texture, Vector2 position)
{
Position = position;
}
//then just add this
public void MoveSprite(int amount)
{
position.X += amount;
}
}
Now, the object name "Sprite" is pretty generic, you will more than likely have many "Sprites" in your game.
So you're going to want to follow good OOP practices and maybe name this specific sprite something different and then have it derive from this class we're looking at right now. (But i'm not going to make design decisions for you)
This was a vague question, but that's my best shot at an answer for you.

Related

XNA mouse 'position relative-to' changes every build

Okay so I'm starting to make a main menu for a small flash game and to do this I want to use the mouse to click on buttons etc. I have a button class in which I create two rectangles: a rectangle for the button and a rectangle for the mouse based on its X and Y, 1 pixel by 1 pixel. I use Rectangle.Intersects to check if they are touching before seeing if left mouse button is down. Problem is, the thing the mouse position is relative to changes every time so no matter where the mouse button is on the screen, it's never the same co-ordinates as in a different build in that exact same position. I seriously just need ideas now as I'm running out. If I didn't explain it very well or you need further details to help please ask - I WOULD BE SO GRATEFUL.
Will post back if I find an answer
Update - Okay here's the button class
class OnScreenButton
{
public Texture2D texture;
Vector2 position;
Rectangle rectangle;
Color colour = new Color(255, 255, 255, 255);
public Vector2 size;
public OnScreenButton(Texture2D newtexture, GraphicsDevice graphics)
{
texture = newtexture;
// ScreenW = 500, ScreenH = 600
// Img W = 80, Img H = 20
size = new Vector2(graphics.Viewport.Width / 10, graphics.Viewport.Height / 30);
size = new Vector2(texture.Width, texture.Height);
}
bool down;
public bool isClicked;
public void Update(MouseState mouseState)
{
rectangle = new Rectangle((int)position.X, (int)position.Y, (int)size.X, (int)size.Y);
Rectangle mouseRectangle = new Rectangle(mouseState.X, mouseState.Y, 1, 1);
if (mouseRectangle.Intersects(rectangle))
{
if (colour.A == 255)
{
down = false;
}
if (colour.A == 0)
{
down = true;
}
if (down)
{
colour.A += 3;
}
else
{
colour.A -= 3;
}
if (mouseState.LeftButton == ButtonState.Pressed)
{
isClicked = true;
}
}
else if (colour.A < 255)
{
colour.A += 3;
isClicked = false;
colour.A = (255);
}
}
public void SetPosition(Vector2 newPos)
{
position = newPos;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, rectangle, colour);
}
}
}
(Sorry for weird formatting, brand new to stack overflow and the posting is still a little confusing)
Here is some other code I think is relevent...
Game.1 initializing stuff
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
protected override void Initialize()
{
// TODO: Add your initialization logic here
Mouse.WindowHandle = Window.Handle;
base.Initialize();
}
public Main()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
KeyboardState keyboardState;
MouseState mouseState;
Main menu update routine...
private void UpdateMainMenu(GameTime gameTime)
{
// Button options
if (buttonPlay.isClicked == true)
{
CreateNewGame();
currentGameState = GameState.playing;
}
buttonPlay.Update(mouseState);
if (buttonExit.isClicked == true)
{
this.Exit();
}
buttonExit.Update(mouseState);
// Press enter to play
if (keyboardState.IsKeyDown(Keys.Enter))
{
CreateNewGame();
currentGameState = GameState.playing;
}
}
Here's thee draw routine for main menu...
public void DrawMainMenu()
{
spriteBatch.Draw(mainMenuBackground, new Vector2(0, 0), Color.White);
buttonPlay.Draw(spriteBatch);
buttonExit.Draw(spriteBatch);
spriteBatch.DrawString(playerAmmoFont, String.Format("{0}", mouseState), new Vector2(0, 0), Color.White);
}
okay that's all I can think of
UPDATE - Okay so I know a few things that aren't the problem...
The whole of my button class is fine, I made a new project and inserted all the relevant code into it and it worked absolutely perfectly so I'm starting to think its something to do with the code positioning and the graphics device stuff although I still don't have a clue how to fix it.
the window appears at the same spot every time
there is no pattern to the change in coordinates at all
this is really annoying
UPDATE - OKAY. I spent a long time writing down the coordinates that I got each time I ran the code and stuck to cursor in the top right corner of the screen. Here is what I got.
(-203, -225)
(-253, -275)
(-53, -75)
(-103, -125)
(-153, -175)
(-203, -225)
(-253, -275)
(-53, -75)
(-103, -125)
(-153, -175)
(-203, -225)
(-253, -275)
(-53, -75)
(-103, -125)
(-153, -175)
(-203, -225)
(-253, -275)
(-53, -75)
(-103, -125)
(-153, -175)
(-203, -225)
(-78, -100)
(-128, -150)
(-178, -200)
(-228, -250)
(-28, -50)
(-53, -75)
(-103, -125)
(-153, -175) < AND FROM HERE THE PATTERN LOOPS ROUND.
I just don't get how the same code can execute a different bug on different executions like this.
Also, mouse.Wheel doesn't go up or down whereas it works on the project that I made to test the relevant code where the mouse position was relevant to the top left pixel of the game window.
UPDATE - EVEN MORE DAMN COMPLICATIONS - So I just rand it a few times again and the offset values are offset... the increase is the same but I got values like (-178, -200) then (-228, -250). I have also discovered that the mouse is not relative to the game window what so ever, if I jam the mouse in the top right corner of the screen and check the coordinates, then move the game window and do the same again, the coordinates don't change. Please please please help me, or tell me if I'm being stupid, or something. Thanks.
The mouse coordinates are relative to the monitor. Here is my general button class to try and work for your situation.
public class Button
{
public event EventHandler<EventArgs> Clicked;
public Vector2 Position { get; set;}
public Texture2D Texture { get; set;}
public Color Tint { get; set; }
public float Scale { get; set; }
public float Rotation { get; set; }
public int Width
{
get
{
if (texture == null)
return 0;
else
return texture.Width;
}
}
public int Height
{
get
{
if (texture == null)
return 0;
else
return texture.Height;
}
}
private void OnClick()
{
if (Clicked != null)
Clicked(this, EventArgs.Empty);
}
public Button(Vector2 position, Texture2D texture)
: base(parent)
{
Position = position;
Texture = texture;
Tint = Color.White;
Scale = 1.0f;
Rotation = 0.0f;
}
public bool HandleClick(Vector2 vector)
{
if (vector.X >= Position.X)
{
if (vector.X <= Position.X + Width)
{
if (vector.Y >= Position.Y)
{
if (vector.Y <= Position.Y + Height)
{
OnClick();
return true;
}
}
}
}
return false;
}
public bool HandleEntered(Vector2 vector)
{
if (vector.X >= Position.X)
{
if (vector.X <= Position.X + Width)
{
if (vector.Y >= Position.Y)
{
if (vector.Y <= Position.Y + Height)
{
return true;
}
}
}
}
return false;
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, null, Tint, Rotation, Vector2.Zero, Scale, SpriteEffects.None, 0.0f);
}
Declare a button:
Button btn = new Button(position where you want the button, texture for the button);
btn.Clicked += () => { /* Handle button clicked code here */ };
In your update method inside your main game:
public void Update (GameTime gameTime)
{
MouseState mouseState = Mouse.GetState();
if(mouseState.LeftButton == ButtonState.Pressed) // check if mouse is clicked
{
btn.HandleClicked(new Vector2(mouseState.X, mouseState.Y)); // If true then the button clicked event will fire
// Here you can also change the color of the button if the button is currently clicked
}
// Here you can change the color of the button if the mouse is hover over the control
// Example:
btn.Tint = btn.HandleEntered(new Vector2(mouseState.X, mouseState.Y)) ? Color.White * 0.75f : Color.White;
}
Note: You can also use a rectangle for the button to adjust its size instead of strictly using the textures dimensions. Hope this gives some insight.
So here's what was going on: I had a bullet class in my game for every bullet shot. In this class I check whether the bullets hits nothing, hits the asteroid, or destroys the asteroids. If the latter is true then I would increment playerScore by 5. PlayerScore was a Game1 attribute so I thought the easiest way to do this would be to create a new Game1 in bullet.cs to allow me to refer to the variable. Deleting the "Main mainGame = new Main():" in Bullet.cs fixed this issue and I think the issue was coming from a new graphics device being made every single time I fired a single bullet.

XNA 2D Platformer Collision and Gravity

I know this question might get asked a lot and for that I am sorry. But I have had trouble with collisions in my game for a while and I would like some help.
First off, the game is a 2D Platformer. Each solid is put in a list. I have this code for collision detection which works pretty good for me:
if (player.rectangle.Intersects(rect))
{
player1Collision = true;
colSolid = solid;
colRectangle = rect;
}
if (player1Collision)
{
Vector2 pos = player.position;
Vector2 pLeft = new Vector2(player.BoundingBox.Left, 0);
Vector2 pRight = new Vector2(player.BoundingBox.Right, 0);
Vector2 pTop = new Vector2(0, player.BoundingBox.Top);
Vector2 pBottom = new Vector2(0, player.BoundingBox.Bottom);
Vector2 sLeft = new Vector2(colSolid.BoundingBox.Left, 0);
Vector2 sRight = new Vector2(colSolid.BoundingBox.Right, 0);
Vector2 sTop = new Vector2(0, colSolid.BoundingBox.Top);
Vector2 sBottom = new Vector2(0, colSolid.BoundingBox.Bottom);
if (player.rectangle.Intersects(colRectangle))
{
if (player.velocity.X > 0 && Vector2.Distance(pRight, sLeft) < player.texture.Width / 2)//left
{
player.velocity.X = 0f;
pos.X = colSolid.BoundingBox.Left - player.BoundingBox.Width;
}
else if (player.velocity.X < 0 && Vector2.Distance(pLeft, sRight) < player.texture.Width / 2)//right
{
player.velocity.X = 0f;
pos.X = colSolid.BoundingBox.Right;
}
if (player.velocity.Y > 0 && Vector2.Distance(pBottom, sTop) < player.texture.Height/ 2) //top
{
player.velocity.Y = 0f;
player.gravityOn = false;
pos.Y = colSolid.BoundingBox.Top - player.BoundingBox.Height;
}
else if (player.velocity.Y < 0 && Vector2.Distance(pTop, sBottom) < player.texture.Height / 2)//bottom
{
player.velocity.Y = 0f;
pos.Y = colSolid.BoundingBox.Bottom;
}
player.position = pos;
}
else
{
player.gravitySpeed = 0.15f;
player.gravityOn = true;
}
}
However the problem is that if the player is not intersecting with the rectangle I set the gravity to on, therefore he falls continuously as he collides with the solid and then is put on top to not collide with it. All I need to know is: how can I avoid this? Is there any other way that I could set the gravity to on without the player falling towards the solid continuously, only to be put back on top of the solid to fall again?
Any help is appreciated.
The way I address this problem may not be optimal (in fact I'm sure it probably isn't) but it has worked for me in all my 2D platforming projects so far.
I begin by defining a second rectangle for the sprite class. This rectangle will have the same Width and X coordinate as the main bounding box, but it will be slightly taller (in my case 2 or 3). You will also need to offset it so that the bottom edges of both rectangles are inline, to illustrate:
Rectangle boundingRect = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height);
Rectangle gravityRect = new Rectangle((int)boundingRect.X, (int)boundingRect.Y - 3, texture.Width, texture.Height + 3);
The sprite class also needs a bool to keep track of if the player should be falling. And one to keep track of whether it is solid (which you obviously assign as desired, during initialization).
public bool isGrounded = false;
bool isSolid;
At the top of my Game1 class, I declare 2 ints:
int gravityTotalI = 0;
int gravityCounterI = 0;
When initializing my sprites, I usually add them all to a List. So that I can do this:
foreach (Sprite s in spriteList)
{
if (s.isSolid)
{
gravityTotalI++;
}
}
Now, I use this bit of logic in the Game1 Update Method:
foreach (Sprite s in spriteList)
{
if (!s.Equals(player)
{
if (player.boundingRect.Intersects(s.boundingRect) || player.boundingRect.Intersects(s.gravityRect))
{
player.isGrounded = true;
gravityCounterI = 0;
}
else
{
gravCounterI++;
if (gravCounterI >= gravTotalI)
{
player.isGrounded = false;
gravCounterI = 0;
}
}
if (player.boundingRect.Intersects(s.boundingRect))
{
player.position.Y -= 2f; //set the resistance of the platform here
}
}
} //end of foreach loop.
if (!player.isGrounded)
{
player.position.Y += 2f; //set the force of gravity here.
}
Building a decent directional collision engine is a different thing, but this technique will handle the basics (and get rid of that infernal bouncing).
Hope this isn't too long-winded/doesn't miss out anything important, and I really hope it helps - I struggled with exactly the same problem as you for a long time, and I know how frustrating it can be!
I'm looking forward to seeing others' techniques for handling this!

actionscript 3.0 built-in collision detection seems to be flawed even with perfect rectangles

This is my first post. I hope the answer to this is not so obviously found- I could not find it.
I have a collision detection project in as3- I know that odd shapes will not hit the built-in detection methods perfectly, but supposedly perfect rectangles are exactly the shape of the bounding boxes they are contained it- yet- running the code below, I find that every once in a while a shape will not seem to trigger the test at the right time, and I cannot figure out why.
I have below two classes- one creates a rectangle shape, and a main class which creates a shape with random width and height, animates them from the top of the screen at a random x value towards the bottom at a set rate, mimicking gravity. If a shape hits the bottom of the screen, it situates itself half way between the displayed and undisplayed portions of the stage about its lower boundary, as expected- but when two shapes eventually collide, the expected behavior does not always happen- the expected behavior being that the shape that has fallen and collided with another shape should stop and rest on the top of the shape it has made contact with, whereas sometimes the falling shape will fall partially or completely through the shape it should have collided with.
does anyone have any idea why this is?
here are my two classes below in their entirety:
// box class //
package
{
import flash.display.Sprite;
public class Box extends Sprite
{
private var w:Number;
private var h:Number;
private var color:uint;
public var vx:Number = 0;
public var vy:Number = 0;
public function Box(width:Number=50,
height:Number=50,
color:uint=0xff0000)
{
w = width;
h = height;
this.color = color;
init();
}
public function init():void{
graphics.beginFill(color);
graphics.drawRect(0, 0, w, h);
graphics.endFill();
}
}
}
//main class//
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Boxes extends Sprite
{
private var box:Box;
private var boxes:Array;
private var gravity:Number = 16;
public function Boxes()
{
init();
}
private function init():void
{
boxes = new Array();
createBox();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(event:Event):void
{
box.vy += gravity;
box.y += box.vy;
if(box.y + box.height / 2 > stage.stageHeight)
{
box.y = stage.stageHeight - box.height / 2;
createBox();
}
for(var i:uint = 0; i < boxes.length; i++)
{
if(box != boxes[i] && box.hitTestObject(boxes[i]))
{
box.y = boxes[i].y - box.height;
createBox();
}
}
}
private function createBox():void
{
box = new Box(Math.random() * 40 + 10,
Math.random() * 40 + 10,
0xffaabb)
box.x = Math.random() *stage.stageWidth;
addChild(box);
boxes.push(box);
}
}
}
Make sure box.vy never exceeds any of the heights of any boxes created. Otherwise, it is possible the box can pass through other boxes while falling. (if box.vy = 40 and boxes[i].height=30, it is possible to pass right over it).
Just add a check:
if(box.vy>terminalVelocity)box.vy=terminalVelocity)
Where terminalVelocity is whatever the minimum height a box can be (in your code, it looks like 10). If you really want those small boxes, you will have to use something more precise than hitTestObject.

Dealing with game cursor, not windows cursor

Earlier, I had an issue with my Windows cursor being uncoordinated with the game and asked here how I could solve this. A member suggested me to hide the Windows cursor and create a custom game cursor, so I did this. However, a new problem occurred.
My game cursor is usually offset to the right of the Windows mouse, so when I want to move the game cursor to the left side of the window and click my left mouse button, it causes a disturbance to the game, such as bringing an application in the background to the top.
Here is a picture of what I mean: http://i.imgur.com/nChwToh.png
As you can see, the game cursor is offset to the right of the Windows cursor, and if I use game cursor to click on something on the left side of the window, the application in the background (Google Chrome in this case), will be brought up to the front, causing disturbance to the game.
Is there anything I can do to use my game cursor without any disturbances?
I have just tried to move everything out of their classes, all into the main Game class.
This fixed the problem, but does not give me an answer to WHY this happens.
The code is exactly the same, it's just organized to separate classes.
So, does anyone know why this is?
Why is using object-oriented programming instead of putting everything in the game class going mess up my mouse coordination and stuff?
Normally, you would have a texture for you in-game cursor where, for instance, the pixel at [16,16] is where you are "aiming" (the center of a crosshair, for instance). What you owuld to to draw this centered on the mouse is to use Mouse.GetState() to get the position, and then offset the drawing of your mouse-texture by the negative of the "center" of the "aim"-point.
so let's say we make a custom Mouse-Class:
public class GameMouse
{
public Vector2 Position = Vector2.Zero;
private Texture2D Texture { get; set; }
private Vector2 CenterPoint = Vector2.Zero;
public MouseState State { get; set; }
public MouseState PreviousState { get; set; }
//Returns true if left button is pressed (true as long as you hold button)
public Boolean LeftDown
{
get { return State.LeftButton == ButtonState.Pressed; }
}
//Returns true if left button has been pressed since last update (only once per click)
public Boolean LeftPressed
{
get { return (State.LeftButton == ButtonState.Pressed) &&
(PreviousState.LeftButton == ButtonState.Released); }
}
//Initialize texture and states.
public GameMouse(Texture2D texture, Vector2 centerPoint)
{
Texture = texture;
CenterPoint = centerPoint;
State = Mouse.GetState();
//Calling Update will set previousstate and update Position.
Update();
}
public void Update()
{
PreviousState = State;
State = Mouse.GetState();
Position.X = State.X;
Position.Y = State.Y;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
spriteBatch.Draw(Texture, Position - CenterPoint, Color.White);
spriteBatch.End();
}
}

XNA Snap sprite to a tile map

I'm looking for the best option on how to handle snapping sprites to a tilemap. I'm trying to make a Chu Chu Rocket clone. If you dont know the game. It is a tilebased game where you place arrows on a specfic tile to direct unts around the maps. So I need to snap the sprites to the center of the tile at all times and then detect a collision with either an arrow which takes up a whole tile or a wall or other obstruction. Any ideas on what the based way would be to detect those things since it would require different kinds of collision detection i believe.
The easiest way to snap the sprites to a tile is to draw them centered at a tile. The collision detection can be done in your update function by checking against your level object.
class Mouse
{
public int XTile;
public int YTile;
public int XDelta;
public int YDelta;
}
//in Update
if (Level[mouse.YTile][mouse.XTile] == Tiles.Arrow)
{
//change mouse.XDelta and mouse.YDelta based on the direction of the arrow
}
if (Level[mouse.YTile + YDelta][mouse.XTile + XDelta] == Tiles.Wall)
{
//change mouse.XDelta and mouse.YDelta based on wall rules
}
//in Draw
int tileSize = 32; //or whatever size tile you are using
spriteBatch.Draw(mouseSprite, new Vector2(mouse.XTile * tileSize,
mouse.YTile * tileSize), Color.White);
//or, if the mouseSprite doesn't take up the whole tile
int sizeDifference = tileSize - mouseSprite.Width;
spriteBatch.Draw(mouseSprite, new Vector2(mouse.XTile * tileSize + sizeDifference / 2f,
mouse.YTile * tileSize + sizeDifference / 2f), Color.White);

Resources