XNA programming a platformer - c#

"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);

Related

MonoGame Problem with renderize Texture2D on camera movement

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.

Drawing Multiple Sprites with Different Properties in XNA 4.0

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.

How do I fix my platformer collision detection?

I'm working on a game that allows my 2D sprite to jump on a platform but when it lands on the platform, my 2D sprite is not exactly on top of the platform, sometimes its exceeding or the same as the position of the platform.
//here is my code:
Texture2D jumper;
Texture2D tile;
Vector2 position, velocity;
Rectangle top;
Rectangle tile_rectangle;
Rectangle jumper_rectangle;
KeyboardState ks;
bool jump;
//here is my Load Content:
protected override void LoadContent()
{
jump = true;
position.X = 10;
position.Y = 10;
jumper = Content.Load<Texture2D>("character");
tile = Content.Load<Texture2D>("tile");
tile_rectangle = new Rectangle(300, 350, tile.Width, tile.Height);
top = new Rectangle(tile_rectangle.X, tile_rectangle.Y - 16, tile_rectangle.Width, 10);
}
//Here is my update:
protected override void Update(GameTime gameTime)
{
ks = Keyboard.GetState();
position += velocity;
float i = 1;
if (ks.IsKeyDown(Keys.Up) && jump == false)
{
position.Y -= 10f;
velocity.Y = -25f;
jump = true;
}
if (jump == true)
{
velocity.Y += 2f * i;
}
if (position.Y > 400)
{
jump = false;
}
if (jump == false)
{
velocity.Y = 0f;
}
BoundingBox();
if (ks.IsKeyDown(Keys.Right))
{
position.X += 5f;
velocity.X = +0.05f;
if (jumper_rectangle.Left > tile_rectangle.Right)
{
jump = true;
}
}
if (ks.IsKeyDown(Keys.Left))
{
position.X -= 5f;
velocity.X = -0.05f;
if (jumper_rectangle.Right < tile_rectangle.Left)
{
jump = true;
}
}
jumper_rectangle = new Rectangle((int)position.X, (int)position.Y, jumper.Width, jumper.Height);
BoundingBox();
base.Update(gameTime);
}
//here is my draw:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(jumper, jumper_rectangle, Color.White);
spriteBatch.Draw(tile, tile_rectangle, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
//here is my method on landing:
public void BoundingBox()
{
if (jumper_rectangle.Intersects(top))
{
if (jumper_rectangle.Bottom > top.Top)
{
position.Y--;
jump = false;
}
}
}
Where did i go wrong or is there some other way?

Attempting to get asteroids to move down screen themselves

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.

Getting Acces to Other Classes Variables

I'm working on a pong game, since i'm new at programming, i don't know how to get acess to another class variable. I have seperate classes, green and blue paddles, a ball, and game1.cs.
I control the ball movement with bool movingUp, movingLeft;
It bounces off the borders of the screen, but i don't know how to make it work with the paddles. Basically, how do i check the position of the paddle, and make so when the ball touches the paddle, it bounces off? I mean, how to detect the collision?
public class Ball
{
ParticleEngine particleEngine;
GraphicsDeviceManager graphics;
Texture2D texture;
Vector2 position;
Boolean movingUp, movingLeft;
Vector2 origin;
public Ball()
{
position = new Vector2(800 / 2, 330);
}
public void LoadContent(ContentManager Content)
{
texture = Content.Load<Texture2D>("ball");
movingLeft = true;
//Particle Engine
List<Texture2D> textures = new List<Texture2D>();
textures.Add(Content.Load<Texture2D>("pixel"));
particleEngine = new ParticleEngine(textures, new Vector2(400, 240));
}
public void Update(GameTime gameTime)
{
float speed = 2.5f;
//Physics
if (movingUp)
{
position.Y -= 3;
}
if (movingLeft)
{
position.X -= 3;
}
if (!movingUp)
{
position.Y += 3;
}
if (!movingLeft)
{
position.X += 3;
}
if (position.X <= 0 && movingLeft) movingLeft = false;
if (position.Y <= 85 && movingUp) movingUp = false;
if (position.X >= 800 - texture.Width && !movingLeft) movingLeft = true;
if (position.Y >= 500 - texture.Height && !movingUp) movingUp = true;
origin = new Vector2(position.X + texture.Width / 2, position.Y + texture.Height / 2);
//Particles
particleEngine.EmitterLocation = new Vector2(origin.X, origin.Y);
particleEngine.Update();
}
public void Draw(SpriteBatch spriteBatch)
{
particleEngine.Draw(spriteBatch);
spriteBatch.Draw(texture, position, Color.White);
}
}
One of the paddle classes (they look the same exept the name and movement keys):
public class GreenPaddle
{
Texture2D texture;
Vector2 position;
float speed = 2f;
public GreenPaddle()
{
position = new Vector2(10, 230);
}
public void LoadContent(ContentManager Content)
{
texture = Content.Load<Texture2D>("greenpaddle");
}
public void Update(GameTime gameTime)
{
KeyboardState keyState = Keyboard.GetState();
//Check If Keys Are Pressed // Movement
if (keyState.IsKeyDown(Keys.W))
position.Y -= speed;
if (keyState.IsKeyDown(Keys.S))
position.Y += speed;
//Check Border
if (position.Y < 87)
{
position.Y = 87;
}
if (position.Y > 396)
{
position.Y = 396;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
}
Thanks in advance, i really wish to learn things like this :D
Declare the variables you want to access as public, or create get methods.
For public variables you would do:
public Vector2 Position;
And to access it, you would call:
Ball ball;
ball.Position
For get method implement:
public Vector2 getPosition()
{
return Position;
}
And you would call that method to get the position.

Categories

Resources