XNA - No loading screen or menu - c#

The problem is that it just shows a black screen and the loading mouse. It doesn't show the loading screen or the menu.
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteBatch mBatch;
Texture2D mTheQuantumBros2;
MenuComponent menuComponent;
public static Rectangle screen;
public static string GameState = "Menu";
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferMultiSampling = false;
graphics.IsFullScreen = true;
graphics.PreferredBackBufferWidth = 1366;
graphics.PreferredBackBufferHeight = 768;
graphics.ApplyChanges();
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
mBatch = new SpriteBatch(this.graphics.GraphicsDevice);
ContentManager aLoader = new ContentManager(this.Services);
aLoader.RootDirectory = "Content";
mTheQuantumBros2 = aLoader.Load<Texture2D>("TheQuantumBros2") as Texture2D;
menuComponent.LoadContent(Content);
}
protected override void UnloadContent()
{
}
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
switch (GameState)
{
case "Menu":
menuComponent.Update(gameTime);
break;
}
base.Update(gameTime);
}
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
switch (GameState)
{
case "Menu":
menuComponent.Draw(spriteBatch);
break;
}
base.Draw(gameTime);
}
}
Other class:
class MenuComponent
{
KeyboardState keyboard;
KeyboardState prevKeyboard;
SpriteBatch mBatch;
Texture2D mTheQuantumBros2;
GameTime gameTime;
MouseState mouse;
MouseState prevMouse;
SpriteFont spriteFont;
List<string> buttonList = new List<string>();
int selected = 0;
public MenuComponent()
{
buttonList.Add("Campaign");
buttonList.Add("Multiplayer");
buttonList.Add("Zombies");
buttonList.Add("Quit Game");
}
public void LoadContent(ContentManager Content)
{
spriteFont = Content.Load<SpriteFont>("Font");
}
public void Update(GameTime gameTime)
{
keyboard = Keyboard.GetState();
mouse = Mouse.GetState();
if (CheckKeyboard(Keys.Up))
{
if (selected > 0) selected--;
}
if (CheckKeyboard(Keys.Down))
{
if (selected < buttonList.Count - 1) selected++;
}
prevMouse = mouse;
prevKeyboard = keyboard;
}
public bool CheckMouse()
{
return (mouse.LeftButton == ButtonState.Pressed && prevMouse.LeftButton == ButtonState.Released);
}
public bool CheckKeyboard(Keys key)
{
return (keyboard.IsKeyDown(key) && prevKeyboard.IsKeyDown(key));
}
public void Draw(SpriteBatch spriteBatch)
{
Color color;
int linePadding = 3;
spriteBatch.Begin();
mBatch.Begin();
mBatch.Draw(mTheQuantumBros2, new Rectangle(300, 150, mTheQuantumBros2.Width, mTheQuantumBros2.Height), Color.White);
if (gameTime.TotalGameTime.TotalSeconds <= 3)
{
mBatch.End();
for (int i = 0; i < buttonList.Count; i++)
{
color = (i == selected) ? Color.LawnGreen : Color.Gold;
spriteBatch.DrawString(spriteFont, buttonList[i], new Vector2((Game1.screen.Width / 2) - (spriteFont.MeasureString(buttonList[i]).X / 2), (Game1.screen.Height / 2) - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding) * i)), color);
}
spriteBatch.End();
}
}
}

