Hjælp til spil
Så måtte det være... er gået i gang med at programmere(lære) 2D, og derefter 3D programming.Fandt et eksempel hos Microsoft hvordan man loader en texture og bevæger den.
Tænkte så at lave et "gammeldavs" ping-pong spil.
Så har loadet og tilføjet en "stick", som man skal kunne bevæge på Y aksen. Og det er så der jeg har brug for lidt assistance, for kan ikke få den til at bevæge sig ved hjælp af Up/Down tasterne.
Koden:
namespace WindowsGame1
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D myTexture;
Texture2D stickTexture;
Vector2 spritePosition = Vector2.Zero;
Vector2 spriteSpeed = new Vector2(100.0f, 100.0f);
Vector2 stickPosition = Vector2.Zero;
Vector2 stickSpeed = new Vector2(0, 100.0f);
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
myTexture = Content.Load<Texture2D>("smiley");
stickTexture = Content.Load<Texture2D>("stick");
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape)) this.Exit(); // ESC = Exit Game
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Up)) MoveStick(true, "Up",gameTime);
if (Keyboard.GetState(PlayerIndex.One).IsKeyUp(Keys.Up)) MoveStick(false, "Up", gameTime);
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Down)) MoveStick(true, "Down", gameTime);
if (Keyboard.GetState(PlayerIndex.One).IsKeyUp(Keys.Down)) MoveStick(false, "Down", gameTime);
UpdateSprite(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
spriteBatch.Draw(myTexture, spritePosition, Color.White);
spriteBatch.Draw(stickTexture, stickPosition, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
void UpdateSprite(GameTime gameTime)
{
spritePosition += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
int MinX = 0;
int MinY = 0;
int MaxX = graphics.GraphicsDevice.Viewport.Width - myTexture.Width;
int MaxY = graphics.GraphicsDevice.Viewport.Height - myTexture.Height;
if (spritePosition.X > MaxX)
{
spriteSpeed.X *= -1;
spritePosition.X = MaxX;
}
else if (spritePosition.X < MinX)
{
spriteSpeed.X *= -1;
spritePosition.X = MinX;
}
else if (spritePosition.Y > MaxY)
{
spriteSpeed.Y *= -1;
spritePosition.Y = MaxY;
}
else if (spritePosition.Y < MinY)
{
spriteSpeed.Y *= -1;
spritePosition.Y = MinY;
}
}
void MoveStick(bool keyPressed, string stickDirection, GameTime gameTime)
{
stickPosition += stickSpeed;
switch (stickDirection)
{
case "Up":
if (keyPressed) stickSpeed.Y *= -1;
if (!keyPressed) stickSpeed.Y = 0;
break;
case "Down":
if (keyPressed) stickSpeed.Y *= -1;
if (!keyPressed) stickSpeed.Y = 0;
break;
}
}
}
}