public void Update() { gamePadState = GamePad.GetState(PlayerIndex.One); bool foundInput = false; if (gamePadState.IsButtonDown(Buttons.Start) && !startPressed) { startPressed = true; new StartButtonCommand().Execute(); } else if (gamePadState.IsButtonUp(Buttons.Start) && startPressed) { startPressed = false; } if (playableObject.IsEnteringPipe || playableObject.IsExitingPipe) { new MarioNoInputCommand(playableObject).Execute(); } else { if (gamePadState.IsButtonDown(Buttons.A) && !jumpPressed) { jumpPressed = true; new MarioJumpCommand(playableObject).Execute(); foundInput = true; } else if (gamePadState.IsButtonDown(Buttons.A)) { foundInput = true; } else if (gamePadState.IsButtonUp(Buttons.A) && jumpPressed) { jumpPressed = false; } if (gamePadState.IsButtonDown(Buttons.B)) { playableObject.MaxHorizontalVelocity = GameValues.MarioRunningSpeed; new MarioRunCommand(playableObject).Execute(); } else { playableObject.MaxHorizontalVelocity = GameValues.MarioWalkingSpeed; } foreach (KeyValuePair<Buttons, ICommand> item in buttonMap) { if (gamePadState.IsButtonDown(item.Key)) { item.Value.Execute(); foundInput = true; } } if (!foundInput) { new MarioNoInputCommand(playableObject).Execute(); } } }
public static List<InputManager.ACTIONS> GetInput() { currentGamePadState = GamePad.GetState(PlayerIndex.One); List<InputManager.ACTIONS> actions = new List<InputManager.ACTIONS>(); if (currentGamePadState.IsButtonUp(Buttons.A) && previousGamePadState.IsButtonDown(Buttons.A)) { actions.Add(InputManager.ACTIONS.JUMP); } if (currentGamePadState.ThumbSticks.Left.X > 0 || currentGamePadState.DPad.Right == ButtonState.Pressed) { actions.Add(InputManager.ACTIONS.RIGHT); } else if (currentGamePadState.ThumbSticks.Left.X < 0 || currentGamePadState.DPad.Left == ButtonState.Pressed) { actions.Add(InputManager.ACTIONS.LEFT); } if (currentGamePadState.IsButtonUp(Buttons.Y) && previousGamePadState.IsButtonDown(Buttons.Y)) { actions.Add(InputManager.ACTIONS.TOGGLE); } previousGamePadState = currentGamePadState; return actions; }
public void PerformMove(Move moveToPerform, KeyboardState keyboardStateInput, GamePadState gamepadStateInput) { if (moveToPerform.name == "RunLeft") { _speed.X = -1.25f; if (gamepadStateInput.IsButtonUp(Buttons.DPadLeft) && gamepadStateInput.IsButtonUp(Buttons.LeftThumbstickLeft) && keyboardStateInput.IsKeyUp(Keys.Left)) { _speed.X = 0; _playerMostRecentMove = null; } } if (moveToPerform.name == "RunRight") { _speed.X = 1.25f; if (gamepadStateInput.IsButtonUp(Buttons.DPadRight) && gamepadStateInput.IsButtonUp(Buttons.LeftThumbstickRight) && keyboardStateInput.IsKeyUp(Keys.Right)) { _speed.X = 0; _playerMostRecentMove = null; } } if (moveToPerform.name == "SprintLeft") { _speed.X = -1.75f; if (gamepadStateInput.IsButtonUp(Buttons.DPadLeft) && gamepadStateInput.IsButtonUp(Buttons.LeftThumbstickLeft) && keyboardStateInput.IsKeyUp(Keys.Left)) { _speed.X = 0; _playerMostRecentMove = null; } } if (moveToPerform.name == "SprintRight") { _speed.X = 1.75f; if (gamepadStateInput.IsButtonUp(Buttons.DPadRight) && gamepadStateInput.IsButtonUp(Buttons.LeftThumbstickRight) && keyboardStateInput.IsKeyUp(Keys.Right)) { _speed.X = 0; _playerMostRecentMove = null; } } if (moveToPerform.name == "Jump") { _isJumping = true; /*if (gamepadStateInput.IsButtonUp(Buttons.A) && keyboardStateInput.IsKeyUp(Keys.A)) { isJumping = false; playerMostRecentMove = null; }*/ } }
// Adds an attack when the attack button is pressed accompanied by sound and animation public static void AttackAdd(ContentManager Content, Player ninja, List<PlayerAttack> ninjaAttacks, KeyboardState presentKey, KeyboardState pastKey, GamePadState pressentButton, GamePadState pastButton) { if (presentKey.IsKeyDown(Keys.Space) && pastKey.IsKeyUp(Keys.Space) || pressentButton.IsButtonDown(Buttons.A) && pastButton.IsButtonUp(Buttons.A)) { // if the attack button is pressed a new attack will be added to the list ninjaAttacks.Add(new PlayerAttack(Content.Load<Texture2D>("Images\\Attack"), new Vector2(ninja.PositionX + (int)(ninja.Texture.Width * 0.8), ninja.PositionY + (int)(ninja.Texture.Height / 2.25)))); // A sound effect will be played each time we press the attack button ninja.PlaySound(); } // The animation texture of the character will change with each attack if (presentKey.IsKeyDown(Keys.Space) || pressentButton.IsButtonDown(Buttons.A)) { ninja.Texture = Content.Load<Texture2D>("Images\\NinjaFrame1-2"); } else { ninja.Texture = Content.Load<Texture2D>("Images\\NinjaFrame1-1"); } }
protected void AmbientToggle(KeyboardState currentKeyboardState, GamePadState currentGamePadState) { // toggle Ambient - Night/Day effect if (previousKeyboardState.IsKeyDown(Keys.E) && currentKeyboardState.IsKeyUp(Keys.E) || previousGamePadState.IsButtonDown(Buttons.RightShoulder) && currentGamePadState.IsButtonUp(Buttons.RightShoulder)) { ambient = !ambient; currentMusic.Stop(); currentMusic.Dispose(); // Ambient true sets to day time effect, false sets to night time effect if(ambient) { skyColor = Color.DeepSkyBlue; effect.Parameters["material"].StructureMembers["ambient"].SetValue(new Vector4(0.65f, 0.65f, 0.6f, 1.0f)); currentMusic = musicDay.CreateInstance(); } else { skyColor = Color.DarkSlateGray; effect.Parameters["material"].StructureMembers["ambient"].SetValue(new Vector4(0.1f, 0.1f, 0.15f, 1.0f)); currentMusic = musicNight.CreateInstance(); } enemy.Apply3DAudio(listener, enemy.Position, currentMusic); currentMusic.Play(); } }
public void InputsPlayer(GameTime gameTime, bool move, bool jump, Player player) { // Save previous keyboard/gamepad states previousKeyboardState = currentKeyboardState; previousGamepadState = currentGamepadState; // Read current keyboard/gamepad currentKeyboardState = Keyboard.GetState(); currentGamepadState = GamePad.GetState(PlayerIndex.One); if (move && player.CanMove) { if (currentKeyboardState.IsKeyDown(Keys.Left) || currentGamepadState.ThumbSticks.Left.X < 0) player.Move(-1f); else if (currentKeyboardState.IsKeyDown(Keys.Right) || currentGamepadState.ThumbSticks.Left.X > 0) player.Move(1f); else player.Move(0f); } if (player.CanJump && jump) { if (currentGamepadState.IsButtonDown(Buttons.A) && previousGamepadState.IsButtonUp(Buttons.A)) player.Jump(); else if (currentKeyboardState.IsKeyDown(Keys.Z) && previousKeyboardState.IsKeyUp(Keys.Z)) player.Jump(); } if (player.IsOverDoor) { if (currentGamepadState.ThumbSticks.Left.Y < 0 && previousGamepadState.ThumbSticks.Left.Y < 0 && player.Velocity.X == 0 ) player.EnterDoor(); else if (currentKeyboardState.IsKeyDown(Keys.Up) && previousKeyboardState.IsKeyUp(Keys.Up) && player.Velocity.X == 0 ) player.EnterDoor(); } if (currentGamepadState.IsButtonDown(Buttons.B) && previousGamepadState.IsButtonUp(Buttons.B)) player.Attack(gameTime); else if (currentKeyboardState.IsKeyDown(Keys.X) && previousKeyboardState.IsKeyUp(Keys.X)) player.Attack(gameTime); }
public static void PickupGold(GamePadState gs, GamePadState previousGamePadState, Player player, GameTime gameTime) { var pickupGoldButton = actionKeys[Action.PickupGold]; if (gs.IsButtonDown(pickupGoldButton) && previousGamePadState.IsButtonUp(pickupGoldButton)) { player.AttemptPickupGold(); } }
public static bool IsButtonPressed(this GamePadState state, GamePadState oldState, params Buttons[] buttons) { bool result = false; foreach (Buttons button in buttons) { result = state.IsButtonDown(button) && oldState.IsButtonUp(button); if (result) break; } return result; }
// Update & Draw public void Update(MouseState mouse, KeyboardState keyboard, GamePadState gamePadState) { for (int i = 0; i < _btnNumber; i++) _buttons[i].Update(mouse, keyboard); if (keyboard.IsKeyDown(Keys.Down) || gamePadState.IsButtonDown(Buttons.DPadDown)) DownButton(); if (keyboard.IsKeyUp(Keys.Down) && gamePadState.IsButtonUp(Buttons.DPadDown)) _currentDownState = false; if (keyboard.IsKeyDown(Keys.Up) || gamePadState.IsButtonDown(Buttons.DPadUp)) UpButton(); if (keyboard.IsKeyUp(Keys.Up) && gamePadState.IsButtonUp(Buttons.DPadUp)) _currentUpState = false; if (keyboard.IsKeyDown(Keys.Enter) || gamePadState.Buttons.Start == ButtonState.Pressed || gamePadState.Buttons.A == ButtonState.Pressed) { switch (_selection) { case 0: { Game1.gameState = GameState.Game; break; } case 1: { break; } case 2: { exitGame = true; break; } } } }
public void Update(GamePadState currentGamePadState, GamePadState previousGamePadState, KeyboardState currentKeyboardState, KeyboardState previousKeyboardState, Game1 game) { float stickY = currentGamePadState.ThumbSticks.Left.Y; spritePosition.Y -= stickY * spriteSpeed; if(currentKeyboardState.IsKeyDown(Keys.W)) { spritePosition.Y -= spriteSpeed; } if (currentKeyboardState.IsKeyDown(Keys.S)) { spritePosition.Y += spriteSpeed; } if (spritePosition.Y <= 0) { spritePosition.Y = 0; } else if (spritePosition.Y >= Game1.SCREEN_HEIGHT - spriteTexture.Height) { spritePosition.Y = Game1.SCREEN_HEIGHT - spriteTexture.Height; } if (currentGamePadState.IsButtonDown(Buttons.A) && previousGamePadState.IsButtonUp(Buttons.A)) { if (Ammo > 0) { arrows.Add(new Missile(arrowTexture, new Vector2(this.spritePosition.X, this.spritePosition.Y + 13), 8.0f)); Ammo--; } } List<Missile> newArrowList = new List<Missile>(); foreach(Missile arrow in arrows) { arrow.Update(game); if (arrow.getActive()) { newArrowList.Add(arrow); } } arrows = newArrowList; }
public void CheckGamePadInput(GamePadState pad, GamePadState padOld, int player) { Buttons[] buttons = new Buttons[] { Buttons.A, Buttons.B, Buttons.X, Buttons.Y, Buttons.LeftShoulder, Buttons.RightShoulder }; for (int i = 0; i < 6; i++) { if (enabledReactions[i] && pad.IsButtonDown(buttons[i]) && padOld.IsButtonUp(buttons[i]) && !hasBeenPressed[player, i]) { reactionTimes[player, i] = "Time: " + timers[i] / 60 + Math.Abs((timers[i] % 60) / 60.0).ToString(".###"); hasBeenPressed[player, i] = true; if (timers[i] >= 0) reactionTimeTotals[player] += timers[i]; else if (-timers[i] >= 60) reactionTimeTotals[player] += -timers[i]; else reactionTimeTotals[player] += 60; } } }
/// <summary> /// Updates one gamepad state /// </summary> internal void Update() { _previousState = _currentState; _currentState = XnaGamePad.GetState(_gamePadIndex); if (!_previousState.IsConnected) { if (_currentState.IsConnected) { if (Connected != null) Connected(this, new GamePadEventArgs(this)); } } else { if (!_currentState.IsConnected) { if (Disconnected != null) Disconnected(this, new GamePadEventArgs(this)); } } if (!_currentState.IsConnected) return; GamePadThumbSticks prevThumb = _previousState.ThumbSticks; GamePadThumbSticks currThumb = _currentState.ThumbSticks; _thumbRightDelta = Vector2.Subtract(currThumb.Right, prevThumb.Right); _thumbLeftDelta = Vector2.Subtract(currThumb.Left, prevThumb.Left); GamePadTriggers prevTrigger = _previousState.Triggers; GamePadTriggers currTrigger = _currentState.Triggers; _triggerRightDelta = currTrigger.Right - prevTrigger.Right; _triggerLeftDelta = currTrigger.Left - prevTrigger.Left; InternalButtonPressed.Clear(); for (short i = 0; i < AllDigital.Length; i++) { if(_currentState.IsButtonUp(AllDigital[i])) continue; AbstractButton btn = new AbstractButton(AllDigital[i]); InternalButtonPressed.Add(new ButtonEvent(btn, (short)_gamePadIndex)); } }
private void checkGameInput() { newState = Keyboard.GetState(); P1newPadState = GamePad.GetState(PlayerIndex.One); P2newPadState = GamePad.GetState(PlayerIndex.Two); if (oldState.IsKeyDown(Keys.D) || P1oldPadState.IsButtonDown(Buttons.DPadRight)) { player1.playerShip.physicsObj.body.Rotation += 0.1f; } if (oldState.IsKeyDown(Keys.A) || P1oldPadState.IsButtonDown(Buttons.DPadLeft)) { player1.playerShip.physicsObj.body.Rotation -= 0.1f; } if (oldState.IsKeyDown(Keys.W) || P1oldPadState.IsButtonDown(Buttons.DPadUp)) { Ship Player1Ship = player1.playerShip; Vector2 direction = new Vector2((float)(Math.Cos(Player1Ship.physicsObj.body.GetAngle())), (float)(Math.Sin(Player1Ship.physicsObj.body.GetAngle()))); direction.Normalize(); direction *= shipSpeed; Player1Ship.physicsObj.body.ApplyLinearImpulse(direction, Player1Ship.physicsObj.body.GetWorldCenter()); } if ((oldState.IsKeyDown(Keys.X) && newState.IsKeyUp(Keys.X)) || (P1oldPadState.IsButtonDown(Buttons.A) && P1newPadState.IsButtonUp(Buttons.A))) { player1.createMissile(); } if (oldState.IsKeyDown(Keys.C) && newState.IsKeyUp(Keys.C) || (P1oldPadState.IsButtonDown(Buttons.B) && P1newPadState.IsButtonUp(Buttons.B))) { if(player1.state == PlayerState.alive) GameObjManager.Instance().createBomb(PlayerID.one); } if (oldState.IsKeyDown(Keys.Right) || P2oldPadState.IsButtonDown(Buttons.DPadRight)) { player2.playerShip.physicsObj.body.Rotation += 0.1f; } if (oldState.IsKeyDown(Keys.Left) || P2oldPadState.IsButtonDown(Buttons.DPadLeft)) { player2.playerShip.physicsObj.body.Rotation -= 0.1f; } if (oldState.IsKeyDown(Keys.Up) || P2oldPadState.IsButtonDown(Buttons.DPadUp)) { Ship Player2Ship = player2.playerShip; Vector2 direction = new Vector2((float)(Math.Cos(Player2Ship.physicsObj.body.GetAngle())), (float)(Math.Sin(Player2Ship.physicsObj.body.GetAngle()))); direction.Normalize(); direction *= shipSpeed; Player2Ship.physicsObj.body.ApplyLinearImpulse(direction, Player2Ship.physicsObj.body.GetWorldCenter()); } if ((oldState.IsKeyDown(Keys.OemQuestion) && newState.IsKeyUp(Keys.OemQuestion)) || (P2oldPadState.IsButtonDown(Buttons.A) && P2newPadState.IsButtonUp(Buttons.A))) { player2.createMissile(); } if (oldState.IsKeyDown(Keys.OemPeriod) && newState.IsKeyUp(Keys.OemPeriod) || (P2oldPadState.IsButtonDown(Buttons.B) && P2newPadState.IsButtonUp(Buttons.B))) { if (player2.state == PlayerState.alive && BombManager.Instance().bombAvailable(PlayerID.two)) GameObjManager.Instance().createBomb(PlayerID.two); } else { } P1oldPadState = P1newPadState; P2oldPadState = P2newPadState; oldState = newState; }
private void GetInput(GamePadState gamePadState, GameTime gameTime) { Vector2 leftStick = gamePadState.ThumbSticks.Right; Vector2 rightStick = gamePadState.ThumbSticks.Right; if (rightStick != Vector2.Zero) { Rotation = (float)Math.Atan2(rightStick.X, rightStick.Y); } //Get analog horizontal movement movement = gamePadState.ThumbSticks.Left.X * MoveStickScale; //Ignore small movements to prevent running in place if (Math.Abs(movement) < 0.5f) movement = 0.0f; // If any digital horizontal movement is found, override the analog movement if (gamePadState.IsButtonDown(Buttons.DPadLeft)) movement = -1.0f; else if (gamePadState.IsButtonDown(Buttons.DPadRight)) movement = 1.0f; // Check if the player wants to jump isJumping = gamePadState.IsButtonDown(JumpButton); // Check if the player wants to shoot if (gameTime.TotalGameTime - previousFireTime > fireTime) { if (gamePadState.IsButtonUp(ShootButton)) { if (gamePadState.IsButtonDown(Buttons.LeftTrigger)) { if (shootHeat < 0) shootHeat = 0; shootHeat -= 0.1f; } } if (gamePadState.IsButtonDown(ShootButton)) { if (shootHeat > 5) { shootHeat = 5; shootOverheat = true; } if (shootHeat < 0 || shootHeat == 0) { shootHeat = 0; shootOverheat = false; } if (shootOverheat == false) { AddBullet(Vector2.Zero); previousFireTime = gameTime.TotalGameTime; shootHeat += 0.2f; } } } }
public void Movement(GameTime gameTime) { _gamePadState = GamePad.GetState(PlayerIndex.One); //Press X to Speed Up! if (Keyboard.GetState().IsKeyDown(Keys.X) || (_gamePadState.IsButtonDown(Buttons.X))) { _topSpeed = 5f; } else { _topSpeed = 3f; } //If We reach top speed, we can't increase velocity anymore if (_velocity.X < _topSpeed+1&&_velocity.X>-_topSpeed-1) { if (Keyboard.GetState().IsKeyDown(Keys.Left) || (_gamePadState.IsButtonDown(Buttons.DPadLeft))) { //Animation stuff if (_canJump) { _currentState = State.RUNNINGLEFT; } _acceleration.X -= .3f; } else if (Keyboard.GetState().IsKeyDown(Keys.Right) || (_gamePadState.IsButtonDown(Buttons.DPadRight))) { //Animation stuff if (_canJump) { _currentState = State.RUNNINGRIGHT; } _acceleration.X += .3f; } else { //Animation stuff if (_canJump&&(_previousState==State.RUNNINGRIGHT||_previousState==State.JUMPINGRIGHT)) { _currentState = State.IDLERIGHT; } if (_canJump && (_previousState == State.RUNNINGLEFT || _previousState == State.JUMPINGLEFT)) { _currentState = State.IDLELEFT; } _acceleration.X = 2f * -_velocity.X; } //Update Velocity _velocity.X += _acceleration.X * (float)gameTime.ElapsedGameTime.TotalSeconds; } else { //Accounting for top speed on + and - if (_velocity.X > -_topSpeed -1) _velocity.X = _topSpeed; else _velocity.X = -_topSpeed; //Reset Acceleration or bad things happen _acceleration.X = 0; } _lastJump = _velocity.Y; //Now for that Y Position... if ((Keyboard.GetState().IsKeyDown(Keys.Z)||(_gamePadState.IsButtonDown(Buttons.A))) && _canJump && _noSpamJump) { _jumpSFX.Play(); _velocity.Y = -_jumpSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; _canJump = false; //Console.WriteLine("Jumped"); //For Counting Jumps and no spamming if (_bruteCount == 0) { _noJumps++; } if (_bruteCount == 3) { _noSpamJump = false; } _bruteCount++; } //NO SPAM JUMPING if (Keyboard.GetState().IsKeyUp(Keys.Z)&&(_gamePadState.IsButtonUp(Buttons.A))) { _noSpamJump = true; _bruteCount = 0; } //Gravity if (!_canJump) { _velocity.Y += _gravity * (float)gameTime.ElapsedGameTime.TotalSeconds; _jumpSpeed = 500f; } else _velocity.Y = 0; //If we've been facing left, jump left, et cetera for right if(!_canJump&&(_previousState==State.IDLELEFT||_previousState==State.RUNNINGLEFT)) { if(!_isColliding) _currentState = State.JUMPINGLEFT; } if (!_canJump && (_previousState == State.IDLERIGHT || _previousState == State.RUNNINGRIGHT)) { if (!_isColliding) _currentState = State.JUMPINGRIGHT; } _canJump = _playerDefaultPosition.Y >= 900; //Finally, Update your actual position and state _playerDefaultPosition+= _velocity; _previousState = _currentState; //DEBUG //Console.WriteLine("Jumps: " + _noJumps); //Console.WriteLine("IsColliding: " + _isColliding); //Console.WriteLine("Position: " + _playerDefaultPosition); //Console.WriteLine("Acceleration: " + _acceleration.X); //Console.WriteLine("Velocity: " + _velocity.X); //Console.WriteLine("X: " + _playerDefaultPosition.X + " Y: " + _playerDefaultPosition.Y); }
/// <summary> /// Handles the input and movement of the character. /// </summary> /// <param name="dt">Time since last frame in simulation seconds.</param> /// <param name="previousKeyboardInput">The last frame's keyboard state.</param> /// <param name="keyboardInput">The current frame's keyboard state.</param> /// <param name="previousGamePadInput">The last frame's gamepad state.</param> /// <param name="gamePadInput">The current frame's keyboard state.</param> public void Update(float dt, KeyboardState previousKeyboardInput, KeyboardState keyboardInput, GamePadState previousGamePadInput, GamePadState gamePadInput) { if (IsActive) { //Note that the character controller's update method is not called here; this is because it is handled within its owning space. //This method's job is simply to tell the character to move around based on the Camera and input. ////Rotate the camera of the character based on the support velocity, if a support with velocity exists. ////This can be very disorienting in some cases; that's why it is off by default! //if (CharacterController.SupportFinder.HasSupport) //{ // SupportData? data; // if (CharacterController.SupportFinder.HasTraction) // data = CharacterController.SupportFinder.TractionData; // else // data = CharacterController.SupportFinder.SupportData; // EntityCollidable support = data.Value.SupportObject as EntityCollidable; // if (support != null && !support.Entity.IsDynamic) //Having the view turned by dynamic entities is extremely confusing for the most part. // { // float dot = Vector3.Dot(support.Entity.AngularVelocity, CharacterController.Body.OrientationMatrix.Up); // Camera.Yaw += dot * dt; // } //} if (UseCameraSmoothing) { //First, find where the camera is expected to be based on the last position and the current velocity. //Note: if the character were a free-floating 6DOF character, this would need to include an angular velocity contribution. //And of course, the camera orientation would be based on the character's orientation. Camera.Position = Camera.Position + CharacterController.Body.LinearVelocity * dt; //Now compute where it should be according the physical body of the character. Vector3 up = CharacterController.Body.OrientationMatrix.Up; Vector3 bodyPosition = CharacterController.Body.BufferedStates.InterpolatedStates.Position; Vector3 goalPosition = bodyPosition + up * (CharacterController.StanceManager.CurrentStance == Stance.Standing ? StandingCameraOffset : CrouchingCameraOffset); //Usually, the camera position and the goal will be very close, if not matching completely. //However, if the character steps or has its position otherwise modified, then they will not match. //In this case, we need to correct the camera position. //To do this, first note that we can't correct infinite errors. We need to define a bounding region that is relative to the character //in which the camera can interpolate around. The most common discontinuous motions are those of upstepping and downstepping. //In downstepping, the character can teleport up to the character's MaximumStepHeight downwards. //In upstepping, the character can teleport up to the character's MaximumStepHeight upwards, and the body's CollisionMargin horizontally. //Picking those as bounds creates a constraining cylinder. Vector3 error = goalPosition - Camera.Position; float verticalError = Vector3.Dot(error, up); Vector3 horizontalError = error - verticalError * up; //Clamp the vertical component of the camera position within the bounding cylinder. if (verticalError > CharacterController.StepManager.MaximumStepHeight) { Camera.Position -= up * (CharacterController.StepManager.MaximumStepHeight - verticalError); verticalError = CharacterController.StepManager.MaximumStepHeight; } else if (verticalError < -CharacterController.StepManager.MaximumStepHeight) { Camera.Position -= up * (-CharacterController.StepManager.MaximumStepHeight - verticalError); verticalError = -CharacterController.StepManager.MaximumStepHeight; } //Clamp the horizontal distance too. float horizontalErrorLength = horizontalError.LengthSquared(); float margin = CharacterController.Body.CollisionInformation.Shape.CollisionMargin; if (horizontalErrorLength > margin * margin) { Vector3 previousHorizontalError = horizontalError; Vector3.Multiply(ref horizontalError, margin / (float)Math.Sqrt(horizontalErrorLength), out horizontalError); Camera.Position -= horizontalError - previousHorizontalError; } //Now that the error/camera position is known to lie within the constraining cylinder, we can perform a smooth correction. //This removes a portion of the error each frame. //Note that this is not framerate independent. If fixed time step is not enabled, //a different smoothing method should be applied to the final error values. //float errorCorrectionFactor = .3f; //This version is framerate independent, although it is more expensive. float errorCorrectionFactor = (float)(1 - Math.Pow(.000000001, dt)); Camera.Position += up * (verticalError * errorCorrectionFactor); Camera.Position += horizontalError * errorCorrectionFactor; } else { Camera.Position = CharacterController.Body.Position + (CharacterController.StanceManager.CurrentStance == Stance.Standing ? StandingCameraOffset : CrouchingCameraOffset) * CharacterController.Body.OrientationMatrix.Up; } Vector2 totalMovement = Vector2.Zero; #if XBOX360 Vector3 forward = Camera.WorldMatrix.Forward; forward.Y = 0; forward.Normalize(); Vector3 right = Camera.WorldMatrix.Right; totalMovement += gamePadInput.ThumbSticks.Left.Y * new Vector2(forward.X, forward.Z); totalMovement += gamePadInput.ThumbSticks.Left.X * new Vector2(right.X, right.Z); CharacterController.HorizontalMotionConstraint.MovementDirection = Vector2.Normalize(totalMovement); CharacterController.StanceManager.DesiredStance = gamePadInput.IsButtonDown(Buttons.RightStick) ? Stance.Crouching : Stance.Standing; //Jumping if (previousGamePadInput.IsButtonUp(Buttons.LeftStick) && gamePadInput.IsButtonDown(Buttons.LeftStick)) { CharacterController.Jump(); } #else //Collect the movement impulses. Vector3 movementDir; if (keyboardInput.IsKeyDown(Keys.E)) { movementDir = Camera.WorldMatrix.Forward; totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z)); } if (keyboardInput.IsKeyDown(Keys.D)) { movementDir = Camera.WorldMatrix.Forward; totalMovement -= Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z)); } if (keyboardInput.IsKeyDown(Keys.S)) { movementDir = Camera.WorldMatrix.Left; totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z)); } if (keyboardInput.IsKeyDown(Keys.F)) { movementDir = Camera.WorldMatrix.Right; totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z)); } if (totalMovement == Vector2.Zero) CharacterController.HorizontalMotionConstraint.MovementDirection = Vector2.Zero; else CharacterController.HorizontalMotionConstraint.MovementDirection = Vector2.Normalize(totalMovement); CharacterController.StanceManager.DesiredStance = keyboardInput.IsKeyDown(Keys.Z) ? Stance.Crouching : Stance.Standing; //Jumping if (previousKeyboardInput.IsKeyUp(Keys.A) && keyboardInput.IsKeyDown(Keys.A)) { CharacterController.Jump(); } #endif } }
/// <summary> /// Handles the input and movement of the character. /// </summary> /// <param name="dt">Time since last frame in simulation seconds.</param> /// <param name="previousKeyboardInput">The last frame's keyboard state.</param> /// <param name="keyboardInput">The current frame's keyboard state.</param> /// <param name="previousGamePadInput">The last frame's gamepad state.</param> /// <param name="gamePadInput">The current frame's keyboard state.</param> public void Update(float dt, KeyboardState previousKeyboardInput, KeyboardState keyboardInput, GamePadState previousGamePadInput, GamePadState gamePadInput) { if (IsActive) { //Note that the character controller's update method is not called here; this is because it is handled within its owning space. //This method's job is simply to tell the character to move around based on the Camera and input. //Puts the Camera at eye level. Camera.Position = CharacterController.Body.Position + CameraOffset; Vector2 totalMovement = Vector2.Zero; #if !WINDOWS Vector3 forward = Camera.WorldMatrix.Forward; forward.Y = 0; forward.Normalize(); Vector3 right = Camera.WorldMatrix.Right; totalMovement += gamePadInput.ThumbSticks.Left.Y * new Vector2(forward.X, forward.Z); totalMovement += gamePadInput.ThumbSticks.Left.X * new Vector2(right.X, right.Z); CharacterController.MovementDirection = Vector2.Normalize(totalMovement); //Jumping if (previousGamePadInput.IsButtonUp(Buttons.LeftStick) && gamePadInput.IsButtonDown(Buttons.LeftStick)) { CharacterController.Jump(); } #else //Collect the movement impulses. Vector3 movementDir; if (keyboardInput.IsKeyDown(Keys.E)) { movementDir = Camera.WorldMatrix.Forward; totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z)); } if (keyboardInput.IsKeyDown(Keys.D)) { movementDir = Camera.WorldMatrix.Forward; totalMovement -= Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z)); } if (keyboardInput.IsKeyDown(Keys.S)) { movementDir = Camera.WorldMatrix.Left; totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z)); } if (keyboardInput.IsKeyDown(Keys.F)) { movementDir = Camera.WorldMatrix.Right; totalMovement += Vector2.Normalize(new Vector2(movementDir.X, movementDir.Z)); } if (totalMovement == Vector2.Zero) CharacterController.MovementDirection = Vector2.Zero; else CharacterController.MovementDirection = Vector2.Normalize(totalMovement); //Jumping if (previousKeyboardInput.IsKeyUp(Keys.A) && keyboardInput.IsKeyDown(Keys.A)) { CharacterController.Jump(); } #endif } }
private bool IsButtonUp(Buttons button, ref GamePadState oldState, ref GamePadState newState) { return newState.IsButtonUp(button) && oldState.IsButtonDown(button); }
protected void WallToggle(KeyboardState currentKeyboardState, GamePadState currentGamePadState) { if ((previousKeyboardState.IsKeyDown(Keys.R) && currentKeyboardState.IsKeyUp(Keys.R)) || (previousGamePadState.IsButtonDown(Buttons.DPadDown) && currentGamePadState.IsButtonUp(Buttons.DPadDown))) { drawWall = !drawWall; } }
protected void MusicToggle(KeyboardState currentKeyboardState, GamePadState currentGamePadState) { if ((previousKeyboardState.IsKeyDown(Keys.X) && currentKeyboardState.IsKeyUp(Keys.X)) || (previousGamePadState.IsButtonDown(Buttons.RightStick) && currentGamePadState.IsButtonUp(Buttons.RightStick))) { music = !music; // toggle music on/off if (music) { currentMusic.Volume = 1f; } else { currentMusic.Volume = 0f; } } }
/// <summary> /// Handles Toggle Fog on and off /// </summary> /// <param name="currentKeyboardState">Current Keyboard state</param> /// <param name="currentGamePadState">Current GamePad state</param> protected void FogToggle(KeyboardState currentKeyboardState, GamePadState currentGamePadState) { if ((previousKeyboardState.IsKeyDown(Keys.Q) && currentKeyboardState.IsKeyUp(Keys.Q)) || (previousGamePadState.IsButtonDown(Buttons.X) && currentGamePadState.IsButtonUp(Buttons.X))) { fog = !fog; // toggle Fog on/off if (fog) { // enable fog effect.Parameters["fog"].StructureMembers["FogEnabled"].SetValue(true); // if music is on then half volume set while there is fog if (music) currentMusic.Volume = 0.5f; } else { //diable fog effect.Parameters["fog"].StructureMembers["FogEnabled"].SetValue(false); // if music is on then full volume while there is no fog if (music) currentMusic.Volume = 1f; } } }
public void UpdateInput(GameMaster game, GamePadState padState, GamePadState prevPadState) { if ((padState.IsButtonDown(Buttons.DPadDown) && prevPadState.IsButtonUp(Buttons.DPadDown)) || (padState.IsButtonDown(Buttons.LeftThumbstickDown) && prevPadState.IsButtonUp(Buttons.LeftThumbstickDown)) && selectedIndex < 1) { selectedIndex++; if (selectedIndex > 1) { selectedIndex = 1; } } else if ((padState.IsButtonDown(Buttons.DPadUp) && prevPadState.IsButtonUp(Buttons.DPadUp)) || (padState.IsButtonDown(Buttons.LeftThumbstickUp) && prevPadState.IsButtonUp(Buttons.LeftThumbstickUp)) && selectedIndex > -1) { selectedIndex--; if (selectedIndex < 0) { selectedIndex = 0; } } else if (GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.A)) { if (selectedIndex == 0) { MouseClicked((screenCenter.X - (startButton.Width / 2)), (int)(Height * 0.5859375), game); } else if (selectedIndex == 1) { MouseClicked((screenCenter.X - (startButton.Width / 2)), (int)(Height * 0.8463541667), game); } } else if (GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.Start) && prevPadState.IsButtonUp(Buttons.Start)) { MouseClicked((screenCenter.X - (startButton.Width / 2)), (int)(Height * 0.5859375), game); } }
public void updateWorld(GameTime gameTime) { gamePadState = GamePad.GetState(PlayerIndex.One); KeyboardState keyBoardState = Keyboard.GetState(); gameInterface.instance.updateStats(); //update the variables in gameInterface panel gameInterface.instance.summaryPanel.updateSummary(); //open menu keyboard hotkey if (keyBoardState.IsKeyDown(Keys.M) && buttonCheck == false) { if (inGameMenu.instance.visible == true) { gameInterface.instance.inGameMenuClicked(); inGameMenu.instance.visible = false; isPaused = false; } else { //open menu gameInterface.instance.inGameMenuClicked(); inGameMenu.instance.visible = true; gameInterface.instance.summaryPanel.visible = false; isPaused = true; } buttonCheck = true; } //open menu gamepad if (gamePadState.IsButtonDown(Buttons.Start) && buttonCheck2 == false) { if (inGameMenu.instance.visible == true) { inGameMenu.instance.visible = false; isPaused = false; } else { //open menu inGameMenu.instance.visible = true; //close summary if open gameInterface.instance.summaryPanel.visible = false; isPaused = true; } buttonCheck2 = true; } //test to see if hit multipe times if (keyBoardState.IsKeyUp(Keys.M) && buttonCheck == true) { buttonCheck = false; } if (gamePadState.IsButtonUp(Buttons.Start) && buttonCheck2 == true) { buttonCheck2 = false; } //fox warning counter update if (GameUI.gameInterface.instance.foxWarning.visible == true) { GameUI.gameInterface.instance.foxWarningCounter ++; } if (isPaused != true) { endOfDay = false; if (winLoss.checkVictory(player.money, days) == true) { //you win do whatever VictoryLossScreen.instance.enableKeypress = true; VictoryLossScreen.instance.enableKeyPress(); VictoryLossScreen.instance.determineWinLossInfo(winLoss.checkVictory(player.money, days)); Game1.instance.setGameState(Game1.GameState.winloss); isPaused = true; initializeWorld(); player.InitializeEconomic(); } else if (myCharacter.hitPoints <= 0 || player.money < 0)// for debugging, money<0 { //lose VictoryLossScreen.instance.enableKeypress = true; VictoryLossScreen.instance.enableKeyPress(); VictoryLossScreen.instance.determineWinLossInfo(false); Game1.instance.setGameState(Game1.GameState.winloss); isPaused = true; initializeWorld(); player.InitializeEconomic(); } //updates time of day dayTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //runs at the end of day if (dayTime >= endDay) { if (Chicken.AudioManager.instance.sFXOn == true && isPaused != true) { Chicken.AudioManager.instance.endDaySound.Play(); } dayTime = 0; if (Game1.instance.tutorial == true) { days = 0; Game1.instance.tutorial = false; } else { days++; } endOfDay = true; //tutorial = false;//after the first day, turn tutorial tip boxes off player.feed(numChic, numRooster); //take upkeep cost out at end of day roosterQueue = numRooster; chickenQueue = numChic; myFox.FoxReset(); player.money += eggCount * player.eggSellEnd; eggCount = 0; numEgg = 0; isPaused = true; timedGoalCurrent++; //open up menu; EndDaySummary.instance.setSummaryState(EndDaySummary.SummaryState.endDaySummary); gameInterface.instance.summaryPanel.updateSummary(); gameInterface.instance.summaryPanel.visible = true; //end of day summary becomes visible inGameMenu.instance.updateEggPrice(player.eggSellEnd); //inGameMenu.instance.visible = true; } //camera always looking at character cameraLookAt = myCharacter.position; //camera position follows character movement cameraPosition.X = myCharacter.position.X - camRearOffset * (float)Math.Sin(myCharacter.rotation); cameraPosition.Z = myCharacter.position.Z - camRearOffset * (float)Math.Cos(myCharacter.rotation); //get input from Xbox controller for one player //GamePadState gamePadState = GamePad.GetState(PlayerIndex.One); //zoom camera position with Xbox controller if (camRearOffset >= minCamOffset) { if (camRearOffset <= maxCamOffset) { camRearOffset += gamePadState.ThumbSticks.Right.X * 10f; } else { camRearOffset = maxCamOffset; } } else { camRearOffset = minCamOffset; } cameraPosition.Y = camHeightOffset; //adjust camera height if (camHeightOffset <= maxCamHeight) { if (camHeightOffset >= minCamHeight) { camHeightOffset += gamePadState.ThumbSticks.Right.Y * 10f; } else { camHeightOffset = minCamHeight; } } else { camHeightOffset = maxCamHeight; } //rotate camera position with keyboard input //KeyboardState keyBoardState = Keyboard.GetState(); //rotate camera position with keyboard if (keyBoardState.IsKeyDown(Keys.W)) { if (camHeightOffset <= maxCamHeight) { //move camera higher camHeightOffset += 10; } else { //set camera height to maximum camHeightOffset = maxCamHeight; } } if (keyBoardState.IsKeyDown(Keys.S)) { if (camHeightOffset >= minCamHeight) { //move camera lower camHeightOffset -= 10; } else { //set camera height to minimum camHeightOffset = minCamHeight; } } if (keyBoardState.IsKeyDown(Keys.A)) { if (camRearOffset <= maxCamOffset) { //zoom out camRearOffset += 10; } else { camRearOffset = maxCamOffset; } } if (keyBoardState.IsKeyDown(Keys.D)) { if (camRearOffset >= minCamOffset) { //zoom in camRearOffset -= 10; } else { camRearOffset = minCamOffset; } } //updates each chicken for (int i = 0; i < numChic - chickenQueue; i++) { chickenList[i].update(gameTime, numRooster, ref numEgg); } // update each rooster for (int i = 0; i < numRooster - roosterQueue; i++) { roosterList[i].update(gameTime, myCharacter.position, ref myCharacter.hitPoints); } //updates each egg for (int i = 0; i < numEgg; i++) { eggList[i].update(gameTime); //checks to see if egg hits character if (Vector3.Distance(eggList[i].position, myCharacter.position) < 100) { if (Chicken.AudioManager.instance.sFXOn == true && isPaused != true) { Chicken.AudioManager.instance.itemCollectSound.Play(); } eggList[i] = null; eggCount++; player.eggsCollected++; decrementEgg(i); decrementEggShadow(i); numEgg--; } //checks to see if egg hits the ground else if (eggList[i].position.Y <= 185) { if (Chicken.AudioManager.instance.sFXOn == true && isPaused != true) { Chicken.AudioManager.instance.eggCrackSound.Play(); } addBrokenEgg(eggList[i].position); eggList[i] = null; //makes egg disappear decrementEgg(i); numEgg--; } } //chicken queue add chickens if (chickenQueue > 0) { //chicken timer, add chicken every so often chickenTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //adds chicken every few seconds until chickens reach max number //or until the number of chickens owned is reached if (chickenTime > chicQueueTime && numChic - chickenQueue < maxChicken) { if (Chicken.AudioManager.instance.sFXOn == true && isPaused != true) { Chicken.AudioManager.instance.chickenSpawnSound.Play(); } addChicken(); chickenTime = 0; chickenQueue--; } } //rooster queue add roosters if (roosterQueue > 0) { //rooster timer, add rooster every so often roosterTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //adds rooster every 10 seconds until chickens reach max number if (roosterTime > roostQueueTime && numRooster - roosterQueue < maxRooster) { if (Chicken.AudioManager.instance.sFXOn == true && isPaused != true) { Chicken.AudioManager.instance.roosterSpawnSound.Play(0.5f, 0f, 0f); } addRooster(); roosterTime = 0; roosterQueue--; } } //add egg to Egg Queue if Chicken lays egg for (int i = 0; i < numChic - chickenQueue; i++) { if (chickenList[i].eggLaid == true) { addEgg(chickenList[i].position); if (Chicken.AudioManager.instance.sFXOn == true && isPaused != true) { Chicken.AudioManager.instance.chickenEggLaySound.Play(); } //addEggShadow(eggList[i].position); } } //update broken egg for (int i = 0; i < numBrokeEgg; i++) { brokenEggList[i].update(gameTime); } myCharacter.update(gameTime, brokenEggList, numBrokeEgg, bootsEquipped, ref cameraPosition, ref cameraLookAt, ref cameraViewMatrix, player, ref eggCount); //update fox myFox.update(gameTime, ref chickenList, ref roosterList, ref numRooster, ref numChic, myCharacter.position, roosterQueue, chickenQueue, player); //broken egg remove if (numBrokeEgg > 0) { brokenEggTime += (float)gameTime.ElapsedGameTime.TotalSeconds; } if (brokenEggTime >= brokenEggDisappear) { decrementBrokenEgg(0); brokenEggTime = 0; } } else { //display "PAUSED" on the screen } //update boots bootTime += (float)gameTime.ElapsedGameTime.TotalSeconds; equippedTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //add new boots if (bootTime >= bootWaitTime && bootPresent == false) { // audio play when boots spawn addBoots(); bootPresent = true; bootsEquipped = false; } //if boots have been on too long, remove them if (equippedTime >= maxEquipTime && bootsEquipped == true) { gameInterface.instance.bootIsEquipped = false; bootsEquipped = false; bootPresent = false; bootTime = 0.0f; } for (int i = 0; i < numBoots; i++) { //delete boots //checks to see if character picks up boots if (Vector3.Distance(myBootList[i].position, myCharacter.position) < 200) { // audio play when boots are picked up Chicken.AudioManager.instance.itemCollectSound.Play(); player.money += 5; //monetary reward for picking up the boots gameInterface.instance.bootIsEquipped = true; myBootList[i] = null; bootsEquipped = true; deleteBoots(i); numBoots--; //bootTime = 0.0f; equippedTime = 0.0f; } //checks to see if boots have been out too long else if (bootTime >= bootDeleteTime && bootPresent == true) { myBootList[i] = null; deleteBoots(i); bootTime = 0.0f; numBoots--; bootPresent = false; } } // base.Update(gameTime); }
private void UpdateGamePad() { GamePadState oldState = sGamePadState; sGamePadState = GamePad.GetState(PlayerIndex.One); Buttons[] buttons = sGamePadInputState.Keys.ToArray<Buttons>(); foreach (Buttons button in buttons) { InputState state = new InputState(); state.Down = sGamePadState.IsButtonDown(button); state.Pressed = (sGamePadState.IsButtonDown(button) && oldState.IsButtonUp(button)); state.Released = (sGamePadState.IsButtonUp(button) && oldState.IsButtonDown(button)); sGamePadInputState[button] = state; } }
public override void Update(GameTime gameTime) { base.Update(gameTime); // Fade effect for highlighed menu button if (isFading) { cSelected.A -= 3; if (cSelected.A == 0) isFading = false; } else { cSelected.A += 3; if (cSelected.A == 255) isFading = true; } newKeyState = Keyboard.GetState(); newPadState = GamePad.GetState(PlayerIndex.One); if((newKeyState.IsKeyUp(Keys.Enter) && oldKeyState.IsKeyDown(Keys.Enter)) || (newPadState.IsButtonUp(Buttons.A) && oldPadState.IsButtonDown(Buttons.A))) { if (isIn) { sfxConfirm.Play(); Back(); } else { isIn = true; } } oldKeyState = newKeyState; oldPadState = newPadState; }
public bool KeyReleased(Buttons button) { if (button == (Buttons)(-1)) return false; CurrentPadState = GamePad.GetState(PlayerIndex.One, GamePadDeadZone.Circular); bool result; result = CurrentPadState.IsButtonUp(button) && LastPadState.IsButtonDown(button); return result; }
/// <summary> /// Allows the game to run logic. /// </summary> protected override void Update(GameTime gameTime) { lastKeyboardState = currentKeyboardState; lastGamePadState = currentGamePadState; currentKeyboardState = Keyboard.GetState(); currentGamePadState = GamePad.GetState(PlayerIndex.One); if (ship.thrustAmount > 1.5f) currentflame = flame1; else if (ship.thrustAmount > 1.0f) currentflame = flame2; else if (ship.thrustAmount > 0.5f) currentflame = flame3; #region If State = New Game if (_gameState == State.NewGame) { if (currentKeyboardState.IsKeyUp(Keys.Enter) && lastKeyboardState.IsKeyDown(Keys.Enter)) { _gameState = State.Playing; return; } } if (_gameState == State.Gameover) { if (currentKeyboardState.IsKeyUp(Keys.Enter) && lastKeyboardState.IsKeyDown(Keys.Enter)) { timeLeft = TimeSpan.FromSeconds(60); man.Model = manStanding; camera.DesiredPositionOffset = new Vector3(0.0f, 2000.0f, 3500.0f); gameOver = false; _gameState = State.Playing; ship.Reset(); camera.Reset(); lives = 3; _objects.Clear(); SpawnObjects(); NewManPos(); return; } if (currentKeyboardState.IsKeyUp(Keys.Escape) && lastKeyboardState.IsKeyDown(Keys.Escape)) { _gameState = State.Credits; } return; } #endregion If State = New Game #region If State = Paused if (_gameState == State.Paused) { if (currentKeyboardState.IsKeyUp(Keys.P) && lastKeyboardState.IsKeyDown(Keys.P)) _gameState = State.Playing; return; } #endregion If State = Paused #region if state = playing if (_gameState == State.Playing) { if (lastKeyboardState.IsKeyUp(Keys.I) && currentKeyboardState.IsKeyDown(Keys.I)) ship.inverted = !ship.inverted; timeLeft -= gameTime.ElapsedGameTime; controlTimer -= gameTime.ElapsedGameTime; if (timeLeft.TotalMilliseconds <= 0) { gameOver = true; } if (currentKeyboardState.IsKeyDown(Keys.G)) gameOver = true; if (currentKeyboardState.IsKeyUp(Keys.P) && lastKeyboardState.IsKeyDown(Keys.P)) _gameState = State.Paused; if (currentKeyboardState.IsKeyUp(Keys.Enter) && lastKeyboardState.IsKeyDown(Keys.Enter)) _gameState = State.Paused; if (gameOver) { UpdateCameraChaseTarget(); camera.Reset(); camera.DesiredPositionOffset = new Vector3(0.0f, 40000.0f, 70000.0f); if (man.World.Translation.Z + (man.Width / 2) <= _buildings[rI].World.Translation.Z + (_buildings[rI].Width / 2)) { man.Model = manRunning; man.World *= Matrix.CreateTranslation(0.0f, 0.0f, 50.0f); } else if (man.World.Translation.Y > 0) { man.Model = manFalling; man.World *= Matrix.CreateTranslation(0.0f, -100.0f, 0.0f); } else _gameState = State.Gameover; base.Update(gameTime); return; } if ((currentKeyboardState.IsKeyDown(Keys.F1) && lastKeyboardState.IsKeyUp(Keys.F1)) || (currentGamePadState.IsButtonDown(Buttons.Back) && lastGamePadState.IsButtonUp(Buttons.Back))) { showCollisions = !showCollisions; } // Exit when the Escape key or Back button is pressed if (currentKeyboardState.IsKeyDown(Keys.Escape) || currentGamePadState.IsButtonDown(Buttons.Start)) { Exit(); } bool touchTopLeft = currentMouseState.LeftButton == ButtonState.Pressed && lastMousState.LeftButton != ButtonState.Pressed && currentMouseState.X < GraphicsDevice.Viewport.Width / 10 && currentMouseState.Y < GraphicsDevice.Viewport.Height / 10; if (lastKeyboardState.IsKeyUp(Keys.E) && (currentKeyboardState.IsKeyDown(Keys.E))) NewManPos(); // Reset the ship on R key or right thumb stick clicked if (currentKeyboardState.IsKeyDown(Keys.R)) { ship.Reset(); camera.Reset(); } // Update the ship ship.Update(gameTime); // Update the camera to chase the new target UpdateCameraChaseTarget(); // Update the business man's objects UpdateBusObjects(); // The chase camera's update behavior is the springs camera.Update(gameTime); if (_hudTextStuff.Count > 0) { for (int i = _hudTextStuff.Count - 1; i >= 0; i--) { _hudTextStuff[i].Update(gameTime); if (_hudTextStuff[i].DoneDrawing) _hudTextStuff.RemoveAt(i); } } foreach (Buildings check in _buildings) { int lol; if (check == _buildings[rI]) lol = 1; check.UpdateCollisions(); if (ship.CheckCollisionWith(check)) { _hudTextStuff.Add(new HudText((Content.Load<Texture2D>("Textures/Hud/crashed")), TimeSpan.FromSeconds(3), new Vector2(400, 300))); lives--; if (lives <= 0) gameOver = true; ship.Reset(); } } if (ship.CheckCollisionWith(man)) if (_objects.Count == 0) { score += 100; timeLeft += TimeSpan.FromSeconds(40); Console.WriteLine("New Score : " + score); // Spawn the objects again at NEW random locations // Make a new Business man at a new random location SpawnObjects(); NewManPos(); } skyBox.World = Matrix.CreateTranslation(camera.Position - new Vector3(0.0f, 100.0f, 0.0f)); base.Update(gameTime); } #endregion if state = playing if (_gameState == State.Credits) { creditTime -= gameTime.ElapsedGameTime; if (creditTime.TotalSeconds <= 0) Exit(); } }
public void HandleInput(GamePadState gamePad) { if (this.Dead == false) { switch (currentState) { case CharacterState.IDLE: this.lastPosition = position; if (gamePad.IsButtonDown(Buttons.DPadLeft)) { this.currentState = CharacterState.MOVELEFT; this.lastState = currentState; } if (gamePad.IsButtonDown(Buttons.DPadRight)) { this.currentState = CharacterState.MOVERIGHT; this.lastState = currentState; } if (gamePad.IsButtonDown(Buttons.DPadUp)) { this.currentState = CharacterState.MOVEUP; } if (gamePad.IsButtonDown(Buttons.DPadDown)) { this.currentState = CharacterState.MOVEDOWN; } if (gamePad.IsButtonDown(Buttons.A)) { this.velocity = new Vector2(0, jumpHeight); this.currentState = CharacterState.JUMP; if (SideScrollGame.main.IsNetwork) { if (this.currentState == CharacterState.JUMP) { NetOutgoingMessage outMsg = SideScrollGame.main.client.CreateMessage(); outMsg.Write((byte)PacketTypes.UPDATEVELOCITY); outMsg.Write((byte)this.currentState); outMsg.Write((byte)this.lastState); outMsg.Write((float)this.lastPosition.X); outMsg.Write((float)this.lastPosition.Y); outMsg.Write((float)this.velocity.X); outMsg.Write((float)this.velocity.Y); SideScrollGame.main.client.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered); } } } if (gamePad.IsButtonDown(Buttons.X)) { this.currentState = CharacterState.SHOOT; } break; case CharacterState.MOVERIGHT: if (gamePad.IsButtonUp(Buttons.DPadRight)) { this.lastState = currentState; this.currentState = CharacterState.IDLE; } else { this.lastPosition = position; if (gamePad.IsButtonDown(Buttons.X)) { this.currentState = CharacterState.SHOOT; } if (gamePad.IsButtonDown(Buttons.A)) { this.velocity = new Vector2(jumpDistance, jumpHeight); this.currentState = CharacterState.JUMP; if (SideScrollGame.main.IsNetwork) { if (this.currentState == CharacterState.JUMP) { NetOutgoingMessage outMsg = SideScrollGame.main.client.CreateMessage(); outMsg.Write((byte)PacketTypes.UPDATEVELOCITY); outMsg.Write((byte)this.currentState); outMsg.Write((byte)this.lastState); outMsg.Write((float)this.lastPosition.X); outMsg.Write((float)this.lastPosition.Y); outMsg.Write((float)this.velocity.X); outMsg.Write((float)this.velocity.Y); SideScrollGame.main.client.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered); } } } if (gamePad.IsButtonDown(Buttons.RightTrigger)) { this.currentState = CharacterState.BOOST; } } break; case CharacterState.MOVELEFT: if (gamePad.IsButtonUp(Buttons.DPadLeft)) { this.lastState = currentState; this.currentState = CharacterState.IDLE; } else { this.lastPosition = position; if (gamePad.IsButtonDown(Buttons.X)) { this.currentState = CharacterState.SHOOT; } if (gamePad.IsButtonDown(Buttons.A)) { this.velocity = new Vector2(jumpDistance, jumpHeight); this.currentState = CharacterState.JUMP; if (SideScrollGame.main.IsNetwork) { if (this.currentState == CharacterState.JUMP) { NetOutgoingMessage outMsg = SideScrollGame.main.client.CreateMessage(); outMsg.Write((byte)PacketTypes.UPDATEVELOCITY); outMsg.Write((byte)this.currentState); outMsg.Write((byte)this.lastState); outMsg.Write((float)this.lastPosition.X); outMsg.Write((float)this.lastPosition.Y); outMsg.Write((float)this.velocity.X); outMsg.Write((float)this.velocity.Y); SideScrollGame.main.client.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered); } } } if (gamePad.IsButtonDown(Buttons.RightTrigger)) { this.currentState = CharacterState.BOOST; } } break; case CharacterState.MOVEUP: if (gamePad.IsButtonUp(Buttons.DPadUp)) { this.currentState = CharacterState.IDLE; } break; case CharacterState.MOVEDOWN: if (gamePad.IsButtonUp(Buttons.DPadDown)) { this.currentState = CharacterState.IDLE; } break; case CharacterState.SHOOT: if (gamePad.IsButtonUp(Buttons.X)) { this.currentState = CharacterState.IDLE; } break; case CharacterState.BOOST: if (gamePad.IsButtonUp(Buttons.RightTrigger)) { this.currentState = lastState; } else { this.lastPosition = position; if (gamePad.IsButtonDown(Buttons.A)) { this.velocity = new Vector2((jumpDistance * 2), jumpHeight); this.currentState = CharacterState.JUMP; if (SideScrollGame.main.IsNetwork) { if (this.currentState == CharacterState.JUMP) { NetOutgoingMessage outMsg = SideScrollGame.main.client.CreateMessage(); outMsg.Write((byte)PacketTypes.UPDATEVELOCITY); outMsg.Write((byte)this.currentState); outMsg.Write((byte)this.lastState); outMsg.Write((float)this.lastPosition.X); outMsg.Write((float)this.lastPosition.Y); outMsg.Write((float)this.velocity.X); outMsg.Write((float)this.velocity.Y); SideScrollGame.main.client.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered); } } } } break; } } }
/// <summary> /// Handles the input and movement of the character. /// </summary> /// <param name="dt">Time since last frame in simulation seconds.</param> /// <param name="previousKeyboardInput">The last frame's keyboard state.</param> /// <param name="keyboardInput">The current frame's keyboard state.</param> /// <param name="previousGamePadInput">The last frame's gamepad state.</param> /// <param name="gamePadInput">The current frame's keyboard state.</param> public void Update(float dt, KeyboardState previousKeyboardInput, KeyboardState keyboardInput, GamePadState previousGamePadInput, GamePadState gamePadInput) { if (IsActive) { //Note that the character controller's update method is not called here; this is because it is handled within its owning space. //This method's job is simply to tell the character to move around. CameraControlScheme.Update(dt); Vector2 totalMovement = Vector2.Zero; #if XBOX360 totalMovement += new Vector2(gamePadInput.ThumbSticks.Left.X, gamePadInput.ThumbSticks.Left.Y); CharacterController.HorizontalMotionConstraint.SpeedScale = Math.Min(totalMovement.Length(), 1); //Don't trust the game pad to output perfectly normalized values. CharacterController.HorizontalMotionConstraint.MovementDirection = totalMovement; CharacterController.StanceManager.DesiredStance = gamePadInput.IsButtonDown(Buttons.RightStick) ? Stance.Crouching : Stance.Standing; //Jumping if (previousGamePadInput.IsButtonUp(Buttons.LeftStick) && gamePadInput.IsButtonDown(Buttons.LeftStick)) { CharacterController.Jump(); } #else //Collect the movement impulses. if (keyboardInput.IsKeyDown(Keys.E)) { totalMovement += new Vector2(0, 1); } if (keyboardInput.IsKeyDown(Keys.D)) { totalMovement += new Vector2(0, -1); } if (keyboardInput.IsKeyDown(Keys.S)) { totalMovement += new Vector2(-1, 0); } if (keyboardInput.IsKeyDown(Keys.F)) { totalMovement += new Vector2(1, 0); } if (totalMovement == Vector2.Zero) CharacterController.HorizontalMotionConstraint.MovementDirection = Vector2.Zero; else CharacterController.HorizontalMotionConstraint.MovementDirection = Vector2.Normalize(totalMovement); CharacterController.StanceManager.DesiredStance = keyboardInput.IsKeyDown(Keys.Z) ? Stance.Crouching : Stance.Standing; //Jumping if (previousKeyboardInput.IsKeyUp(Keys.A) && keyboardInput.IsKeyDown(Keys.A)) { CharacterController.Jump(); } #endif CharacterController.ViewDirection = Camera.WorldMatrix.Forward; } }
protected void FlashToggle(KeyboardState currentKeyboardState, GamePadState currentGamePadState) { if ((previousKeyboardState.IsKeyDown(Keys.F) && currentKeyboardState.IsKeyUp(Keys.F)) || (previousGamePadState.IsButtonDown(Buttons.LeftShoulder) && currentGamePadState.IsButtonUp(Buttons.LeftShoulder))) { flash = !flash; // toggle Fog on/off if (flash) { effect.Parameters["light"].StructureMembers["radius"].SetValue(12.0f); } else { effect.Parameters["light"].StructureMembers["radius"].SetValue(0.1f); } } }