What is the purpose of this statement: (gameTime.TotalGameTime.TotalSeconds <= 3)?
Also, you are never updating the game time in the menu component. So, the aforementioned code would behave unexpectedly.
You are also calling spriteBatch.Begin() twice before end is called... So that should be giving you an error. Check those for issues.
EDIT: Since you are only calling spriteBatch.End() IF less than 3 seconds have passed, it will never be called again after that? I think.
As a potential fix... I would try only calling spriteBatch.Begin() and spriteBatch.End() inside of game1.cs. So:
//In your menu class
public void Draw(SpriteBatch spriteBatch)
{
Color color;
int linePadding = 3;
if (gameTime.TotalGameTime.TotalSeconds <= 3)
{
mBatch.Begin();
mBatch.Draw(mTheQuantumBros2, new Rectangle(300, 150, mTheQuantumBros2.Width, mTheQuantumBros2.Height), Color.White);
mBatch.End();
}
else
{
for (int i = 0; i < buttonList.Count; i++)
{
color = (i == selected) ? Color.LawnGreen : Color.Gold;
spriteBatch.DrawString(spriteFont, buttonList[i], new Vector2((Game1.screen.Width / 2) - (spriteFont.MeasureString(buttonList[i]).X / 2), (Game1.screen.Height / 2) - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding) * i)), color);
}
}
}
And back in game1.cs, call spriteBatch.End() right before base.Draw() is called.
In general, it is best to only use one spriteBatch, I believe it is simply faster than beginning and ending two different batches.
EDIT 2:
Just uhm... copy and paste I guess. It works fine after the adjustments I made (you can read about them at the bottom).
You're refactored code:
game1.cs:
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
MenuComponent menuComponent;
public static Rectangle screen;
public static string GameState = "Menu";
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferMultiSampling = false;
//graphics.IsFullScreen = true;
graphics.PreferredBackBufferWidth = 1366;
graphics.PreferredBackBufferHeight = 768;
graphics.ApplyChanges();
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
menuComponent = new MenuComponent();
menuComponent.LoadContent(Content, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
}
protected override void UnloadContent()
{
}
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
switch (GameState)
{
case "Menu":
menuComponent.Update(gameTime);
break;
}
base.Update(gameTime);
}
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
switch (GameState)
{
case "Menu":
menuComponent.Draw(spriteBatch, gameTime);
break;
}
spriteBatch.End();
base.Draw(gameTime);
}
MenuComponent:
KeyboardState keyboard;
KeyboardState prevKeyboard;
MouseState mouse;
MouseState prevMouse;
GraphicsDevice graphicsDevice;
Texture2D mTheQuantumBros2;
SpriteFont spriteFont;
List<string> buttonList = new List<string>();
int selected = 0;
int screenWidth;
int screenHeight;
public MenuComponent()
{
buttonList.Add("Campaign");
buttonList.Add("Multiplayer");
buttonList.Add("Zombies");
buttonList.Add("Quit Game");
}
public void LoadContent(ContentManager Content, int _screenWidth, int _screenHeight)
{
spriteFont = Content.Load<SpriteFont>("Font");
mTheQuantumBros2 = Content.Load<Texture2D>("TheQuantumBros2");
screenHeight = _screenHeight;
screenWidth = _screenWidth;
}
public void Update(GameTime gameTime)
{
keyboard = Keyboard.GetState();
mouse = Mouse.GetState();
if (CheckKeyboard(Keys.Up))
{
if (selected > 0) selected--;
}
if (CheckKeyboard(Keys.Down))
{
if (selected < buttonList.Count - 1) selected++;
}
prevMouse = mouse;
prevKeyboard = keyboard;
}
public bool CheckMouse()
{
return (mouse.LeftButton == ButtonState.Pressed && prevMouse.LeftButton == ButtonState.Released);
}
public bool CheckKeyboard(Keys key)
{
return (keyboard.IsKeyDown(key) && prevKeyboard.IsKeyDown(key));
}
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
Color color;
int linePadding = 3;
if (gameTime.TotalGameTime.TotalSeconds <= 3)
{
spriteBatch.Draw(mTheQuantumBros2, new Rectangle(300, 150, mTheQuantumBros2.Width, mTheQuantumBros2.Height), Color.White);
}
else
{
for (int i = 0; i < buttonList.Count; i++)
{
color = (i == selected) ? Color.LawnGreen : Color.Gold;
spriteBatch.DrawString(spriteFont, buttonList[i], new Vector2((screenWidth / 2) - (spriteFont.MeasureString(buttonList[i]).X / 2), (screenHeight / 2) - (spriteFont.LineSpacing * (buttonList.Count) / 2) + ((spriteFont.LineSpacing + linePadding) * i)), color);
}
}
}
There were a bunch of little issues. For example, you were setting the menuComp = to a new menu component on every update call, so all the old variables in there would be lost, hence there was no images loading. SpriteBatch.Begin() was being called twice in a row, and then end was being called twice in a row. One spriteBatch (from game1.cs preferrably) should be used to draw. By sending that spritebatch through the method, you do not need to call begin again, and it is simply better not to for performance reasons. Last thing I noticed (that I can think of) was that the graphics device was not being set to anything because you were constantly creating a new version of it. Oh also, you were calling graphicsDevice.Clear() way too early, this only should be called once per draw (at the beginning, so old graphical info is removed from the screen).

