Advertisement
Guest User

Controls

a guest
Nov 1st, 2012
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.32 KB | None | 0 0
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Input;
  3.  
  4. namespace WindowsGame4
  5. {
  6.     class Controls
  7.     {
  8.         KeyboardState previousKeyState;
  9.         KeyboardState currentKeyState;
  10.  
  11.         float player_speed = 4.0f;
  12.         Vector2 gravity = new Vector2(0, 2.0f);
  13.         Vector2 jumpVector = new Vector2(0, -16.0f);
  14.  
  15.         public void Update(PlayerObject player)
  16.         {
  17.             //If we were on the ground, but the Yvelocity became higher than 0, then apperantly we are not on the ground anymore
  18.             if (player.PositionState == PositionState.onGround && player.Velocity.Y > 0)
  19.                 player.PositionState = PositionState.inAir;
  20.  
  21.             previousKeyState = currentKeyState;
  22.             currentKeyState = Keyboard.GetState();
  23.  
  24.             int direction_x = 0;
  25.             int direction_y = 0;
  26.  
  27.             if (currentKeyState.IsKeyDown(Keys.Left))
  28.                 direction_x = -1;
  29.             if (currentKeyState.IsKeyDown(Keys.Right))
  30.                 direction_x = 1;
  31.  
  32.             //only in space we have free movement in all directions
  33.             if (player.PositionState == PositionState.inSpace)
  34.             {
  35.                 if (currentKeyState.IsKeyDown(Keys.Up))
  36.                     direction_y = -1;
  37.                 if (currentKeyState.IsKeyDown(Keys.Down))
  38.                     direction_y = 1;
  39.             }
  40.  
  41.             Vector2 previousVelocity = player.Velocity;
  42.             player.Velocity = new Vector2(direction_x, direction_y) * player_speed;
  43.  
  44.             //When we aren't in space, we apply gravity
  45.             if (player.PositionState != PositionState.inSpace)
  46.             {
  47.                 player.Velocity += gravity;
  48.                 player.VelocityY += previousVelocity.Y;
  49.             }
  50.  
  51.             //You can only jump if you are on the ground
  52.             if (player.PositionState == PositionState.onGround)
  53.             {
  54.                 if (currentKeyState.IsKeyDown(Keys.Up) && previousKeyState.IsKeyUp(Keys.Up))
  55.                 {
  56.                     player.Velocity += jumpVector;
  57.                     player.PositionState = PositionState.inAir;
  58.                 }
  59.             }
  60.  
  61.             //Max falling speed, to avoid falling though tiles
  62.             if (player.Velocity.Y > 16)
  63.                 player.VelocityY = 16;
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement