private bool DidOpenDropMenu(KeyboardState keyboardState) { if (!keyboardState.IsKeyUp(Keys.O) || _lastKeyboardState?.IsKeyDown(Keys.O) != true) { return(false); } _lastKeyboardState = keyboardState; var openCommand = _commandFactory.GetCommand <OpenContainerCommand>(); var actor = _uiState.ActiveActor?.Actor; if (actor is null) { Debug.Fail( "Active actor must be assigned before the sector view model and the sector interactor start processing of user input."); return(true); } _uiState.SelectedViewModel = GetStaticObjectUnderActor(actor); if (openCommand.CanExecute().IsSuccess) { _commandPool.Push(openCommand); } return(true); }
private void HandleHotkeys() { var keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyUp(Keys.I) && _lastKeyboard?.IsKeyDown(Keys.I) == true) { _personPropButton.Click(); } else if (keyboardState.IsKeyUp(Keys.C) && _lastKeyboard?.IsKeyDown(Keys.C) == true) { _personStatsButton.Click(); } _lastKeyboard = keyboardState; }
private bool HandleHotKeys() { var keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyUp(Keys.T) && _lastKeyboardState?.IsKeyDown(Keys.T) == true) { _lastKeyboardState = keyboardState; var transitionCommand = _commandFactory.GetCommand <SectorTransitionMoveCommand>(); if (transitionCommand.CanExecute().IsSuccess) { _commandPool.Push(transitionCommand); } return(true); } if (keyboardState.IsKeyUp(Keys.O) && _lastKeyboardState?.IsKeyDown(Keys.O) == true) { _lastKeyboardState = keyboardState; var openCommand = _commandFactory.GetCommand <OpenContainerCommand>(); var actor = _uiState.ActiveActor?.Actor; if (actor is null) { Debug.Fail( "Active actor must be assigned befor sector view model and command input starts processing of user input."); return(true); } _uiState.SelectedViewModel = GetStaticObjectUnderActor(actor); if (openCommand.CanExecute().IsSuccess) { _commandPool.Push(openCommand); } return(true); } _lastKeyboardState = keyboardState; return(false); }
private void HandleHotkeys() { var keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyUp(Keys.Space) && _lastKeyboard?.IsKeyDown(Keys.Space) == true) { _travelPanel._idleButton.Click(); } _lastKeyboard = keyboardState; }
protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } KeyboardState prevKeyboard = keyboard; keyboard = Keyboard.GetState(); GamePadState prevGamepad = gamepad; gamepad = GamePad.GetState(PlayerIndex.One); Random random = new Random(); if (keyboard.IsKeyDown(Keys.F1) && prevKeyboard.IsKeyUp(Keys.F1)) { graphics.ToggleFullScreen(); } if (keyboard.IsKeyDown(Keys.F2) && prevKeyboard.IsKeyUp(Keys.F2)) { player.lives -= 1; } switch (gameState) { case GameState.startScreen: if (keyboard.IsKeyDown(Keys.Space) || gamepad.Buttons.A == ButtonState.Pressed) { gameState = GameState.menu; } break; case GameState.menu: menu.Update(); if (keyboard.IsKeyDown(Keys.Escape) && prevKeyboard.IsKeyUp(Keys.Escape) || gamepad.Buttons.Start == ButtonState.Pressed && prevGamepad.Buttons.Start == ButtonState.Released) { if (startedGame) { gameState = GameState.game; } } if (keyboard.IsKeyDown(Keys.Space) && prevKeyboard.IsKeyUp(Keys.Space) || gamepad.Buttons.A == ButtonState.Pressed && prevGamepad.Buttons.A == ButtonState.Released) { switch (menu.selected) { case 1: gameState = GameState.game; if (!startedGame) { Initialize(); startedGame = true; } break; case 2: gameState = GameState.howTo; break; case 3: this.Exit(); break; } } break; case GameState.levelTransition: if (keyboard.IsKeyDown(Keys.Space) && prevKeyboard.IsKeyUp(Keys.Space)) { resetLevel(); gameState = GameState.game; } break; case GameState.gameOver: gibs.Clear(); if (keyboard.IsKeyDown(Keys.Space) && prevKeyboard.IsKeyUp(Keys.Space)) { resetLevel(); Initialize(); gameState = GameState.menu; } break; case GameState.game: if (!this.IsActive) { gameState = GameState.menu; } player.Input(projectiles, particles); player.Update(); if (player.lives <= -1) { gameState = GameState.gameOver; } player.CheckHealth(healthbar, particles); spawnManager.Spawn(level, backgroundObjects, enemies, powerUps, bosses); gui.Update(player, level); foreach (gib g in gibs) { g.movment(); } foreach (boss b in bosses) { b.Attack(enemyProjectiles, player); b.Movment(player); b.checkHealth(projectiles, ref player, ref level); b.Update(); if (b.nextLevelCount >= 128 * 2) { gameState = GameState.levelTransition; } } foreach (enemyProjectile ep in enemyProjectiles) { ep.Movment(player); ep.Update(player, projectiles, gibs); } foreach (hitEffect he in hitEffects) { he.Update(); } foreach (enemy e in enemies) { e.Attack(enemyProjectiles, player); e.Movment(player); e.Animation(); e.CheckHealth(projectiles, explosions, hitEffects, gibs, ref player); } foreach (explosion ex in explosions) { ex.Animation(); } foreach (powerUp pu in powerUps) { pu.Update(ref player); pu.Movment(); } foreach (backgroundObject bo in backgroundObjects) { bo.Movment(); } foreach (projectile p in projectiles) { p.Movment(); p.Update(particles); } foreach (particle p in particles) { p.Movemnt(); } if (keyboard.IsKeyDown(Keys.Escape) && prevKeyboard.IsKeyUp(Keys.Escape) || gamepad.Buttons.Start == ButtonState.Pressed && prevGamepad.Buttons.Start == ButtonState.Released) { gameState = GameState.menu; menu.selected = 1; } for (int i = 0; i < projectiles.Count; i++) { if (projectiles[i].destroy) { projectiles.RemoveAt(i); } } for (int i = 0; i < gibs.Count; i++) { if (gibs[i].destroy) { gibs.RemoveAt(i); } } for (int i = 0; i < hitEffects.Count; i++) { if (hitEffects[i].destroy) { hitEffects.RemoveAt(i); } } for (int i = 0; i < enemyProjectiles.Count; i++) { if (enemyProjectiles[i].destroy) { enemyProjectiles.RemoveAt(i); } } for (int i = 0; i < particles.Count; i++) { if (particles[i].destroy) { particles.RemoveAt(i); } } for (int i = 0; i < enemies.Count; i++) { if (enemies[i].destroy) { enemies.RemoveAt(i); } } for (int i = 0; i < backgroundObjects.Count; i++) { if (backgroundObjects[i].destroy) { backgroundObjects.RemoveAt(i); } } for (int i = 0; i < powerUps.Count; i++) { if (powerUps[i].destroy) { powerUps.RemoveAt(i); } } for (int i = 0; i < explosions.Count; i++) { if (explosions[i].destroy) { explosions.RemoveAt(i); } } for (int i = 0; i < bosses.Count; i++) { if (bosses[i].destroy) { bosses.RemoveAt(i); } } break; case GameState.howTo: if (keyboard.IsKeyDown(Keys.Space) && prevKeyboard.IsKeyUp(Keys.Space) || gamepad.Buttons.A == ButtonState.Pressed && prevGamepad.Buttons.A == ButtonState.Released) { gameState = GameState.menu; } break; } base.Update(gameTime); }
/// <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) { PreviousKeyboardInput = KeyboardInput; KeyboardInput = Keyboard.GetState(); var dt = (float)gameTime.ElapsedGameTime.TotalSeconds; #if WINDOWS PreviousMouseInput = MouseInput; MouseInput = Mouse.GetState(); //Keep the mouse within the screen if (!IsMouseVisible) { Mouse.SetPosition(200, 200); } #endif PreviousGamePadInput = GamePadInput; for (int i = 0; i < 4; i++) { GamePadInput = GamePad.GetState((PlayerIndex)i); if (GamePadInput.IsConnected) { break; } } // Allows the default game to exit on Xbox 360 and Windows if (KeyboardInput.IsKeyDown(Keys.Escape) || GamePadInput.Buttons.Back == ButtonState.Pressed) { Exit(); } //Toggle mouse control. The camera will look to the IsMouseVisible to determine if it should turn. if (WasKeyPressed(Keys.Tab)) { IsMouseVisible = !IsMouseVisible; } #region UI Toggles #if !WINDOWS if (WasButtonPressed(Buttons.Start)) { displayMenu = !displayMenu; } #else if (WasKeyPressed(Keys.F1)) { displayMenu = !displayMenu; } #endif if (WasKeyPressed(Keys.I)) { if (KeyboardInput.IsKeyDown(Keys.RightShift) || KeyboardInput.IsKeyDown(Keys.LeftShift)) { displayActiveEntityCount = !displayActiveEntityCount; } else { displayUI = !displayUI; } } if (WasKeyPressed(Keys.J)) { displayConstraints = !displayConstraints; } if (WasKeyPressed(Keys.K)) { displayContacts = !displayContacts; } if (WasKeyPressed(Keys.U)) { displayBoundingBoxes = !displayBoundingBoxes; } if (WasKeyPressed(Keys.Y)) { displayEntities = !displayEntities; } if (WasKeyPressed(Keys.H)) { displaySimulationIslands = !displaySimulationIslands; } if (WasKeyPressed(Keys.G)) { ModelDrawer.IsWireframe = !ModelDrawer.IsWireframe; } #endregion #region Simulation Switcharoo #if !WINDOWS int switchTo = -2; if (WasButtonPressed(Buttons.DPadLeft)) { switchTo = currentSimulationIndex - 1; } else if (WasButtonPressed(Buttons.DPadRight)) { switchTo = currentSimulationIndex + 1; } if (switchTo != -2) { if (switchTo < 1) { switchTo += demoTypes.Length; } else if (switchTo > demoTypes.Length) { switchTo = 1; } SwitchSimulation(switchTo); } #else foreach (Keys key in KeyboardInput.GetPressedKeys()) { int code = key.GetHashCode(); if (code >= 48 && code <= 57) { int simNumber; if (code == 48) { simNumber = 10; } else { simNumber = code - 48; } if (KeyboardInput.IsKeyDown(Keys.LeftShift)) { simNumber += 10; } if (KeyboardInput.IsKeyDown(Keys.LeftControl)) { simNumber += 20; } if (simNumber <= demoTypes.Length) { SwitchSimulation(simNumber); } } } #endif #endregion currentSimulation.Update(dt); if (displayConstraints) { ConstraintDrawer.Update(); } if (displayEntities) { ModelDrawer.Update(); } base.Update(gameTime); }
/********* ** Private methods *********/ /// <summary>Get whether the tractor is toggled on by the player.</summary> private bool IsEnabled() { if (!this.IsCurrentPlayerRiding) { return(false); } // automatic mode if (!this.Config.Controls.HoldToActivate.Any()) { return(true); } // hold-to-activate mode KeyboardState state = Keyboard.GetState(); return(this.Keys.HoldToActivate.Any(button => button.TryGetKeyboard(out Keys key) && state.IsKeyDown(key))); }
private void HandleInput() { currentKeyboard = Keyboard.GetState(); // Set culling mode if (currentKeyboard.IsKeyDown(Keys.F1)) { if (!previousKeyboard.IsKeyDown(Keys.F1)) { cullingModeOn = !cullingModeOn; } } // Check for exit. if (currentKeyboard.IsKeyDown(Keys.Escape)) { Exit(); } // Fullscreen on/off toggle if (currentKeyboard.IsKeyDown(Keys.F11)) { // If not down last update, key has just been pressed. if (!previousKeyboard.IsKeyDown(Keys.F11)) { fullscreenMode = !fullscreenMode; SetScreenMode(); } } // Seated on/off toggle if (currentKeyboard.IsKeyDown(Keys.V)) { if (!previousKeyboard.IsKeyDown(Keys.V)) { chooser.SeatedMode = !chooser.SeatedMode; skeletonDetected = false; } } // Near mode on/off toggle if (currentKeyboard.IsKeyDown(Keys.N)) { if (!previousKeyboard.IsKeyDown(Keys.N)) { chooser.NearMode = !chooser.NearMode; skeletonDetected = false; } } // Reset the avatar filters (also resets camera) if (currentKeyboard.IsKeyDown(Keys.R)) { if (!previousKeyboard.IsKeyDown(Keys.R)) { } } // Рисовать bounding boxes вкл/выкл if (currentKeyboard.IsKeyDown(Keys.B)) { if (!previousKeyboard.IsKeyDown(Keys.B)) { drawBoundingBoxesOn = !drawBoundingBoxesOn; } } }
public bool IsKeyDown(Keys k) => lastKbs?.IsKeyDown(k) ?? false;
void CameraControls(float frameDuration) { KBS = Keyboard.GetState(); if (KBS.IsKeyDown(Key.E)) { cameraM *= Matrix4.CreateTranslation(0, -(16f * frameDuration), 0); } if (KBS.IsKeyDown(Key.Q)) { cameraM *= Matrix4.CreateTranslation(0, (16f * frameDuration), 0); } if (KBS.IsKeyDown(Key.A)) { cameraM *= Matrix4.CreateTranslation((16f * frameDuration), 0, 0); } if (KBS.IsKeyDown(Key.D)) { cameraM *= Matrix4.CreateTranslation(-(16f * frameDuration), 0, 0); } if (KBS.IsKeyDown(Key.W)) { cameraM *= Matrix4.CreateTranslation(0, 0, (16f * frameDuration)); } if (KBS.IsKeyDown(Key.S)) { cameraM *= Matrix4.CreateTranslation(0, 0, -(16f * frameDuration)); } if (KBS.IsKeyDown(Key.I)) { cameraM *= Matrix4.CreateRotationX((-0.8f * frameDuration)); } if (KBS.IsKeyDown(Key.K)) { cameraM *= Matrix4.CreateRotationX((0.8f * frameDuration)); } if (KBS.IsKeyDown(Key.J)) { cameraM *= Matrix4.CreateRotationY(-(0.8f * frameDuration)); } if (KBS.IsKeyDown(Key.L)) { cameraM *= Matrix4.CreateRotationY((0.8f * frameDuration)); } if (KBS.IsKeyDown(Key.U)) { cameraM *= Matrix4.CreateRotationZ(-(0.8f * frameDuration)); } if (KBS.IsKeyDown(Key.O)) { cameraM *= Matrix4.CreateRotationZ((0.8f * frameDuration)); } }
public bool IsNewPress(Keys key) { return(previousState.IsKeyUp(key) && currentState.IsKeyDown(key)); }
/// <summary> /// Input helper method provided by GameScreen. Packages up the various input /// values for ease of use. Here it checks for pausing and handles controlling /// the player's tank. /// </summary> /// <param name="input">The state of the gamepads</param> public override void HandleInput(InputState input) { if (input == null) { throw new ArgumentNullException("input"); } if (input.PauseGame) { if (gameOver == true) { finishCurrentGame(); } } else { touchState = TouchPanel.GetState(); bool buttonTouched = false; //interpret touch screen presses foreach (TouchLocation location in touchState) { switch (location.State) { case TouchLocationState.Pressed: buttonTouched = true; break; case TouchLocationState.Moved: break; case TouchLocationState.Released: break; } } float movement = 0.0f; if (accelState != null) { if (Math.Abs(accelState.X) > 0.10f) { if (accelState.X > 0.0f) { movement = 1.0f; } else { movement = -1.0f; } } } player.Velocity.X = movement; //This section handles tank movement. We only allow one "movement" action //to occur at once so that touchpad devices don't get double hits. KeyboardState keyState = Keyboard.GetState(); if (input.CurrentGamePadStates[0].DPad.Left == ButtonState.Pressed || keyState.IsKeyDown(Keys.Left)) { player.Velocity.X = -1.0f; } else if (input.CurrentGamePadStates[0].DPad.Right == ButtonState.Pressed || keyState.IsKeyDown(Keys.Right)) { player.Velocity.X = 1.0f; } else { player.Velocity.X = MathHelper.Min(input.CurrentGamePadStates[0].ThumbSticks.Left.X * 2.0f, 1.0f); } // B button, or pressing on the upper half of the pad or space on keyboard or touching the touch panel fires the weapon. if (input.CurrentGamePadStates[0].IsButtonDown(Buttons.B) || input.CurrentGamePadStates[0].IsButtonDown(Buttons.A) || input.CurrentGamePadStates[0].ThumbSticks.Left.Y > 0.25f || keyState.IsKeyDown(Keys.Space) || buttonTouched) { if (!gameOver) { if (player.FireTimer <= 0.0f && player.IsAlive && !gameOver) { Bullet bullet = CreatePlayerBullet(); bullet.Position = new Vector2((int)(player.Position.X + player.Width / 2) - bulletTexture.Width / 2, player.Position.Y - 4); bullet.Velocity = new Vector2(0, -256.0f); player.FireTimer = 1.0f; particles.CreatePlayerFireSmoke(player); playerFired.Play(); } else if (gameOver) { finishCurrentGame(); } } else if (gameOver) { finishCurrentGame(); } } } }
public bool KeyPressed(Keys k) { return(currentKeyboardState.IsKeyDown(k) && previousKeyboardState.IsKeyUp(k)); }
protected override void Update(GameTime gameTime) { KeyboardState teclado = Keyboard.GetState(); //Pausa if (teclado.IsKeyDown(Keys.P) && !pulsada) { pausado = pausado ? false : true; } pulsada = teclado.IsKeyDown(Keys.P) ? true : false; if (pausado) { if (teclado.IsKeyDown(Keys.Escape)) { Exit(); } } if (!pausado) { //Colocar bomba if (teclado.IsKeyDown(Keys.E)) { Bomba bAux = new Bomba(jugador.X - (jugador.X % 40), jugador.Y - (jugador.Y % 40), jugador.LongitudBomba); //He cambiado el .Equals() para que compare solo las posiciones X e Y if (!bombas.Contains(bAux)) { bAux.SetImagen(Content.Load <Texture2D>("bomba")); bombas.Add(bAux); } } //Movimiento jugador jugador.SetImagen(Content.Load <Texture2D>("jugador1")); if (teclado.IsKeyDown(Keys.W)) { jugador.Y -= (int)(jugador.GetVelocidad() * (float)gameTime.ElapsedGameTime.TotalSeconds); jugador.SetImagen(Content.Load <Texture2D>("jugador1U")); } if (teclado.IsKeyDown(Keys.A)) { jugador.X -= (int)(jugador.GetVelocidad() * (float)gameTime.ElapsedGameTime.TotalSeconds); jugador.SetImagen(Content.Load <Texture2D>("jugador1L")); } if (teclado.IsKeyDown(Keys.S)) { jugador.Y += (int)(jugador.GetVelocidad() * (float)gameTime.ElapsedGameTime.TotalSeconds); jugador.SetImagen(Content.Load <Texture2D>("jugador1D")); } if (teclado.IsKeyDown(Keys.D)) { jugador.X += (int)(jugador.GetVelocidad() * (float)gameTime.ElapsedGameTime.TotalSeconds); jugador.SetImagen(Content.Load <Texture2D>("jugador1R")); } //Se mueven los enemigos foreach (Enemigo e in enemigos) { e.Mover(gameTime); } //HACER FUNCIONAMIENTO DE LAS BOMBAS for (int i = 0; i < bombas.Count; i++) { if ((int)(bombas[i].Contador += gameTime.ElapsedGameTime.TotalSeconds) == 2 && !bombas[i].HaExplotado()) { bombas[i].Explotar(paredes, muros); foreach (Explosion e in bombas[i].GetExplosion()) { e.SetImagen(Content.Load <Texture2D>("explosion")); //Colisiones de las explosiones con los muros para destruirlos for (int j = 0; j < muros.Count; j++) { if (new Rectangle(muros[j].X, muros[j].Y, 40, 40).Intersects( new Rectangle(e.X, e.Y, 40, 40))) { muros.RemoveAt(j); } } } } if (bombas[i].GetExplosion().Count > 0) { foreach (Explosion e in bombas[i].GetExplosion()) { //Colision de las bombas con los enemigos para matarlos for (int j = 0; j < enemigos.Count; j++) { if (new Rectangle(enemigos[j].X, enemigos[j].Y, 40, 40).Intersects( new Rectangle(e.X, e.Y, 40, 40))) { puntuacion += enemigos[j].GetType() == typeof(EnemigoFinal) ? 300 : 100; enemigos.RemoveAt(j); } } if (new Rectangle(jugador.X, jugador.Y, 30, 30).Intersects( new Rectangle(e.X, e.Y, 40, 40))) { Exit(); } } } if (bombas[i].Contador >= 4) { bombas.RemoveAt(i); } } //Se comprueban colisiones de los enemigos foreach (Enemigo e in enemigos) { if (colisiona(e.X, e.Y, 40, true)) { e.X -= (int)(e.GetVelocidadX() * (float)gameTime.ElapsedGameTime.TotalSeconds); e.Y -= (int)(e.GetVelocidadY() * (float)gameTime.ElapsedGameTime.TotalSeconds); e.CambiarDireccion(); } //Aquí se comprueba si pasa por al lado de un hueco y hay una probabilidad de que cambie de direccion //Para que no entren en bucles if (e.GetType() != typeof(Enemigo3)) { if ((e.Y % 80 == 0 && e.GetVelocidadX() == 0 || e.X % 40 == 0 && e.X % 80 != 0 && e.GetVelocidadY() == 0) && r.Next(0, 3) == 2) { e.CambiarDireccion(); } } //Si el enemigo final te toca mueres if (new Rectangle(e.X + 10, e.Y + 10, 30, 30).Intersects( new Rectangle(jugador.X, jugador.Y, 30, 30))) { Thread.Sleep(1500); Exit(); } } //Se comprueban colisiones con las paredes if (colisiona(jugador.X, jugador.Y, 30)) { if (teclado.IsKeyDown(Keys.W)) { jugador.Y += (int)(jugador.GetVelocidad() * (float)gameTime.ElapsedGameTime.TotalSeconds); } if (teclado.IsKeyDown(Keys.A)) { jugador.X += (int)(jugador.GetVelocidad() * (float)gameTime.ElapsedGameTime.TotalSeconds); } if (teclado.IsKeyDown(Keys.S)) { jugador.Y -= (int)(jugador.GetVelocidad() * (float)gameTime.ElapsedGameTime.TotalSeconds); } if (teclado.IsKeyDown(Keys.D)) { jugador.X -= (int)(jugador.GetVelocidad() * (float)gameTime.ElapsedGameTime.TotalSeconds); } } //Calcular segundos if (tiempo > 0) { tiempo -= gameTime.ElapsedGameTime.TotalSeconds; } else if (!final) { enemigosFinales(); } //Salida de la puerta if (new Rectangle(salida.X + 10, salida.Y + 10, 20, 20).Intersects( new Rectangle(jugador.X, jugador.Y, 30, 30)) && enemigos.Count == 0) { puntuacion += 10000; muerto = false; Exit(); } //Colision con la mejora if (mejora != null && new Rectangle(mejora.X + 10, mejora.Y + 10, 20, 20).Intersects( new Rectangle(jugador.X, jugador.Y, 30, 30))) { mejora = null; puntuacion += 1000; jugador.LongitudBomba += 1; } } base.Update(gameTime); }
/// <summary> /// Lets the game respond to player input. Unlike the Update method, /// this will only be called when the gameplay screen is active. /// </summary> public override void HandleInput(InputState input) { if (input == null) { throw new ArgumentNullException("input"); } KeyboardState keyboardState = Keyboard.GetState(); MouseState mouseState = Mouse.GetState(); if (input.IsPauseGame(ControllingPlayer)) { ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer); } else { if (!piranha.IsInvul) { #region Keyboard toggle keys if (keyboardState.IsKeyDown(Keys.R) && prevKeyboard.IsKeyUp(Keys.R)) { ResetGame(); } if (keyboardState.IsKeyDown(Keys.M) && prevKeyboard.IsKeyUp(Keys.M)) { canUseMouse = !canUseMouse; } if (keyboardState.IsKeyDown(Keys.G) && prevKeyboard.IsKeyUp(Keys.G)) { godMode = !godMode; } #endregion #region Mouse control if (canUseMouse) { // Mouse control, can travel in all directions Vector2 mousePos = new Vector2(mouseState.X, mouseState.Y); Vector2 oldMousePos = new Vector2(prevMouse.X, prevMouse.Y); if (mousePos != oldMousePos) { piranha.WantedPosition = new Vector2(mouseState.X, mouseState.Y); } } #endregion #region Keyboard directional control keys if (keyboardState.IsKeyDown(Keys.Up)) { piranha.WantedPosition += new Vector2(0, -18); } else if (keyboardState.IsKeyDown(Keys.Down)) { piranha.WantedPosition += new Vector2(0, 18); } else if (keyboardState.IsKeyDown(Keys.Left)) { piranha.WantedPosition += new Vector2(-18, 0); } else if (keyboardState.IsKeyDown(Keys.Right)) { piranha.WantedPosition += new Vector2(18, 0); } #endregion // Clamp the wanted position to the screen bounds (with a little leeway) piranha.WantedPosition = new Vector2( MathHelper.Clamp(piranha.WantedPosition.X, -30, Functions.GameSize.X + 30), MathHelper.Clamp(piranha.WantedPosition.Y, -30, Functions.GameSize.Y + 30)); } } prevKeyboard = keyboardState; prevMouse = mouseState; }
protected override void OnUpdateFrame(FrameEventArgs e) { KeyboardState input = Keyboard.GetState(); if (input.IsKeyDown(Key.Escape)) { Exit(); } if (input.IsKeyDown(Key.Up) && !lastInput.IsKeyDown(Key.Up)) { if (!fragmentPlacementMode) { map.playerY--; } else { map.fragmentY++; } } if (input.IsKeyDown(Key.Down) && !lastInput.IsKeyDown(Key.Down)) { if (!fragmentPlacementMode) { map.playerY++; } else { map.fragmentY--; } } if (input.IsKeyDown(Key.Left) && !lastInput.IsKeyDown(Key.Left)) { if (!fragmentPlacementMode) { map.playerX--; } else { map.fragmentX++; } } if (input.IsKeyDown(Key.Right) && !lastInput.IsKeyDown(Key.Right)) { if (!fragmentPlacementMode) { map.playerX++; } else { map.fragmentX--; } } if (input.IsKeyDown(Key.Space) && !lastInput.IsKeyDown(Key.Space)) { if (!fragmentPlacementMode) { // } else { // set fragment to ship map foreach (KeyValuePair <(int x, int y), MapTile> item in map.fragment) { int x = item.Key.x; int y = item.Key.y; MapTile tile = item.Value; map.ship[(x - map.fragmentX, y - map.fragmentY)] = tile;
/// <summary> /// Handles camera input. /// </summary> private void UpdateCamera(GameTime gameTime) { float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds; // Check for input to rotate the camera up and down around the model. if (currentKeyboardState.IsKeyDown(Keys.Up) || currentKeyboardState.IsKeyDown(Keys.W)) { cameraArc += time * 0.1f; } if (currentKeyboardState.IsKeyDown(Keys.Down) || currentKeyboardState.IsKeyDown(Keys.S)) { cameraArc -= time * 0.1f; } cameraArc += currentGamePadState.ThumbSticks.Right.Y * time * 0.25f; // Limit the arc movement. if (cameraArc > 90.0f) { cameraArc = 90.0f; } else if (cameraArc < -90.0f) { cameraArc = -90.0f; } // Check for input to rotate the camera around the model. if (currentKeyboardState.IsKeyDown(Keys.Right) || currentKeyboardState.IsKeyDown(Keys.D)) { cameraRotation += time * 0.1f; } if (currentKeyboardState.IsKeyDown(Keys.Left) || currentKeyboardState.IsKeyDown(Keys.A)) { cameraRotation -= time * 0.1f; } cameraRotation += currentGamePadState.ThumbSticks.Right.X * time * 0.25f; // Check for input to zoom camera in and out. if (currentKeyboardState.IsKeyDown(Keys.Z)) { cameraDistance += time * 0.5f; } if (currentKeyboardState.IsKeyDown(Keys.X)) { cameraDistance -= time * 0.5f; } cameraDistance += currentGamePadState.Triggers.Left * time; cameraDistance -= currentGamePadState.Triggers.Right * time; // Limit the camera distance. if (cameraDistance > 5000.0f) { cameraDistance = 5000.0f; } else if (cameraDistance < 350.0f) { cameraDistance = 350.0f; } if (currentGamePadState.Buttons.RightStick == ButtonState.Pressed || currentKeyboardState.IsKeyDown(Keys.R)) { cameraArc = 0; cameraRotation = 45; cameraDistance = 1500; } }
public void Update(float elapsedTime, KeyboardState keyboardState) { var vel_an = 5f * (level == 0 ? 1 : -1); if (keyboardState.IsKeyDown(Keys.Left)) { angle -= elapsedTime * vel_an; } if (keyboardState.IsKeyDown(Keys.Right)) { angle += elapsedTime * vel_an; } ant_pos = pos; pos += elapsedTime * (keyboardState.IsKeyDown(Keys.Space) ? 0 : vel_lineal); var i = (int)Math.Floor(pos); var frac = pos - i; var Q0 = Path[i % max_path]; var Q1 = Path[(i + 1) % max_path]; var Q2 = Path[(i + 2) % max_path]; var N0 = Vector3.Normalize(Q1 - Q0); var N1 = Vector3.Normalize(Q2 - Q1); var U = Vector3.Cross(new Vector3(0, 1, 0), N0); var V = Vector3.Cross(N0, U); Position = Q0 * (1 - frac) + Q1 * frac; ViewDir = N0 * (1 - frac) + N1 * frac; Up = V * MathF.Cos(angle) + U * MathF.Sin(angle); if (level == 0) { PosGamer = Position + ViewDir * 700 - Up * 250; } else { PosGamer = Position + ViewDir * 700 + Up * 200; Position += Up * 420; } // collision detect colision = false; for (var L = 0; L < 2 && !colision; ++L) { for (var k = 1; k < 3 && !colision; ++k) { var p_obs = curr_obs = obstaculo[L, i + k]; if (p_obs > 0) { var p = PosGamer - ViewDir * 50; var q = PosGamer + ViewDir * 50; var p0 = Vertices[p_obs].Position; var p1 = Vertices[p_obs + 1].Position; var p2 = Vertices[p_obs + 2].Position; var p3 = Vertices[p_obs + 3].Position; var uvw = new Vector3(); var Ip = new Vector3(); float t; if (TGCCollisionUtils.IntersectSegmentTriangle(p, q, p0, p1, p2, out uvw, out t, out Ip) || TGCCollisionUtils.IntersectSegmentTriangle(p, q, p0, p2, p3, out uvw, out t, out Ip)) { colision = true; } } } } }
protected override void Update(GameTime gameTime) { if (Enemy[0].Active == 0) { _gameState = "result"; _isWin = true; } if (_gameState == "title") { KeyboardState keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Keys.Enter)) { _gameState = "game"; _currSong = "background"; _currentCue.Stop(AudioStopOptions.Immediate); _currentCue = _soundBankBG.GetCue(_currSong); _currentCue.Play(); _playingSong = true; } if (keyboardState.IsKeyDown(Keys.Escape)) { this.Exit(); } base.Update(gameTime); } else if (_gameState == "result") { KeyboardState keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Keys.Space)) { _gameState = "title"; _currSong = "title"; _currentCue.Stop(AudioStopOptions.Immediate); _currentCue = _soundBankBG.GetCue(_currSong); _currentCue.Play(); _playingSong = true; InitLevel(); for (int i = 0; i < 3; ++i) { prop[i].number = 1; } Life.number = 2; _hasEnter = false; } base.Update(gameTime); } else { checkPauseKey(); if (paused == false) { int i; ControlKey(); MoveEnemy(); Master.updata(); if (Master.Active == 0 && Life.number != 0) { Master.Active = 1; Master.pos = MyHelp.masterStartPos; } if (Master.Active == 0 && Life.number == 0) { _gameState = "result"; _isWin = false; } for (i = 0; i < MyHelp.maxLei; ++i) { if (lei[i].Active != 0) { lei[i].updata(); } } for (i = 0; i < MyHelp.maxActicle; ++i) { if (acticle[i].active) { acticle[i].updata(); } } base.Update(gameTime); } } _audioEngine.Update(); if (_playingSong == false) { _currentCue = _soundBankBG.GetCue(_currSong); _currentCue.Play(); _playingSong = true; } if (_currentCue.IsStopped == true) { _playingSong = false; } if (_lei == true) { _soundBankBG.GetCue("lei").Play(); _lei = false; } if (_drop == true) { _soundBankBG.GetCue("drop").Play(); _drop = false; } }
private void UpdateGamePlay() { KeyboardState keys = Keyboard.GetState(); if (keys.IsKeyDown(Keys.Up)) { cheese.StartMovingUp(); } else { cheese.StopMovingUp(); } if (keys.IsKeyDown(Keys.Down)) { cheese.StartMovingDown(); } else { cheese.StopMovingDown(); } if (keys.IsKeyDown(Keys.Left)) { cheese.StartMovingLeft(); } else { cheese.StopMovingLeft(); } if (keys.IsKeyDown(Keys.Right)) { cheese.StartMovingRight(); } else { cheese.StopMovingRight(); } foreach (Sprite s in gameSprites) { s.Update(1.0f / 60.0f); } foreach (Target t in crackers) { if (cheese.IntersectsWith(t)) { ////BurpSound.Play(); Burp sound is here t.Reset(); score = score + 10; } } timer = timer - 1; int secsLeft = timer / 60; messageString = "Time: " + secsLeft.ToString() + " Score: " + score; if (timer == 0) { messageString = " Game Over : Press Space to exit Score: " + score.ToString(); gameOver(); } }
public override void Update(GameTime gameTime) { keyboardState = Keyboard.GetState(); MouseState mouseState = Mouse.GetState(); Vector2 mouseLocation = new Vector2(mouseState.X, mouseState.Y); mouseLocation -= Position; Rotation = (float)Math.Atan2(mouseLocation.Y, mouseLocation.X); // fires weapon if Fire Rate is ready if (canFire) { // check for left mouse pressed and fire event if (mouseState.LeftButton == ButtonState.Pressed) { FireWeapon(); } } previousMouse = mouseState; //Update timer fireTimer.Update(gameTime.ElapsedGameTime); #region Movement //Movement if (keyboardState.IsKeyDown(Keys.W)) { Position.Y -= moveSpeed; } if (keyboardState.IsKeyDown(Keys.S)) { Position.Y += moveSpeed; } if (keyboardState.IsKeyDown(Keys.A)) { Position.X -= moveSpeed; } if (keyboardState.IsKeyDown(Keys.D)) { Position.X += moveSpeed; } #endregion #region Change Weapon //Change weapon if (keyboardState.IsKeyDown(Keys.D1)) { weaponType = WeaponType.WaterGun; } if (keyboardState.IsKeyDown(Keys.D2)) { weaponType = WeaponType.SlingShot; } if (keyboardState.IsKeyDown(Keys.D3)) { weaponType = WeaponType.DonutGun; } #endregion base.Update(gameTime); }
public void tポーリング(bool bWindowがアクティブ中) { for (int i = 0; i < 256; i++) { this.bKeyPushDown[i] = false; this.bKeyPullUp[i] = false; } if (bWindowがアクティブ中) { this.list入力イベント.Clear(); // #xxxxx 2012.6.11 yyagi; To optimize, I removed new(); //----------------------------- KeyboardState currentState = Keyboard.GetState(); if (currentState.IsConnected) { for (int index = 0; index < Enum.GetNames(typeof(Key)).Length; index++) { if (currentState[(Key)index]) { // #xxxxx: 2017.5.7: from: TKK (OpenTK.Input.Key) を SlimDX.DirectInput.Key に変換。 var key = DeviceConstantConverter.TKKtoKey((Key)index); if (SlimDXKey.Unknown == key) { continue; // 未対応キーは無視。 } if (this.bKeyState[(int)key] == false) { if (key != SlimDXKey.Return || (bKeyState[(int)SlimDXKey.LeftAlt] == false && bKeyState[(int)SlimDXKey.RightAlt] == false)) // #23708 2016.3.19 yyagi { var ev = new STInputEvent() { nKey = (int)key, b押された = true, b離された = false, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bKeyState[(int)key] = true; this.bKeyPushDown[(int)key] = true; } } } { // #xxxxx: 2017.5.7: from: TKK (OpenTK.Input.Key) を SlimDX.DirectInput.Key に変換。 var key = DeviceConstantConverter.TKKtoKey((Key)index); if (SlimDXKey.Unknown == key) { continue; // 未対応キーは無視。 } if (this.bKeyState[(int)key] == true && !currentState.IsKeyDown((Key)index)) // 前回は押されているのに今回は押されていない → 離された { var ev = new STInputEvent() { nKey = (int)key, b押された = false, b離された = true, nTimeStamp = CSound管理.rc演奏用タイマ.nシステム時刻ms, // 演奏用タイマと同じタイマを使うことで、BGMと譜面、入力ずれを防ぐ。 }; this.list入力イベント.Add(ev); this.bKeyState[(int)key] = false; this.bKeyPullUp[(int)key] = true; } } } } //----------------------------- } }
static public Triggers Read() { Triggers currentKeyState = 0; GamePadState gamepadState = GamePad.GetState(PlayerIndex.One); KeyboardState keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Keys.Escape) || ((previousGamePadState.Buttons.Back != ButtonState.Pressed) && (gamepadState.Buttons.Back == ButtonState.Pressed))) { currentKeyState |= Triggers.ExitLevel; } // the DownArrow bit is turned on if (keyboardState.IsKeyDown(Keys.Down)) { currentKeyState |= Triggers.DownArrow; } if (keyboardState.IsKeyDown(Keys.Up)) { currentKeyState |= Triggers.UpArrow; } if (keyboardState.IsKeyDown(Keys.Right)) { currentKeyState |= Triggers.RightArrow; } if (keyboardState.IsKeyDown(Keys.Left)) { currentKeyState |= Triggers.LeftArrow; } if (keyboardState.IsKeyDown(Keys.Space)) { currentKeyState |= Triggers.Resume; } if (keyboardState.IsKeyDown(Keys.P)) { currentKeyState |= Triggers.Pause; } if (keyboardState.IsKeyDown(Keys.Escape)) { currentKeyState |= Triggers.ExitLevel; } if (keyboardState.IsKeyDown(Keys.R)) { currentKeyState |= Triggers.Reset; } if (keyboardState.IsKeyDown(Keys.Q)) { currentKeyState |= Triggers.Quit; } if (gamepadState.DPad.Down == ButtonState.Pressed) { currentKeyState |= Triggers.DownArrow; } if (gamepadState.DPad.Up == ButtonState.Pressed) { currentKeyState |= Triggers.UpArrow; } if (gamepadState.DPad.Right == ButtonState.Pressed) { currentKeyState |= Triggers.RightArrow; } if (gamepadState.DPad.Left == ButtonState.Pressed) { currentKeyState |= Triggers.LeftArrow; } if (gamepadState.Buttons.A == ButtonState.Pressed) { // This is the big Zunepad button currentKeyState |= Triggers.Resume; } if ((previousGamePadState.Buttons.B != ButtonState.Pressed) && (gamepadState.Buttons.B == ButtonState.Pressed)) { // This is the forward key next to the Zunepad button currentKeyState |= Triggers.Pause; } previousGamePadState = gamepadState; lastKeyValuesRead = currentKeyState; return(currentKeyState); }//eom
public void processKeyboardInput(KeyboardState state) { if (state.IsKeyDown(Key.W)) { Pos += (Target * stepSize); } if (state.IsKeyDown(Key.S)) { Pos -= (Target * stepSize); } if (state.IsKeyDown(Key.A)) { Vector3 Left = Vector3.Cross(Target, Up); Left.Normalize(); Left *= stepSize; Pos += Left; } if (state.IsKeyDown(Key.D)) { Vector3 Right = Vector3.Cross(Up, Target); Right.Normalize(); Right *= stepSize; Pos += Right; } /* Mouse movement code temporarily mapped to arrow keys */ bool shouldUpdate = false; if (state.IsKeyDown(Key.Left)) { angleH -= 0.1f; shouldUpdate = true; } else if (state.IsKeyDown(Key.Right)) { angleH += 0.1f; shouldUpdate = true; } if (state.IsKeyDown(Key.Up)) { if (angleV > -90.0f) { angleV -= 0.1f; shouldUpdate = true; } } else if (state.IsKeyDown(Key.Down)) { if (angleV < 90.0f) { angleV += 0.1f; shouldUpdate = true; } } if (shouldUpdate) { update(); } }
public bool IsKeyDown(Key key) { return(KeyboardState.IsKeyDown(key)); }
/// <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) { KeyboardState keyboardState = Keyboard.GetState(); gameState = actualLevel.LevelNum; foreach (Tile t in actualLevel._tileList) { t.Update(gameTime); } foreach (Individual i in actualLevel._individualList) { pState = i.Update(gameTime, actualLevel._tileList, actualLevel._xTiles, actualLevel._yTiles, 0.4f, pState, Window); if (i.isMC == true) { cam.Update(i.Position, 0f, 0f, GraphicsDevice.Viewport, actualLevel._xTiles, actualLevel._yTiles, 75, 75); } } // if (Keyboard.GetState().IsKeyDown(Keys.R)) //{ //if(cam.Rotation<Math.PI-0.007) // cam.Rotation += 0.01f; //} /* * if (cam.Zoom > 2) * { * FUNFLAG = false; * } * if (cam.Zoom == 1) * { * FUNFLAG = true; * } * if (FUNFLAG==true) * { * cam.Zoom += 0.1f; * * } * else * { * cam.Zoom -= 0.1f; * }*/ if (keyboardState.IsKeyDown(Keys.T)) { UnloadContent(); LoadContent(); } if (keyboardState.IsKeyDown(Keys.Escape)) { this.Exit(); } // TODO: Add your update logic here base.Update(gameTime); }
/// <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) { Time += 1; //ökar variabeln som skapar fiender TurretCD++; //ökar variabeln som hindrar mig skapa flera torn //skapar en fiende var 100 enhet if (Time == enemys_frequency) { SpawnMinion(new Vector2(-60, 60), new Vector2(enemy_speed, 0), enemy_hp, 0); //kallar på metoden som skapar en "Minion"(fiende) Enemys++; //ökar antalet enemies för att veta hur många "Time" ska delas med. Time = 0; } ofmaxhp = player_current_hp / player_max_hp; //ofmaxhp är procent av max hp som spelaren just nu har. Kan vara mellan 0 och 1. realofmaxhp = Convert.ToInt32(ofmaxhp * 800); //gör om ofmaxhp till int. Multiplicerar även 800 för att täcka hela x-axeln. if (player_current_hp <= 0) { Exit(); } //gör spelet svårare genom: hastighet, hälsa och frekvens av fiender if (Enemys == 20) { enemy_hp = 3; } if (Enemys == 30) { turret_cost_increase = 3; } if (Enemys == 60) { enemy_speed = 3; turret_cost_increase = 4; enemys_frequency = 70; } if (Enemys == 70) { turret_cost_increase = 5; } if (Enemys == 100) { enemy_hp = 5; enemy_speed = 4; turret_cost_increase = 6; } if (Enemys == 150) { enemys_frequency = 50; turret_cost_increase = 10; } //förflytta spelarens karaktär KeyboardState kstate = Keyboard.GetState(); if (kstate.IsKeyDown(Keys.W)) { ME_y = ME_y - 3; } if (kstate.IsKeyDown(Keys.S)) { ME_y = ME_y + 3; } if (kstate.IsKeyDown(Keys.D)) { ME_x = ME_x + 3; } if (kstate.IsKeyDown(Keys.A)) { ME_x = ME_x - 3; } //skapar ett torn där spelaren står if (kstate.IsKeyDown(Keys.Space) && TurretCD > 40 && money1 >= turret_cost) { TurretCD = 0; //Kan bara skapa ett torn var 40'onde enhet. Här blir enheten 0 igen. SpawnTurret(ME_x + 40, ME_y, 100, 0, 200, new List <Minion>(), new List <Minion>()); //kallar på metoden som skapar ett torn. //ändrar pengar money1 = money1 - turret_cost; turret_cost = turret_cost + turret_cost_increase; } //går igenom varje torn så att de ska: antingen skjuta rätt fiende eller göra sig redo för att skjuta foreach (Turret a in turrets) //a = ally { current_highest_traveled = -1; //minskar variabel som sparar "highest traveled" bland de fiender inom räckvidd till -1. a.attack_Wind_UP++; //får tornet redo att attackera. Just nu behöver denna bli 100(attack speed). if (a.attack_Wind_UP > a.attack_speed) //får tornet att attackera ifall den får det { a.attack_Wind_UP = 0; a.minions_in_range.Clear(); //kollar distansen till varje fiende foreach (Minion e in minions) //e = enemy { if (GetDistance(a.x_position, a.y_position, e.Position.X + 30, e.Position.Y + 25) <= a.attack_range) { a.minions_in_range.Add(e); //lägger till dem till variabeln om dem är in-range } } //kollar vilken fiende in-range som har färdats längst if (a.minions_in_range != null) { foreach (Minion e in a.minions_in_range) { if (e.units_traveled > current_highest_traveled) { a.list_target.Clear(); current_highest_traveled = e.units_traveled; //Den sparar vilket värde som färdats längst inom räckhåll. a.list_target.Add(e); } } } //skadar fienden som har samma position som den sparade variabeln "highest traveled" for (int e = minions.Count - 1; e >= 0; e--) { if (minions[e].units_traveled == current_highest_traveled) { //skapar ett grafiskt skott som bara är för syns skull. SpawnShot(new Vector2(a.x_position, a.y_position), minions[e].Position - new Vector2(a.x_position, a.y_position), 0, ((minions[e].Position.X + 30) - (a.x_position) + ((minions[e].Position.Y + 25) - a.y_position)), new List <Minion>(e)); minions[e].health--; } } } } //förflyttar varje skott beroende på dess riktning och hastighet. foreach (Shot s in shots) //s = shots { s.Direction.Normalize(); s.Position += (s.Direction * shotspeed); } //ökar varje skotts "units_traveled", och tar bort skottet ifall den nått sin destination. if (shots.Count > 0) { for (int i = shots.Count - 1; i >= 0; i--) { shots[i].units_traveled = (shots[i].units_traveled) + (shots[i].Direction.X * shotspeed) + (shots[i].Direction.Y * shotspeed); //ökar "units traveled" if (shots[i].units_traveled >= shots[i].units_to_target) { shots.RemoveAt(i); //tar bort "shot". } } } //om en fiende får 0 eller mindre i hälso så försvinner den, och man får pengar. for (int i = minions.Count - 1; i >= 0; i--) { if (minions[i].health <= 0) { minions.RemoveAt(i); //tar bort fiende. money1++; //man får pengar } } //flyttar varje fiende(minion), och ökar dess "units_traveled" foreach (Minion e in minions) { e.units_traveled = e.units_traveled + e.Speed.X + e.Speed.Y; //units_traveled e.Position += e.Speed; //position } //fiende ändrar riktning så de följer banan foreach (Minion e in minions) { if (e.Position.X == 384 && e.Position.Y == 60) { e.Speed.X = 0; e.Speed.Y = enemy_speed; } if (e.Position.X == 384 && e.Position.Y == 216) { e.Speed.X = enemy_speed; e.Speed.Y = 0; } if (e.Position.X == 552 && e.Position.Y == 216) { e.Speed.X = 0; e.Speed.Y = -enemy_speed; } if (e.Position.X == 552 && e.Position.Y == 60) { e.Speed.X = enemy_speed; e.Speed.Y = 0; } if (e.Position.X == 684 && e.Position.Y == 60) { e.Speed.X = 0; e.Speed.Y = enemy_speed; } if (e.Position.X == 684 && e.Position.Y == 360) { e.Speed.X = -enemy_speed; e.Speed.Y = 0; } } //om en fiende passerar dess mål förlorar spelaren liv och fienden försvinner. for (int e = minions.Count - 1; e >= 0; e--) { if (minions[e].Position.X <= -61) { minions.RemoveAt(e); player_current_hp--; } } if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) { Exit(); } // TODO: Add your update logic here base.Update(gameTime); }
/// <summary> /// Update the camera position /// </summary> /// <param name="gameTime">GameTime</param> public override void Update(GameTime gameTime) { float dt = (float)gameTime.ElapsedGameTime.TotalSeconds; currentMouseState = Mouse.GetState(); KeyboardState ks = Keyboard.GetState(); Vector3 moveVector = Vector3.Zero; if (ks.IsKeyDown(Keys.W)) { moveVector.Z = 1; } if (ks.IsKeyDown(Keys.S)) { moveVector.Z = -1; } if (ks.IsKeyDown(Keys.A)) { moveVector.X = 1; } if (ks.IsKeyDown(Keys.D)) { moveVector.X = -1; } if (ks.IsKeyDown(Keys.Space)) { if (!Game1.isFlipped) { moveVector.Y = 1; } else if (Game1.isFlipped && (Position.Y < -5.0f)) { moveVector.Y = 1; } } if (ks.IsKeyDown(Keys.X)) { if (!Game1.isFlipped && (Position.Y - 1f) > (terrainMaxHeight + 20f)) { moveVector.Y = -1; } else if (Game1.isFlipped && (Position.Y - 1f) < 20f) { moveVector.Y = -1; } } if (moveVector != Vector3.Zero) { // normalize the vector; so that we don't move faster diagonally moveVector.Normalize(); // Add in smooth and speed moveVector *= (dt * CameraSpeed); // Move camera Move(moveVector); } if (ks.IsKeyDown(Keys.Back)) { MoveTo(camOrigin, Rotation); } // Handle Mouse movement float deltaX; float deltaY; if (currentMouseState != prevMouseState) { // Cache mouse location deltaX = currentMouseState.X - (Game.GraphicsDevice.Viewport.Width / 2); deltaY = currentMouseState.Y - (Game.GraphicsDevice.Viewport.Height / 2); mouseRotationBuffer.X -= 0.01f * deltaX * dt; mouseRotationBuffer.Y -= 0.01f * deltaY * dt; //if (mouseRotationBuffer.X < MathHelper.ToRadians(-75.0f)) // mouseRotationBuffer.X = mouseRotationBuffer.X - (mouseRotationBuffer.X - MathHelper.ToRadians(-75.0f)); //if (mouseRotationBuffer.X < MathHelper.ToRadians(75.0f)) // mouseRotationBuffer.X = mouseRotationBuffer.X - (mouseRotationBuffer.X - MathHelper.ToRadians(75.0f)); Rotation = new Vector3( -MathHelper.Clamp( mouseRotationBuffer.Y, MathHelper.ToRadians(-75.0f), MathHelper.ToRadians(75.0f)), MathHelper.WrapAngle(mouseRotationBuffer.X), 0); deltaX = 0; deltaY = 0; } Mouse.SetPosition(Game.GraphicsDevice.Viewport.Width / 2, Game.GraphicsDevice.Viewport.Height / 2); prevMouseState = currentMouseState; base.Update(gameTime); }
protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } //UPDATING PLAYING STATE switch (gameState) { //UPDATING MENU STATE case State.Menu: { //Get keyboard state KeyboardState ks = Keyboard.GetState(); if (ks.IsKeyDown(Keys.Enter)) { gameState = State.Playing; } space.Update(gameTime); break; } case State.Playing: { space.Update(gameTime); ship.Update(gameTime); hud.Update(gameTime); explosion.Update(gameTime); foreach (AsteroidLeft asteroid in asteroidList) { //Check enemy bullet with player ship for (int i = 0; i < asteroid.asteroidList.Count; i++) { if (ship.trickRec.Intersects(asteroid.asteroidList[i].boundingBox) || ship.trickRec2.Intersects(asteroid.asteroidList[i].boundingBox) || ship.trickRec3.Intersects(asteroid.asteroidList[i].boundingBox) || ship.trickRec4.Intersects(asteroid.asteroidList[i].boundingBox) || ship.trickRec5.Intersects(asteroid.asteroidList[i].boundingBox)) { ship.isVisible = false; explosion.isVisible = true; } if (ship.ScoretrickRec.Intersects(asteroid.asteroidList[i].boundingBox)) { hud.counter += 1; if (hud.counter == 149) { hud.counter = 0; } hud.openerMusic = true; } } asteroid.Update(gameTime); } foreach (AsteroidRight asteroid2 in asteroid2List) { //Check enemy bullet with player ship for (int i = 0; i < asteroid2.asteroidList.Count; i++) { if (ship.trickRec.Intersects(asteroid2.asteroidList[i].boundingBox) || ship.trickRec2.Intersects(asteroid2.asteroidList[i].boundingBox) || ship.trickRec3.Intersects(asteroid2.asteroidList[i].boundingBox) || ship.trickRec4.Intersects(asteroid2.asteroidList[i].boundingBox) || ship.trickRec5.Intersects(asteroid2.asteroidList[i].boundingBox)) { ship.isVisible = false; explosion.isVisible = true; } } asteroid2.Update(gameTime); } if (!ship.isVisible) { explosion.isVisible = true; // sürekli yeni asteroid göndermesin diye update metodunu kapatarak hem pozisyonunu deðiþtirmiyor ve durmuþ gibi efekt veriyor foreach (AsteroidLeft asteroid in asteroidList) { asteroid.updateBool = false; } foreach (AsteroidRight asteroid2 in asteroid2List) { asteroid2.updateBool = false; } ship.ScoretrickPos = new Vector2(401, 0); // sayaç için konulan rectangle ý kesiþmicek þekile dýþarý gönderiyor. space.speed = 0; //arka planý durduruyor explosion.keyboardBool = false; hud.openerMusic = false; Delay--; if (Delay == 0) { explosion.drawVisible = false; gameState = State.Gameover; Delay = 25; } explosion.explosionMusic = true; hud.shipSound = false; } LoadAsteroids(); LoadAsteroids2(); break; } //UPDATING GAMEOVER STATE case State.Gameover: { break; } } base.Update(gameTime); }
/// <summary> /// Determines whether or not the key was pressed this frame. /// </summary> /// <param name="key">Key to check.</param> /// <returns>Whether or not the key was pressed.</returns> public bool WasKeyPressed(Keys key) { return(KeyboardInput.IsKeyDown(key) && PreviousKeyboardInput.IsKeyUp(key)); }
//Methods from IMovable public void Move(KeyboardState keyBoardState) { keyBoardState = Keyboard.GetState(); this.Velocity = Vector2.Zero; if (keyBoardState.IsKeyDown(Keys.Up)) { this.velocity.Y = -movementSpeed.Y; } if (keyBoardState.IsKeyDown(Keys.Left)) { this.velocity.X = -movementSpeed.X; } if (keyBoardState.IsKeyDown(Keys.Down)) { this.velocity.Y = movementSpeed.Y; } if (keyBoardState.IsKeyDown(Keys.Right)) { this.velocity.X = movementSpeed.X; } this.Position += this.velocity; }
public bool CheckKey(Keys theKey) { return(lastKeyboardState.IsKeyDown(theKey) && currentKeyboardState.IsKeyUp(theKey)); }
private bool IsKeyDownAndChanged(KeyboardState keyState, Keys key) { bool keyDown = keyState.IsKeyDown(key); bool changed = keyDown != _oldState.IsKeyDown(key); return (keyDown && changed); }
private void UpdatePlayer(GameTime gameTime) { player.Update(gameTime); // Get Thumbstick Controls player.position.X += currentGamePadState.ThumbSticks.Left.X * playerMoveSpeed; player.position.Y -= currentGamePadState.ThumbSticks.Left.Y * playerMoveSpeed; // Use the Keyboard / Dpad if (currentKeyboardState.IsKeyDown(Keys.Left) || currentGamePadState.DPad.Left == ButtonState.Pressed) { player.position.X -= playerMoveSpeed; } if (currentKeyboardState.IsKeyDown(Keys.Right) || currentGamePadState.DPad.Right == ButtonState.Pressed) { player.position.X += playerMoveSpeed; } if (currentKeyboardState.IsKeyDown(Keys.Up) || currentGamePadState.DPad.Up == ButtonState.Pressed) { player.position.Y -= playerMoveSpeed; } if (currentKeyboardState.IsKeyDown(Keys.Down) || currentGamePadState.DPad.Down == ButtonState.Pressed) { player.position.Y += playerMoveSpeed; } // Make sure that the player does not go out of bounds player.position.X = MathHelper.Clamp(player.Position.X, 0, GraphicsDevice.Viewport.Width - player.Width); player.position.Y = MathHelper.Clamp(player.Position.Y, 0, GraphicsDevice.Viewport.Height - player.Height); // Fire Projectiles if (currentGamePadState.Buttons.B == ButtonState.Pressed) { // Fire only when button is held with same rate as autofire if (gameTime.TotalGameTime - previousFireTime > fireTime) { // Reset our current time previousFireTime = gameTime.TotalGameTime; // Add the projectile, but add it to the front and center of the player AddProjectile(player.Position + new Vector2(player.Width / 2, 0)); // Play the laser sound laserSound.Play(); } } // Fire Lasers if (currentGamePadState.Buttons.X == ButtonState.Pressed) { // Fire only when button is held with same rate as autofire if (gameTime.TotalGameTime - previousFireTime > fireTime) { // Reset our current time previousFireTime = gameTime.TotalGameTime; // Add the projectile, but add it to the front and center of the player AddLaser(player.Position + new Vector2(player.Width / 2, 0)); // Play the laser sound laserSound.Play(); } } // Fire Troll if (currentGamePadState.Buttons.Y == ButtonState.Pressed) { // Fire only when button is held with same rate as autofire if (gameTime.TotalGameTime - previousFireTime > fireTime) { // Reset our current time previousFireTime = gameTime.TotalGameTime; // Add the projectile, but add it to the front and center of the player AddTroll(player.Position + new Vector2(player.Width / 2, 0)); // Play the laser sound laserSound.Play(); } } // Fire All if (currentGamePadState.Buttons.RightShoulder == ButtonState.Pressed) { // Fire only when button is held with same rate as autofire if (gameTime.TotalGameTime - previousFireTime > fireTime) { // Reset our current time previousFireTime = gameTime.TotalGameTime; // Add the projectile, but add it to the front and center of the player AddProjectile(player.Position + new Vector2(player.Width / 2, 0)); AddLaser(player.Position + new Vector2(player.Width / 2, 0)); AddTroll(player.Position + new Vector2(player.Width / 2, 0)); // Play the laser sound laserSound.Play(); } } // reset score if player health goes to zero if (player.Health <= 0) { player.Health = 100; score = 0; } }
protected void handleKeyboard(float dt) { keystate = Keyboard.GetState(); /* Lateral movement */ if (keystate.IsKeyDown(Key.W)) position += forward * speed * dt; if (keystate.IsKeyDown(Key.S)) position -= forward * speed * dt; if (keystate.IsKeyDown(Key.A)) position -= right * speed * dt; if (keystate.IsKeyDown(Key.D)) position += right * speed * dt; /* Fly up/down */ if (keystate.IsKeyDown(Key.Space)) position.Y += speed * dt; if (keystate.IsKeyDown(Key.LShift)) position.Y -= speed * dt; /* Keyboard turn */ if (keystate.IsKeyDown(Key.Left)) yaw -= keyTurnSpeed * dt; if (keystate.IsKeyDown(Key.Right)) yaw += keyTurnSpeed * dt; if (keystate.IsKeyDown(Key.Up)) pitch += keyTurnSpeed * dt; if (keystate.IsKeyDown(Key.Down)) pitch -= keyTurnSpeed * dt; }