I debugged your program/code and there are a few problems:
There is a declaration of MenuComponent menuComponent, but you didn't create an instance in the Game1() constructor. So add: menuComponent = new MenuComponent()
There is a declaration of SpriteBatch mBatch, but you didn't create an instance in the MenuComponent() constructor. So create one. The same for GameTime gameTime variable.
At the moment I don't have SpriteFont and TheQuantumBros2 texture. Is it possible that you upload your project and share it?

Related

Move enemy sprite depending on which side it spawns. c# monogame

So I have a code where the sprite spawn outside the window and I want it to move on a specific straight line depending on where it spawn say if the sprite spawn at the top it goes at the bottom and vise versa if the sprite then spawn to the left it will go right and vise versa.
Game1.cs code:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player player;
List<Enemy> enemies = new List<Enemy>();
public Vector2 ecords
{
get { return ecords; }
set { ecords = value; }
}
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
//player
Texture2D playertexture = Content.Load<Texture2D>("Player");
player = new Player(new Vector2(350, 175), playertexture);
//enemy
Texture2D enemytexture = Content.Load<Texture2D>("Enemy");
Random random = new Random();
var width = GraphicsDevice.Viewport.Width;
var height = GraphicsDevice.Viewport.Height;
for (int i = 0; i < 20; i++)
{
enemies.Add(new Enemy(new Vector2(random.Next(width, width + 100), random.Next(0, height)), enemytexture));
enemies.Add(new Enemy(new Vector2(random.Next(0 - 100, 0), random.Next(0, height)), enemytexture));
enemies.Add(new Enemy(new Vector2(random.Next(0, width), random.Next(-100, 0)), enemytexture));
enemies.Add(new Enemy(new Vector2(random.Next(0, width), random.Next(height, height + 100)), enemytexture));
}
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
foreach (Enemy enemy in enemies)
{
enemy.Update(gameTime);
}
player.Update(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
foreach (Enemy enemy in enemies)
{
enemy.Draw(spriteBatch);
}
player.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
Enemy.cs
class Enemy
{
Texture2D enemytexture;
Vector2 enemyposition;
public Enemy(Vector2 enemyposition, Texture2D enemytexture)
{
this.enemyposition = enemyposition;
this.enemytexture = enemytexture;
}
public void Update(GameTime gameTime)
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(enemytexture, enemyposition, Color.White);
}
}
One option would be to add a velocity (or you can name it movement/direction) to Enemy, passed to the constructor in a parameter just like your existing enemyposition. Then update the current position by adding the velocity in the Update method of Enemy:
public void Update(GameTime gameTime)
{
this.enemyposition += this.velocity;
}
You can use unit vectors (optionally multiplied by speed) for the velocity value:
var (left, right) = (-Vector2.UnitX, Vector2.UnitX);
var (up, down) = (-Vector2.UnitY, Vector2.UnitY);
float enemySpeed = 5.0f;
enemies.Add(new Enemy(
new Vector2(random.Next(width, width + 100), random.Next(0, height)),
enemytexture, velocity: left * enemySpeed));
// etc.

all menu item's become selectable

I am trying to create a simple menu, the string that is selected changes colur as it is instructed to do, I just can't seem to space out each item in the string list on the Y axis, currently they are all positioned in the middle but at the top of the screen overlapping each other. I know this is probably a very simple fix but I am a novice at XNA. Any help would be very appreciated. Thanks in advance.
MenuManagement Class
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Game2
{
class MenuManagement
{
KeyboardState keyboard;
KeyboardState prevKey;
MouseState mouse;
Vector2 position;
List<String> buttonList = new List<string>();
SpriteFont spriteFont;
int selected = 0;
public MenuManagement ()
{
buttonList.Add("Play");
buttonList.Add("Options");
buttonList.Add("instructions");
buttonList.Add("Exit");
}
private void MeasureMenu()
{
height = 0;
width = 0;
foreach (string item in buttonList)
{
Vector2 size = spriteFont.MeasureString(item);
height += spriteFont.LineSpacing + 5;
}
}
public void LoadContent (ContentManager Content )
{
spriteFont = Content.Load<SpriteFont>("spriteFont");
}
public void Update (GameTime theGameTime)
{
keyboard = Keyboard.GetState();
if (checkKeyBoard(Keys.Up))
{
if (selected > 0)
{
selected--;
}
}
if (checkKeyBoard(Keys.Down))
{
if (selected < buttonList.Count - 1)
{
selected++;
}
}
prevKey = keyboard;
}
public bool checkKeyBoard (Keys key)
{
return (keyboard.IsKeyDown(key) && prevKey.IsKeyDown(key));
}
public void Draw (SpriteBatch theSpriteBatch)
{
theSpriteBatch.Begin();
Color color;
for (int i = 0; i < buttonList.Count; i++)
{
Vector2 location = position;
if (i == selected)
{
color = Color.Yellow;
}
else
{
color = Color.Blue;
}
location.Y += spriteFont.LineSpacing + 5;
}
theSpriteBatch.DrawString(spriteFont, buttonList[0], new Vector2 (300, 100), color);
theSpriteBatch.DrawString(spriteFont, buttonList[1], new Vector2(300, 150), color);
theSpriteBatch.DrawString(spriteFont, buttonList[2], new Vector2(300, 200), color);
theSpriteBatch.DrawString(spriteFont, buttonList[3], new Vector2(300, 250), color);
theSpriteBatch.End();
}
}
}
Game1
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Game2
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch theSpriteBatch;
public static Rectangle screen;
public static string GameState = "Menu";
MenuManagement menuManagement;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
menuManagement = new MenuManagement();
screen = new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
base.Initialize();
}
protected override void LoadContent()
{
theSpriteBatch = new SpriteBatch(GraphicsDevice);
menuManagement.LoadContent(Content);
// TODO: use this.Content to load your game content here
}
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)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
switch (GameState)
{
case "Menu":
menuManagement.Update(gameTime);
break;
}
base.Update(gameTime);
}
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
switch (GameState)
{
case "Menu":
menuManagement.Draw(theSpriteBatch);
break;
}
base.Draw(gameTime);
}
}
}
You can calculate the length of the strings and place the next item where you want. You should look to SpriteFont.MeasureString().
https://msdn.microsoft.com/en-us/library/bb464128(v=xnagamestudio.30).aspx
To be clear, the reason they are overlapping is because you are putting them all in the same position:
Vector2 location = position;
and then:
new Vector2 (300, location.Y)
is where you are drawing the entire batch. You need to change the position of each of the menu items. The simplest fix is to increment the Y value of the location for each item. That will move the next menu item toward the bottom. Increment X to move right.

How can I measure the time of a drag on my Windows Phone?

I want to measure the time of a drag. From the beginning(when the player touches the screen) to the end(when the player releases his finger from the screen).
In addition, I want to measure the distance of the drag to calculate the velocity of the drag.
But I always get the following two error messages.
1)When I touche the screen I get this error message in the first line of the foreach loop:
GestureSample gs = TouchPanel.ReadGesture();
An exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.Input.Touch.ni.dll but was not handled in user code
If there is a handler for this exception, the program may be safely continued.
2)The second error message is in this line:
DragTime = (float)(EndTime - StartTime);
Cannot convert type 'System.DateTime' to 'float'
What is wrong? What can I do to fix the error messages?
Here is my code:
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Vector2 DragVelocity;
TimeSpan StartTime;
DateTime EndTime;
float DragTime;
Vector2 StartPoint, EndPoint, DragDistance;
bool FirstTimePressed = true;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
TargetElapsedTime = TimeSpan.FromTicks(333333);
InactiveSleepTime = TimeSpan.FromSeconds(1);
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
TouchPanel.EnabledGestures = GestureType.FreeDrag;
}
protected override void Update(GameTime gameTime)
{
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
GestureSample gs = TouchPanel.ReadGesture();
if (FirstTimePressed == true)
{
if ((tl.State == TouchLocationState.Pressed))
{
StartTime = gs.Timestamp;
StartPoint = gs.Delta;
FirstTimePressed = false;
}
}
if ((tl.State == TouchLocationState.Released))
{
EndTime = DateTime.Now;
DragTime = (float)(EndTime - StartTime);
EndPoint = gs.Delta;
DragDistance = EndPoint - StartPoint;
DragVelocity = DragDistance / DragTime;
FirstTimePressed = true;
}
}
while (TouchPanel.IsGestureAvailable)
{
GestureSample gs = TouchPanel.ReadGesture();
switch (gs.GestureType)
{
case GestureType.FreeDrag:
break;
}
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
base.Draw(gameTime);
}
}
If I were you I would do it this way- when user presses the screen for the first time, set a global variable TimeSpan time to TimeSpan.Zero. Then, on every update, add gameTime.ElapsedRealTime to time variable. When user releases, your can get your time from time variable, it's easy. To get seconds just use: time.totalSeconds.
I've modified your code a little, here you go:
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
float DragVelocity, DragDistance, DragTime;
TimeSpan time;
Vector2 StartPoint, EndPoint;
bool isThisFirstTime = true;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
TargetElapsedTime = TimeSpan.FromTicks(333333);
InactiveSleepTime = TimeSpan.FromSeconds(1);
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
TouchPanel.EnabledGestures = GestureType.DragComplete | GestureType.FreeDrag;
}
protected override void Update(GameTime gameTime)
{
while (TouchPanel.IsGestureAvailable)
{
GestureSample gs = TouchPanel.ReadGesture();
switch (gs.GestureType)
{
case GestureType.FreeDrag:
if (isThisFirstTime == true)
{
time = TimeSpan.Zero;
StartPoint = gs.Position;
isThisFirstTime = false;
}
else
{
EndPoint = gs.Position;
time += gameTime.ElapsedGameTime;
}
break;
case GestureType.DragComplete:
isThisFirstTime = true;
DragTime = (float) time.TotalSeconds;
DragDistance = Vector2.Distance(StartPoint, EndPoint);
DragVelocity = DragDistance / DragTime;
break;
}
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
base.Draw(gameTime);
}
}

XNA - The name 'ball' does not exist in the current context

I'm working on a pong game since I'm pretty new to XNA, and I've ran into a problem...
i have 3 classes, "Game1.cs", "Ball.cs", and "GreenPaddle.cs".
The GreenPaddle.cs contains Rectangle gpRect, Texture2D gPtexture, Vector2 position.
I have movement and such, and in the ball class I have an intersect boolean.
But when i try to initialize it in game1.cs i get errors. Here are the classes:
GreenPaddle.cs:
public class GreenPaddle
{
Texture2D gPtexture;
public Vector2 position;
public Rectangle gpRect;
public Vector2 origin;
public int speed = 2;
public GreenPaddle()
{
}
public void LoadContent(ContentManager Content)
{
gPtexture = Content.Load<Texture2D>("greenpaddle");
position = new Vector2(20, 200);
gpRect = new Rectangle((int)position.X, (int)position.Y,
gPtexture.Width, gPtexture.Height);
}
public void Update(GameTime gameTime)
{
KeyboardState keyState = Keyboard.GetState();
//Movement
PaddleMovement();
//Border Collision
isCollidingWithBorders();
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(gPtexture, position, gpRect, Color.LawnGreen);
}
public Boolean isCollidingWithBorders()
{
if (position.Y < 83 && gpRect.Y < 83)
{
position.Y = 83;
gpRect.Y = 83;
return true;
}
if (position.Y > 400 && gpRect.Y > 400)
{
position.Y = 400;
gpRect.Y = 400;
return true;
}
else { return false; }
}
public void PaddleMovement()
{
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.W))
{
position.Y -= speed;
gpRect.Y -= speed;
}
if (keyState.IsKeyDown(Keys.S))
{
position.Y += speed;
gpRect.Y += speed;
}
}
}
Ball.cs:
public class Ball
{
GreenPaddle gPaddle;
Texture2D ballTexture;
Vector2 ballPosition;
Rectangle ballRect;
int speed = 2;
bool movingUp, movingLeft;
public Ball(GreenPaddle paddle)
{
this.gPaddle = paddle;
movingLeft = true;
movingUp = true;
}
public void LoadContent(ContentManager Content)
{
ballTexture = Content.Load<Texture2D>("ball");
ballPosition = new Vector2(380, 225);
ballRect = new Rectangle((int)ballPosition.X, (int)ballPosition.Y,
ballTexture.Width, ballTexture.Height);
}
public void Update(GameTime gameTime)
{
BallMovement();
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(ballTexture, ballPosition, ballRect, Color.White);
}
public void BallMovement()
{
if (movingUp) { ballPosition.Y -= speed; }
if (!movingUp) { ballPosition.Y += speed; }
if (movingLeft) { ballPosition.X -= speed; }
if (!movingLeft) { ballPosition.X += speed; }
if (ballRect.Intersects(gPaddle.gpRect))
movingLeft = !movingLeft;
movingUp = !movingUp;
if (ballPosition.Y < 85)
{
movingUp = false;
}
}
}
Game1.cs:
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
GreenPaddle gPaddle = new GreenPaddle();
Texture2D BackGround;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferHeight = 500;
}
protected override void Initialize()
{
Ball ball = new Ball(gPaddle);
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
BackGround = Content.Load<Texture2D>("pongBG");
gPaddle.LoadContent(Content);
//ball.LoadContent(Content);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <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();
gPaddle.Update(gameTime);
ball.Update(gameTime);//Error Line
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(BackGround, new Vector2(0f, 0f), Color.White);
gPaddle.Draw(spriteBatch);
ball.Draw(spriteBatch);//Error Line
spriteBatch.End();
base.Draw(gameTime);
}
}
Thats it, I don't know what to do with the initialize part :/
Look carefully how you initialize your ball, you declare it in the scope of the method (Between the braces). This means you cannot access it anywhere else, which you are trying to do in the Update and Draw methods.
protected override void Initialize()
{
Ball ball = new Ball(gPaddle);
base.Initialize();
}
Additionally, as soon as the function ends your Ball object is deleted.
This can be fixed by putting Ball ball into your class scope so that it is available to all members of the class, like so:
Ball ball; //In the class scope
protected override void Initialize()
{
ball = new Ball(gPaddle);
base.Initialize();
}
If your not familiar with scopes, check out this article (Nothing really good on MSDN)

Reset Texture2Ds in XNA

I'm Having a problem with an experiment of mine. I'm trying to make a method that fuses one Texture2D into another Texture2D, then reloads the Texture2D, this time moving the pasted texture in a new spot. I plan to perfect upon this method in later projects where I paste in a spotlight onto a dark background to "illuminate" the scenery behind it. While I managed to make the paste-to method work perfectly, I am having some major problems with the second part of my plan. I have the pasted texture set to a Vector2, where the X member increases by 1 every frame, thus dragging the pasted texture along the background. However, the background doesn't reset after each frame, leaving a drag mark on the background where the previous image was. For the last half hour I've been working to cure this problem by resetting the background texture to make it clean again for when it has the other image pasted onto it.
Here is my code.
namespace CopyTest
{
public class Image
{
public Texture2D Bitmap;
public Vector2 Position;
public String BitmapName;
public Rectangle Viewport;
public Color Tint = Color.White;
public void ResetViewportDimensions()
{
this.Viewport = new Rectangle(this.Viewport.X, this.Viewport.Y, Bitmap.Width, Bitmap.Height);
}
public void Draw(SpriteBatch Target)
{
}
public void FinalizeBitmap(ContentManager Target)
{
this.Bitmap = null;
this.Bitmap = Target.Load<Texture2D>(this.BitmapName);
}
public Image(Vector2 Position, String BitmapName)
{
this.BitmapName = BitmapName;
this.Position = Position;
}
}
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public Image Rainbow = new Image(new Vector2(0, 0), "Rainbow");
public Image Eye = new Image(new Vector2(0, 0), "Glow");
public Image PrintOut = new Image(new Vector2(0, 0), "Rainbow");
public Vector2 Destination = new Vector2(100, 50);
public void PrintTo(Image Source, Image Target, Vector2 Location)
{
Color[] A = new Color[Source.Bitmap.Width * Source.Bitmap.Width];
Color[] B = new Color[Target.Bitmap.Width * Target.Bitmap.Width];
int Y = 0;
int X = 0;
Source.Bitmap.GetData(A);
Target.Bitmap.GetData(B);
for (int i = 0; i < A.Length; i++)
{
B[(int)Location.X + X + (((int)Location.Y + Y) * Target.Bitmap.Width)] = A[i];
X++;
if (X == Source.Bitmap.Width)
{
X = 0;
Y++;
}
}
Target.Bitmap.SetData<Color>(B);
}
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Eye.FinalizeBitmap(Content);
Rainbow.FinalizeBitmap(Content);
PrintOut.FinalizeBitmap(Content);
Eye.ResetViewportDimensions();
Rainbow.ResetViewportDimensions();
PrintOut.ResetViewportDimensions();
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
GraphicsDevice.Textures[0] = null;
PrintOut.FinalizeBitmap(Content);
PrintTo(Eye, PrintOut, Destination);
Destination.Y++;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(PrintOut.Bitmap, PrintOut.Position, PrintOut.Viewport, PrintOut.Tint);
spriteBatch.End();
base.Draw(gameTime);
}
}
Any help at all would be greatly appreciated.

Categories