예제 #1
1
        protected override void Update(TimeSpan gameTime)
        {
            input = WaveServices.Input;

            if (input.KeyboardState.IsConnected)
            {
                keyboardState = input.KeyboardState;

                if (keyboardState.W == ButtonState.Pressed)
                {
                    MoveCamera(ref forward);
                }
                if (keyboardState.S == ButtonState.Pressed)
                {
                    MoveCamera(ref back);
                }
                if (keyboardState.A == ButtonState.Pressed)
                {
                    MoveCamera(ref left);
                }
                if (keyboardState.D == ButtonState.Pressed)
                {
                    MoveCamera(ref right);
                }
            }
            var rotationMatrix = (Matrix.CreateRotationX(MathHelper.ToRadians(45.0f)) * Matrix.CreateRotationY(MathHelper.ToRadians(30.0f)));
            Vector3 transformedReference = Vector3.Transform(Vector3.Down, rotationMatrix);
            Vector3 cameraLookat = Camera.Position + transformedReference;
            var width = WaveServices.Platform.ScreenWidth / 24;
            var height = WaveServices.Platform.ScreenHeight / 24;

            //camera.Projection = Matrix.CreateOrthographic(width, height, camera.NearPlane, camera.FarPlane);
            Camera.LookAt = cameraLookat;
        }
예제 #2
0
        /// <summary>
        /// Allows this instance to execute custom logic during its <c>Update</c>.
        /// </summary>
        /// <param name="gameTime">The game time.</param>
        /// <remarks>
        /// This method will not be executed if it are not <c>Active</c>.
        /// </remarks>
        protected override void Update(TimeSpan gameTime)
        {
            inputService = WaveServices.Input;

            if (inputService.KeyboardState.IsConnected)
            {
                // Key F1
                if (inputService.KeyboardState.F1 == ButtonState.Pressed &&
                    beforeKeyboardState.F1 != ButtonState.Pressed)
                {
                    this.diagnostics = !this.diagnostics;
                    WaveServices.ScreenContextManager.SetDiagnosticsActive(this.diagnostics);
                }

                // Key F3
                if (inputService.KeyboardState.F3 == ButtonState.Pressed &&
                    beforeKeyboardState.F3 != ButtonState.Pressed)
                {
                    this.debugLines = !this.debugLines;
                    this.Scene.RenderManager.DebugLines = this.debugLines;
                }
            }

            beforeKeyboardState = inputService.KeyboardState;
        }
예제 #3
0
 public Keyboard()
 {
     var directInput = new DirectInput();
     mKeyboard = new SlimDX.DirectInput.Keyboard(directInput);
     mKeyboard.Acquire();
     mState = new KeyboardState();
 }
예제 #4
0
        //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;
        }
        /// <summary>
        /// Update Method
        /// </summary>
        /// <param name="gameTime"></param>
        protected override void Update(TimeSpan gameTime)
        {
            this.input = WaveServices.Input;

            // if (this.input.KeyboardState.IsConnected)
            {
                this.keyboardState = this.input.KeyboardState;

                if (revoluteJoint != null)
                {
                    // A, D, S Keyboard Control (left, right, stop motor)
                    if (this.keyboardState.A == ButtonState.Pressed)
                    {
                        if (revoluteJoint.MotorSpeed + motorSpeed <= maxSpeed)
                        {
                            revoluteJoint.MotorSpeed += motorSpeed;
                        }
                    }
                    else if (this.keyboardState.D == ButtonState.Pressed)
                    {
                        if (revoluteJoint.MotorSpeed - motorSpeed >= -maxSpeed)
                        {
                            revoluteJoint.MotorSpeed -= motorSpeed;
                        }
                    }
                    else if (this.keyboardState.S == ButtonState.Pressed)
                    {
                        revoluteJoint.MotorSpeed = 0.0f;
                    }
                }
            }
        }
예제 #6
0
        public void HandleInput(MouseState mouseState, KeyboardState keyboardState)
        {
            KeyboardState = keyboardState;

            if (MouseOverRenderArea && mouseState.LeftButton == ButtonState.Pressed)
            {
                if (!MouseDragging)
                {
                    MouseDragging = true;
                    MousePreviousPosition = new Vector2(mouseState.X, mouseState.Y);
                }

                var mouseNewCoords = new Vector2(mouseState.X, mouseState.Y);

                MouseDelta.X = mouseNewCoords.X - MousePreviousPosition.X;
                MouseDelta.Y = mouseNewCoords.Y - MousePreviousPosition.Y;

                MousePreviousPosition = mouseNewCoords;
            }

            if (!MouseOverRenderArea || mouseState.LeftButton == ButtonState.Released)
            {
                MouseDragging = false;
            }
        }
예제 #7
0
 public Lab1State()
 {
     prevState = Keyboard.GetState();
     layer = new TPLayer(this.layers);
     layer.AddEntity(s);
     s.Position = new Vector2(200, 200);
 }
        public KeyboardInputProcessor()
        {
            _previousKeyboardState = new KeyboardState();
            _currentKeyboardState = new KeyboardState();

            KeyDictionary = new KeyDictionary();
        }
        public void Update(KeyboardState keyboardState)
        {
            _previousKeyboardState = _currentKeyboardState;
            _currentKeyboardState = keyboardState;

            KeyDictionary.Update(keyboardState);
        }
예제 #10
0
파일: Input.cs 프로젝트: spdemille/Baffled
            public static void Update(GameTime dt)
            {
                JoyPrev = JoyState;
                JoyState = GamePad.GetState(PlayerIndex.One);

                KeyPrev = KeyState;
                KeyState = Keyboard.GetState(PlayerIndex.One);
            }
예제 #11
0
 internal KeyboardMapBuilder(IVirtualKeyboard virtualKeyboard)
 {
     _virtualKeyboard = virtualKeyboard;
     _keyboard = _virtualKeyboard.KeyboardState;
     _lookedForOem1ModifierVirtualKey = _keyboard.Oem1ModifierVirtualKey.HasValue;
     _lookedForOem2ModifierVirtualKey = _keyboard.Oem2ModifierVirtualKey.HasValue;
     _possibleModifierVirtualKey = new Lazy<List<uint>>(GetPossibleVirtualKeyModifiers);
 }
예제 #12
0
        public override void Update(GameTime gameTime)
        {
            keyOldState = keyNewState;
            keyNewState = Keyboard.GetState();

            if ((Game.IsActive && (keyNewState.GetPressedKeys().Length > 0 || keyOldState.GetPressedKeys().Length > 0) && KeyEvent != null))
                KeyEvent(keyNewState, keyOldState);
        }
예제 #13
0
        /// <summary>
        /// Check input device without check Floor Height 
        /// </summary>
        public void Poll()
        {
            KeyState = KeyBoardDevice.GetCurrentKeyboardState();
            KeyBoardJOBs();

            MState = MouseDevice.CurrentMouseState;
            MouseJOBs();
        }
예제 #14
0
 internal Keyboard(DKeyboard keyboard)
 {
     System.Diagnostics.Debug.Assert(keyboard != null);
     _dKeyboard = keyboard;
     _inputState = KeyboardInput.CreateEmpty();
     _lastPressedKeys = new List<Key>();
     (_timer = new GameTimer()).Start();
     _currentDirectInputState = new KeyboardState();
 }
예제 #15
0
파일: LuaInput.cs 프로젝트: rumkex/Game
 public void Poll()
 {
     oldState = state;
     state = Keyboard.GetState();
     foreach (var trigger in triggers.Where(trigger => oldState[trigger.Key] != state[trigger.Key]))
     {
         trigger.Value.Call(state[trigger.Key]);
     }
 }
예제 #16
0
 public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
 {
     base.Update(gameTime);
     if (Keyboard.GetState().IsKeyDown(Keys.X) && prevState.IsKeyUp(Keys.X))
     {
         TPEngine.Get().State.PopState();
     }
     prevState = Keyboard.GetState();
 }
예제 #17
0
        protected override void Update(TimeSpan gameTime)
        {
            this.input = WaveServices.Input;
            if (this.input.KeyboardState.IsConnected)
            {
                this.keyboardState = this.input.KeyboardState;

                RigidBody2D rigidBody = Owner.FindComponent<RigidBody2D>();
                if (rigidBody != null)
                {
                    // W, A, S, D applies Directional Linear Impulses
                    Vector2 result = Vector2.Zero;
                    if (keyboardState.A == ButtonState.Pressed)
                    {
                        result += leftDirection;
                    }
                    if (keyboardState.D == ButtonState.Pressed)
                    {
                        result -= leftDirection;
                    }
                    if (keyboardState.W == ButtonState.Pressed)
                    {
                        result += topDirection;
                    }
                    if (keyboardState.S == ButtonState.Pressed)
                    {
                        result -= topDirection;
                    }
                 
                    // Apply Linear Impulse
                    if (result != Vector2.Zero)
                    {
                        rigidBody.ApplyLinearImpulse(result);
                    }

                    // Left and Right arrow applies angular impulse
                    if (keyboardState.Left == ButtonState.Pressed)
                    {
                        rigidBody.ApplyAngularImpulse(-angularImpulse);
                    }
                    else if (keyboardState.Right == ButtonState.Pressed)
                    {
                        rigidBody.ApplyAngularImpulse(angularImpulse);
                    }

                    // J and K applies Torque
                    if (keyboardState.J == ButtonState.Pressed)
                    {
                        rigidBody.ApplyTorque(torque);
                    }
                    else if (keyboardState.K == ButtonState.Pressed)
                    {
                        rigidBody.ApplyTorque(-torque);
                    }
                }
            }
        }
예제 #18
0
        /// <summary>
        /// Hlavní konstruktor.
        /// </summary>
        /// <param name="window">Herní okno.</param>
        public Keyboard(GlibWindow window)
            : base(window)
        {
            keyboard = new KeyboardDirect(Input);
            keyboard.Properties.BufferSize = 128;
            keyboard.Acquire();

            state = new KeyboardState();
        }
예제 #19
0
 public void update()
 {
     oldStateG = currentStateG;
     currentStateG = GamePad.GetState(PlayerIndex.One);
     oldStateK = currentStateK;
     currentStateK = Keyboard.GetState();
     oldStateM = currentStateM;
     currentStateM = Mouse.GetState();
 }
예제 #20
0
 public static void PressAnyKey()
 {
     initializeKeyboard();
     while ((keyState = keyDevice.GetCurrentKeyboardState()) == null)
     {
         Application.DoEvents();
     }
     FreeKeyboard();
 }
예제 #21
0
        /// <summary>
        /// Check input device with check Floor Height 
        /// </summary>
        /// <param name="vFloor"></param>
        public void Poll(ref Microsoft.DirectX.Direct3D.CustomVertex.PositionTextured[] vFloor)
        {
            _vFloor = vFloor;
            KeyState = KeyBoardDevice.GetCurrentKeyboardState();
            KeyBoardJOBs();

            MState = MouseDevice.CurrentMouseState;
            MouseJOBs();
        }
예제 #22
0
        void InputKeyBoard_KeyEvent(KeyboardState keyNewState, KeyboardState keyOldState)
        {
            if (keyNewState.IsKeyDown(Keys.Escape) && keyOldState.IsKeyUp(Keys.Escape)) game.Exit();

            if (keyNewState.IsKeyDown(Keys.Up) && keyOldState.IsKeyUp(Keys.Up)) game.Window.Title = "Up";
            if (keyNewState.IsKeyDown(Keys.Down) && keyOldState.IsKeyUp(Keys.Down)) game.Window.Title = "Down";
            if (keyNewState.IsKeyDown(Keys.Left) && keyOldState.IsKeyUp(Keys.Left)) game.Window.Title = "Left";
            if (keyNewState.IsKeyDown(Keys.Right) && keyOldState.IsKeyUp(Keys.Right)) game.Window.Title = "Right";
        }
예제 #23
0
 public InputSystem()
 {
     CurrentKeyboardState = new KeyboardState();
     PreviousKeyboardState = new KeyboardState();
     CurrentGamepadState = new GamePadState();
     PreviousGamepadState = new GamePadState();
     CurrentMouseState = new MouseState();
     PreviousMouseState = new MouseState();
 }
예제 #24
0
 /// <summary>
 /// Updates the DIKeyboard state.
 /// </summary>
 public override void Update()
 {
     try {
         _keys = _device.GetCurrentKeyboardState();
     }
     catch {
         // Lost access to keyboard.
         _acquireDevice();
     }
 }
        public void Update(KeyboardState keyboardState)
        {
            var array = _keys.Keys.ToArray();

            for (var i = 0; i < array.Length; i++)
            {
                var key = array[i];
                _keys[key] = keyboardState[key];
            }
        }
예제 #26
0
 public KeyboardState GetState()
 {
     lock (this.UpdateLock)
       {
     KeyboardState local_0 = new KeyboardState();
     foreach (KeyboardState item_0 in this.keyboards)
       local_0.MergeBits(item_0);
     return local_0;
       }
 }
예제 #27
0
 public static void Differentiate(KeyboardState from, KeyboardState to,
     out bool[] pressedKeys, out bool[] releasedKeys)
 {
     pressedKeys = new bool[NumKeys];
     releasedKeys = new bool[NumKeys];
     for (int i = 0; i < NumKeys; ++i)
     {
         pressedKeys[i] = !from.KeyPressed[i] && to.KeyPressed[i];
         releasedKeys[i] = from.KeyPressed[i] && !to.KeyPressed[i];
     }
 }
예제 #28
0
        /// <summary>
        /// Creates string name for the key code and key modifiers
        /// </summary>        
        private string GetKeyName(Keys keys, KeyboardState keyboardState)
        {
            var control = String.Empty;
            var shift = String.Empty;
            if ((keyboardState & KeyboardState.Control) == KeyboardState.Control)
                control = "^";
            if ((keyboardState & KeyboardState.Shift) == KeyboardState.Shift)
                shift = "!";

            return control + shift + keys.ToString();
        }
        protected override void Update(TimeSpan gameTime)
        {
            var currentKeyboardState = this.inputService.KeyboardState;

            if (this.lastKeyboardState.IsKeyPressed(this.KeyTrigger) &&
                currentKeyboardState.IsKeyReleased(this.KeyTrigger))
            {
                this.navComponent.DoNavigation();
            }

            this.lastKeyboardState = currentKeyboardState;
        }
예제 #30
0
파일: Frm_Key.cs 프로젝트: afonsof/nes-hd
        private bool CheckInput(KeyboardState state, int index)
        {
            if (state == null)
                return false;

            if (state.PressedKeys.Count > 0)
            {
                _inputName = "Keyboard." + state.PressedKeys[0].ToString();
                return true;
            }
            return false;
        }
예제 #31
0
        // Handles all input and updates velocity accordingly
        void HandleInputAndUpdateVelocity()
        {
            // Getting new input states
            GamePadState  newGamepadState  = GamePad.GetState(PlayerIndex.One);
            KeyboardState newKeyboardState = Keyboard.GetState();

            // Handling X velocity, left/right input, dashing
            float inputVel = 0;

            if (newKeyboardState.IsKeyDown(Keys.Left) || newKeyboardState.IsKeyDown(Keys.A))
            {
                inputVel = -xAcceleration;
            }
            if (newKeyboardState.IsKeyDown(Keys.Right) || newKeyboardState.IsKeyDown(Keys.D))
            {
                inputVel = xAcceleration;
            }

            if (newGamepadState.ThumbSticks.Left.X < -0.05)
            {
                inputVel = -xAcceleration;
            }
            if (newGamepadState.ThumbSticks.Left.X > 0.05)
            {
                inputVel = xAcceleration;
            }

            if (inputVel == 0)                                  // Decelerates player when no left/right input is given-
            {
                if (XVel > 0)
                {
                    XVel -= xDeceleration;
                    if (XVel < 0)
                    {
                        XVel = 0;
                    }
                }
                if (XVel < 0)
                {
                    XVel += xDeceleration;
                    if (XVel > 0)
                    {
                        XVel = 0;
                    }
                }
                if (Math.Abs(XVel) < 0.08f)                     // Round small fractions to 0
                {
                    XVel = 0;
                }
            }
            else
            {
                XVel += inputVel;
            }

            if ((newKeyboardState.IsKeyDown(Keys.LeftShift) || newGamepadState.Triggers.Right > 0.05f) && // Dash handling
                IsOnTheGround && inputVel != 0)
            {
                XVel = MathHelper.Clamp(XVel, 1.75f * -xMaxVelocity, 1.75f * xMaxVelocity);
                millisecondsPerFrame = 30;
            }
            else
            {
                XVel = MathHelper.Clamp(XVel, -xMaxVelocity, xMaxVelocity);
                millisecondsPerFrame = 50;
            }

            // Handling Y velocity and jumping
            if ((newKeyboardState.IsKeyUp(Keys.Space) && newGamepadState.Buttons.A == ButtonState.Released && jumpCounter > minJumpVelFrames) ||
                jumpCounter > maxJumpVelFrames)
            {
                isJumping   = false;
                jumpCounter = 1;
            }
            else if (isJumping)
            {
                YVel += jumpInitialVelocity / (jumpCurveFactor * jumpCounter);      // Each additional frame jump is held gives less up velocity based on jumpCounter and jumpCurveFactor
                ++jumpCounter;
            }

            if ((newKeyboardState.IsKeyDown(Keys.Space) && oldKeyboardState.IsKeyUp(Keys.Space)) ||
                (newGamepadState.Buttons.A == ButtonState.Pressed && oldGamepadState.Buttons.A == ButtonState.Released))
            {
                if (IsOnTheGround)
                {
                    YVel      = jumpInitialVelocity;
                    isJumping = true;
                }
            }

            if (YVel != 0)                                      // Currently prevents jumping from setting YVel to 1
            {
                IsOnTheGround = false;
            }

            if (IsOnTheGround)                                  // If ground collision last update
            {
                YVel = 1;                                       // Start falling again to detect walking off ledge or slope
            }
            else
            {
                YVel += gravity;
            }

            if (YVel > terminalVelocity)
            {
                YVel = terminalVelocity;
            }

            // Shooting
            if (PulledTheTrigger == true)
            {
                PulledTheTrigger = false;
            }
            if ((newKeyboardState.IsKeyDown(Keys.RightControl) && oldKeyboardState.IsKeyUp(Keys.RightControl)) ||
                (newGamepadState.Buttons.X == ButtonState.Pressed && oldGamepadState.Buttons.X == ButtonState.Released))
            {
                PulledTheTrigger = true;
            }

            // Turn on/off diagnostic modes
            if ((newKeyboardState.IsKeyDown(Keys.D1) && oldKeyboardState.IsKeyUp(Keys.D1)) ||
                (newGamepadState.Buttons.LeftShoulder == ButtonState.Pressed && oldGamepadState.Buttons.LeftShoulder == ButtonState.Released))
            {
                ShowBoundingBoxes = !ShowBoundingBoxes;
            }

            if ((newKeyboardState.IsKeyDown(Keys.D2) && oldKeyboardState.IsKeyUp(Keys.D2)) ||
                (newGamepadState.Buttons.RightShoulder == ButtonState.Pressed && oldGamepadState.Buttons.RightShoulder == ButtonState.Released))
            {
                ShowTerrainBoxes = !ShowTerrainBoxes;
            }

            // Updating old input states
            oldGamepadState  = newGamepadState;
            oldKeyboardState = newKeyboardState;
        }
예제 #32
0
파일: Snakeplayer2.cs 프로젝트: Alejanky/PR
        private int Move()
        {
            oldState = Keyboard.GetState();
            if (oldState.IsKeyDown(Keys.W))               // hacer algo con el up stroke
            {
                if (oldState.IsKeyDown(Keys.A))
                {
                    body        = jump;
                    totalFrames = 9;
                    return(5);
                }
                else
                {
                    if (oldState.IsKeyDown(Keys.D))
                    {
                        body        = jump;
                        totalFrames = 9;
                        return(6);
                    }
                    else
                    {
                        totalFrames = 9;
                        body        = jump;
                        return(0);
                    }
                }
            }

            if (oldState.IsKeyDown(Keys.S))               // probablemente no hacer cambiio
            {
                if (oldState.IsKeyDown(Keys.A))
                {
                    totalFrames = 9;
                    body        = idle;
                    return(7);
                }
                else
                {
                    if (oldState.IsKeyDown(Keys.D))
                    {
                        totalFrames = 9;
                        body        = idle;
                        return(8);
                    }
                    else
                    {
                        totalFrames = 9;
                        body        = idle;
                        return(4);
                    }
                }
            }
            if (oldState.IsKeyDown(Keys.A))
            {
                totalFrames = 8;
                body        = run;
                return(2);
            }
            if (oldState.IsKeyDown(Keys.D))
            {
                body        = run;
                totalFrames = 8;
                return(3);
            }
            else
            {
                totalFrames = 9;
                body        = idle;
                return(4);
            }
        }
예제 #33
0
        public void Update(KeyboardState kb, TimeSpan deltaTime, Level level, SoundEffect grunt)
        {
            if (kb.IsKeyDown(Keys.Up))
            {
                velocity.Y = -speed;
            }
            if (kb.IsKeyDown(Keys.Down))
            {
                velocity.Y = speed;
            }
            if (kb.IsKeyDown(Keys.Left))
            {
                velocity.X = -speed;
            }
            if (kb.IsKeyDown(Keys.Right))
            {
                velocity.X = speed;
            }
            if (kb.IsKeyDown(Keys.Space))
            {
                if (bulletTime > fireRate)
                {
                    Shoot();
                    bulletTime = 0;
                }
            }


            //This code block handles player movement and shooting


            location.X = location.X + (int)velocity.X;
            location.Y = location.Y + (int)velocity.Y;
            //Update the players location

            velocity = velocity / dampening;
            //dampen the player's speed

            if (location.X < 0)
            {
                location.X = 0;
            }
            if (location.Y < 0)
            {
                location.Y = 0;
            }
            if (location.X > screenWidth - location.Width)
            {
                location.X = screenWidth - location.Width;
            }
            if (location.Y > screenHeight - location.Height)
            {
                location.Y = screenHeight - location.Height;
            }
            // keep the player on screen.

            playerBullet.location = location;
            //updates the location of the default bullet

            for (int i = 0; i < bullets.Count; i++)
            {
                if (bullets[i] != null)
                {
                    bullets[i].Update(deltaTime);
                }
            }
            //update the player's bullets

            // handles when player bullets hit enemies
            for (int i = 0; i < bullets.Count; i++)
            {
                for (int j = 0; j < level.Enemies.Count; j++)
                {
                    if (level.Enemies[j] != null && bullets[i] != null)
                    {
                        if (bullets[i].CheckCollision(level.Enemies[j]))
                        {
                            level.Enemies[j] = null;
                            grunt.Play();
                            bullets[i] = null;
                            combo++;
                            score += 100 * combo; // add 100 to the score each time an enemy is killed
                        }
                    }

                    /*
                     * for (int k = 0; k < level.Enemies[j].Bullets.Count; k++)
                     * {
                     *  if (level.Enemies[j].Bullets[k].CheckCollision(this))
                     *  {
                     *      System.Threading.Thread.Sleep(5);
                     *  }
                     * }
                     * */
                }
            }

            // handles when the player is hit by a bullet- reduces number of lives left
            for (int i = 0; i < level.Enemies.Count; i++)
            {
                if (level.Enemies[i] != null)
                {
                    for (int j = 0; j < level.Enemies[i].Bullets.Count; j++)
                    {
                        if (level.Enemies[i].Bullets[j] != null)
                        {
                            if (level.Enemies[i].Bullets[j].CheckCollision(this))
                            {
                                combo = 0; // reset the combo when the player is hit

                                //bullets[i] = null;  this just causes the player bullets to disappear when they're fired
                                lives--;
                            }
                        }
                    }
                }
            }

            // if lives = 0, the player is dead
            if (lives <= 0)
            {
                isDead = true;
            }

            bulletTime += deltaTime.Milliseconds; //updates bullet counter
        }
예제 #34
0
        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            KeyboardState keyboard = Keyboard.GetState();

            if (keyboard.IsKeyDown(Keys.Enter) &&
                prevKeyboardState.IsKeyUp(Keys.Enter) &&
                this.game.GetGameStatus() == Shooter.GameStatus.Simulation &&
                this.game.GetGameStatus() != Shooter.GameStatus.Sending &&
                this.game.GetGameStatus() != Shooter.GameStatus.Receive)
            {
                this.game.SetGameStatus(Shooter.GameStatus.Sending);
            }
            this.prevKeyboardState = keyboard;


            if (this.game.GetGameStatus() == Shooter.GameStatus.Sending)
            {
                if (this.game.bMapIsReady)
                {
                    //
                    // If there's input; send it to server
                    //
                    NetOutgoingMessage om = client.CreateMessage();
                    om.Write((byte)OutgoingMessageType.DataPlayerInfo);
                    om.Write(this.game.path.GetWayPoints().Count);
                    foreach (WayPoint point in this.game.path.GetWayPoints())
                    {
                        Vector3 tempPos = point.CenterPos;//this.game.gamePlayer.GetPlayerPosition();
                        float   tempOri = this.game.gamePlayer.GetPlayerOrientation();
                        om.Write(tempPos.X);
                        om.Write(tempPos.Y);
                        om.Write(tempPos.Z);
                        om.Write(tempOri);
                    }
                    client.SendMessage(om, NetDeliveryMethod.ReliableOrdered);
                }
                this.game.SetGameStatus(Shooter.GameStatus.Receive);
            }

            if (this.game.GetGameStatus() == Shooter.GameStatus.Receive ||
                this.game.GetGameStatus() == Shooter.GameStatus.MainMenu)
            {
                //read message
                NetIncomingMessage msg;
                while ((msg = client.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                    case NetIncomingMessageType.DiscoveryResponse:
                        //just connect to first server discovered
                        client.Connect(msg.SenderEndpoint);
                        playerId = (Project_Origin.Player.PlayerId)(msg.ReadInt32());
                        int mapSeed = msg.ReadInt32();
                        this.game.bMapIsReady = true;
                        this.game.BuildGameComponents(mapSeed);
                        this.game.gamePlayer.SetPlayId();
                        break;

                    case NetIncomingMessageType.Data:
                        //server sent a position update
                        IncomingMessageType imt = (IncomingMessageType)msg.ReadByte();
                        if (imt == IncomingMessageType.DataOtherPlayerInfo)
                        {
                            opponentWaypoint.Clear();
                            int wayPointCounter = msg.ReadInt32();
                            for (int i = 1; i <= wayPointCounter; ++i)
                            {
                                otherPlayerInfo.position.X  = msg.ReadFloat();
                                otherPlayerInfo.position.Y  = msg.ReadFloat();
                                otherPlayerInfo.position.Z  = msg.ReadFloat();
                                otherPlayerInfo.orientation = msg.ReadFloat();

                                Console.WriteLine("{0} {1} {2}", otherPlayerInfo.position.X, otherPlayerInfo.position.Y, otherPlayerInfo.position.Z);
                                opponentWaypoint.Add(new WayPoint(this.game.GraphicsDevice, new Vector3(otherPlayerInfo.position.X,
                                                                                                        otherPlayerInfo.position.Y,
                                                                                                        otherPlayerInfo.position.Z)));
                            }
                        }
                        this.game.gamePlayer.Path.OpponentWayPoints = opponentWaypoint;
                        this.game.SetGameStatus(Shooter.GameStatus.Start);
                        this.game.gamePlayer.StartToMove();
                        break;
                    }
                }
            }


            base.Update(gameTime);
        }
예제 #35
0
 // Ska köras i slutet av update i MainGame
 public static void UpdateEnd()
 {
     oldKeyboardState = currentKeyboardState;
     oldGamePadState  = currentGamePadState;
 }
예제 #36
0
        public void HandleInput()
        {
            KeyboardState kbState = Keyboard.GetState();
            GamePadState  gpState = GamePad.GetState(PlayerIndex.One);

            Matrix rotation = Matrix.Identity;

            if (kbState.IsKeyDown(Keys.NumPad4))
            {
                rotation *= Matrix.CreateFromAxisAngle(Up, rotationSpeed);
            }
            if (kbState.IsKeyDown(Keys.NumPad6))
            {
                rotation *= Matrix.CreateFromAxisAngle(Up, -rotationSpeed);
            }
            if (kbState.IsKeyDown(Keys.NumPad8))
            {
                rotation *= Matrix.CreateFromAxisAngle(Right, -rotationSpeed);
            }
            if (kbState.IsKeyDown(Keys.NumPad2))
            {
                rotation *= Matrix.CreateFromAxisAngle(Right, rotationSpeed);
            }
            if (kbState.IsKeyDown(Keys.NumPad7))
            {
                rotation *= Matrix.CreateFromAxisAngle(Forward, -rotationSpeed);
            }
            if (kbState.IsKeyDown(Keys.NumPad9))
            {
                rotation *= Matrix.CreateFromAxisAngle(Forward, rotationSpeed);
            }

            rotation *= Matrix.CreateFromAxisAngle(Up, -rotationSpeed * gpState.ThumbSticks.Right.X);
            rotation *= Matrix.CreateFromAxisAngle(Right, -rotationSpeed * gpState.ThumbSticks.Right.Y);
            rotation *= Matrix.CreateFromAxisAngle(Forward, rotationSpeed * (-gpState.Triggers.Left + gpState.Triggers.Right));

            if (rotation != Matrix.Identity)
            {
                orientation *= rotation;
            }

            Vector3 translation = Vector3.Zero;

            if (kbState.IsKeyDown(Keys.Up))
            {
                if (kbState.IsKeyDown(Keys.LeftShift) || kbState.IsKeyDown(Keys.RightShift))
                {
                    translation += Forward * moveSpeed;
                }
                else
                {
                    translation += Up * moveSpeed;
                }
            }
            if (kbState.IsKeyDown(Keys.Down))
            {
                if (kbState.IsKeyDown(Keys.LeftShift) || kbState.IsKeyDown(Keys.RightShift))
                {
                    translation += Backward * moveSpeed;
                }
                else
                {
                    translation += Down * moveSpeed;
                }
            }
            if (kbState.IsKeyDown(Keys.Left))
            {
                translation += Left * moveSpeed;
            }
            if (kbState.IsKeyDown(Keys.Right))
            {
                translation += Right * moveSpeed;
            }

            translation += Forward * moveSpeed * gpState.ThumbSticks.Left.Y;
            translation += Right * moveSpeed * gpState.ThumbSticks.Left.X;
            if (gpState.IsButtonDown(Buttons.LeftShoulder))
            {
                translation += Down * moveSpeed;
            }
            if (gpState.IsButtonDown(Buttons.RightShoulder))
            {
                translation += Up * moveSpeed;
            }

            if (translation != Vector3.Zero)
            {
                position += translation;
            }

            if ((rotation != Matrix.Identity) || (translation != Vector3.Zero))
            {
                updateViewMatrix();
            }

            float zoom = 0;

            if (kbState.IsKeyDown(Keys.Add))
            {
                zoom -= zoomSpeed;
            }
            if (kbState.IsKeyDown(Keys.Subtract))
            {
                zoom += zoomSpeed;
            }

            if (zoom != 0)
            {
                fieldOfView += zoom;
                fieldOfView  = MathHelper.Clamp(fieldOfView, fovMin, fovMax);
                updateProjectionMatrix();
            }

            if ((rotation != Matrix.Identity) || (translation != Vector3.Zero) || (zoom != 0))
            {
                updateViewProjectionMatrix();
            }
        }
예제 #37
0
        public override void HandleInput(GamePadState gamePadState, KeyboardState keyboardState, MouseState mouseState)
        {
            if (!isSelectingKey)
            {
                if (InputHandler.WasKeyPressed(keyboardState, KeyConfig.Down, 10))
                {
                    if (!inKeyMenu)
                    {
                        optionsMenu.SelectionDown();
                    }
                    else
                    {
                        if (!isSelectingKey)
                        {
                            keyconfigMenu.SelectionDown();
                        }
                    }
                }
                if (InputHandler.WasKeyPressed(keyboardState, KeyConfig.Left, 10))
                {
                    if (!inKeyMenu)
                    {
                        switch (optionsMenu.GetSelection())
                        {
                        case 0: ScreenHandler.GameOptions.TextSpeed = ScreenHandler.GameOptions.TextSpeed > 0 ? (byte)(ScreenHandler.GameOptions.TextSpeed - 1) : (byte)2; break;

                        case 1: ScreenHandler.GameOptions.BattleScene = ScreenHandler.GameOptions.BattleScene ? false : true; break;

                        case 2: ScreenHandler.GameOptions.BattleStyle = ScreenHandler.GameOptions.BattleStyle ? false : true; break;

                        case 3: ScreenHandler.GameOptions.Sound = ScreenHandler.GameOptions.Sound ? false : true; break;
                        }
                    }
                    UpdateBaseOption(optionsMenu.GetSelection());
                }
                if (InputHandler.WasKeyPressed(keyboardState, KeyConfig.Right, 10))
                {
                    if (!inKeyMenu)
                    {
                        switch (optionsMenu.GetSelection())
                        {
                        case 0: ScreenHandler.GameOptions.TextSpeed = ScreenHandler.GameOptions.TextSpeed < 2 ? (byte)(ScreenHandler.GameOptions.TextSpeed + 1): (byte)0; break;

                        case 1: ScreenHandler.GameOptions.BattleScene = ScreenHandler.GameOptions.BattleScene ? false : true; break;

                        case 2: ScreenHandler.GameOptions.BattleStyle = ScreenHandler.GameOptions.BattleStyle ? false : true; break;

                        case 3: ScreenHandler.GameOptions.Sound = ScreenHandler.GameOptions.Sound ? false : true; break;
                        }
                        UpdateBaseOption(optionsMenu.GetSelection());
                    }
                }
                if (InputHandler.WasKeyPressed(keyboardState, KeyConfig.Up, 10))
                {
                    if (!inKeyMenu)
                    {
                        optionsMenu.SelectionUp();
                    }
                    else
                    {
                        if (!isSelectingKey)
                        {
                            keyconfigMenu.SelectionUp();
                        }
                    }
                }
                if (InputHandler.WasKeyPressed(keyboardState, KeyConfig.Cancel, 10))
                {
                    if (!inKeyMenu)
                    {
                        Close();
                    }
                    else
                    {
                        if (!isSelectingKey)
                        {
                            inKeyMenu = false;
                        }
                    }
                }
                if (InputHandler.WasKeyPressed(keyboardState, KeyConfig.Action, 10))
                {
                    if (!inKeyMenu)
                    {
                        switch (optionsMenu.GetSelection())
                        {
                        case 4: inKeyMenu = true; break;

                        case 6: ScreenHandler.GameOptions.Save(); break;

                        case 7: Close(); break;
                        }
                    }
                    else
                    {
                        if (!isSelectingKey)
                        {
                            int i = keyconfigMenu.GetSelection();
                            if (i <= keyconfigMenu.GetOptionList().Count - 3)
                            {
                                isSelectingKey = true;
                            }
                            else if (i == keyconfigMenu.GetOptionList().Count - 2)
                            {
                                KeyConfig.Save();
                            }
                            else
                            {
                                inKeyMenu = false;
                            }
                        }
                    }
                }
            }
            else
            {
                int i = keyconfigMenu.GetSelection();

                Keys[] selectedKeys = InputHandler.GetSelectedKeys(keyboardState, 10);
                if (selectedKeys.Length > 0 && !selectedKeys[0].Equals(Keys.None) && !checkIfKeyExists(selectedKeys[0]))
                {
                    KeyConfig.KeyList[i] = selectedKeys[0];
                    UpdateKeyOption(i);
                    isSelectingKey = false;
                }
            }
        }
예제 #38
0
 public KeyBoardDevice()
 {
     current  = Keyboard.GetState();
     previous = current;
 }
예제 #39
0
 public void update()
 {
     previous = current;
     current  = Keyboard.GetState();
 }
예제 #40
0
 public KeyboardStateConverter(KeyboardState state)
 {
     State = state;
 }
예제 #41
0
 public virtual void Keyboard(KeyboardState state, KeyboardState oldState)
 {
 }
예제 #42
0
        public void Update(GameTime gametime)
        {
            KeyboardState kb = Keyboard.GetState();

            elapsedTime += (float)gametime.ElapsedGameTime.TotalSeconds;
            speaktimer  += (float)gametime.ElapsedGameTime.TotalSeconds;
            rectangle    = new Rectangle((int)position.X, (int)position.Y, 40, 48);
            Center       = new Vector2(position.X + width / 2, position.Y + height / 2);


            Collision();

            // player movement en acties
            if (kb.IsKeyDown(Keys.Left))
            {
                spriteEffects = SpriteEffects.FlipHorizontally;
            }

            if (kb.IsKeyDown(Keys.Right))
            {
                spriteEffects = SpriteEffects.None;
            }
            for (int i = 0; i < TestLevel.collectibles.Count; i++)
            {
                if (rectangle.Intersects(TestLevel.collectibles[i].rectangle))
                {
                    points += TestLevel.collectibles[i].value;
                    TestLevel.collectibles[i].pickedUp = true;
                }
            }

            if (speaktimer >= 20)
            {
                Game1.i_hope.Play(0.5f, 0, 0);

                speaktimer = 0;
            }

            foreach (Ladder ladder in TestLevel.ladders)
            {
                if (rectangle.Intersects(ladder.rectangle))
                {
                    if (kb.IsKeyDown(Keys.W))
                    {
                        status = HansStatus.climbing;
                    }
                }
            }

            for (int i = 0; i < TestLevel.buttons.Count; i++)
            {
                if (rectangle.Intersects(TestLevel.buttons[i].rectangle))
                {
                    if (PulltheLever)
                    {
                        speaktimer += (float)gametime.ElapsedGameTime.TotalSeconds;

                        for (int h = 0; h < TestLevel.doors.Count; h++)
                        {
                            if (TestLevel.buttons[i].indexNumber == TestLevel.doors[h].indexNumber)
                            {
                                if (speaktimer >= 1.5f)
                                {
                                    TestLevel.doors[i].OpenDoor();
                                    Game1.lever.Play();
                                    speaktimer   = 0;
                                    PulltheLever = false;
                                }
                            }
                        }
                    }

                    if (kb.IsKeyDown(Keys.LeftControl))
                    {
                        if (PulltheLever == false)
                        {
                            PulltheLever = true;
                            Game1.pullLever.Play();
                        }
                    }
                }
            }

            /*foreach (Door_button button in TestLevel.buttons)
             * {
             *
             *  if (rectangle.Intersects(button.rectangle))
             *  {
             *
             *
             *
             *  }
             * }*/

            foreach (MoveDoorButton button in TestLevel.Mbuttons)
            {
                button.FrameIndex = 1;
                button.UpdateAnimation(gametime);
                if (rectangle.Intersects(button.rectangle))
                {
                    if (kb.IsKeyDown(Keys.LeftControl))
                    {
                        for (int h = 0; h < TestLevel.Mbuttons.Count; h++)
                        {
                            if (button.indexNumber == TestLevel.Mdoors[h].indexNumber)
                            {
                                TestLevel.Mdoors[h].move = true;
                            }
                        }
                    }
                }
            }

            if (status == HansStatus.walking)
            {
                if (kb.IsKeyDown(Keys.W) && hasJumped == false)
                {
                    position.Y -= 10f;
                    velocity.Y  = -4f;
                    hasJumped   = true;
                }

                else if (hasJumped)
                {
                    if (Animation != "jump")
                    {
                        Animation          = "jump";
                        IdleAnimate.Frames = 6;
                    }

                    if (kb.IsKeyDown(Keys.A))
                    {
                        position.X += velocity.X;
                        velocity.X  = -3;
                    }

                    if (position.X < 3875)
                    {
                        if (kb.IsKeyDown(Keys.D))
                        {
                            position.X += velocity.X;
                            velocity.X  = 3;
                        }
                    }

                    velocity.Y += 0.15f;
                    position.Y += velocity.Y;
                }

                else if (kb.IsKeyDown(Keys.A))
                {
                    position.X += velocity.X;
                    velocity.X  = -3;
                    if (Animation != "walk")
                    {
                        Animation          = "walk";
                        IdleAnimate.Frames = 14;
                    }
                }

                else if (kb.IsKeyDown(Keys.D))
                {
                    position.X += velocity.X;
                    velocity.X  = 3;
                    if (Animation != "walk")
                    {
                        Animation          = "walk";
                        IdleAnimate.Frames = 14;
                    }
                }

                else
                {
                    if (Animation != "idle")
                    {
                        Animation          = "idle";
                        IdleAnimate.Frames = 11;
                    }
                }

                if (gravity)
                {
                    velocity.Y += gravitypower * (float)gametime.ElapsedGameTime.TotalSeconds;
                    position.Y += velocity.Y;
                }



                /*if (rectangle.Intersects(TestLevel.door.rectangle))
                 * {
                 *  position.X = TestLevel.door.position.X + TestLevel.door.texture.Width;
                 * }
                 *
                 * TestLevel.door.Update(gametime);
                 * TestLevel.button.ReactToDoor(TestLevel.door,position);
                 */

                gravity = true;
            }

            if (status == HansStatus.climbing)
            {
                if (kb.IsKeyDown(Keys.W))
                {
                    position.Y -= 1;
                }

                foreach (Ladder ladder in TestLevel.ladders)
                {
                    if (!rectangle.Intersects(ladder.rectangle))
                    {
                        status = HansStatus.walking;
                    }
                }
            }
        }
예제 #43
0
        public void Update(KeyboardState kstate, GameTime gameTime, Camera camera, List <InventoryItem> actionInventory)
        {
            timeSinceLastExpClean += gameTime.ElapsedGameTime.Milliseconds;

            // clean shots
            foreach (var shot in Shots)
            {
                shot.Update(gameTime);
            }
            if (timeSinceLastExpClean > millisecondsExplosionLasts)
            {
                // remove exploded shots
                for (int i = 0; i < Shots.Count; i++)
                {
                    if (Shots[i].exploded || Shots[i].outOfRange)
                    {
                        Shots.RemoveAt(i);
                    }
                }
                timeSinceLastExpClean = 0;
            }

            // lighting items
            if (emittingLight != null)
            {
                // toggle light
                if (kstate.IsKeyDown(Keys.T))
                {
                    msToggleButtonHit += gameTime.ElapsedGameTime.Milliseconds;
                    if (msToggleButtonHit > 500) // toggle time 500ms
                    {
                        emittingLight.lit = !emittingLight.lit;
                        msToggleButtonHit = 0;
                    }
                }

                emittingLight.Update(kstate, gameTime, GetBoundingBox().Center.ToVector2());
            }

            aiming = false;

            // aiming
            if (Mouse.GetState().LeftButton == ButtonState.Pressed)
            {
                timeSinceLastShot += gameTime.ElapsedGameTime.Milliseconds;
                float percentReloaded = timeSinceLastShot / millisecondsNewShot;

                aiming       = true;
                startAimLine = GetBoundingBox().Center.ToVector2();

                Vector2 mousePos   = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
                Vector2 clickPos   = mousePos - new Vector2(GameOptions.PrefferedBackBufferWidth / 2, GameOptions.PrefferedBackBufferHeight / 2) + camera.Position;
                Vector2 reloadSpot = new Vector2(((1 - percentReloaded) * startAimLine.X + (percentReloaded * clickPos.X)), ((1 - percentReloaded) * startAimLine.Y + (percentReloaded * clickPos.Y)));

                var lineDistanceFull   = PhysicsUtility.VectorMagnitude(clickPos.X, startAimLine.X, clickPos.Y, startAimLine.Y);
                var lineDistanceReload = PhysicsUtility.VectorMagnitude(reloadSpot.X, startAimLine.X, reloadSpot.Y, startAimLine.Y);

                // max range
                float   disRatio = shotRange / lineDistanceFull;
                Vector2 maxPos   = new Vector2(((1 - disRatio) * startAimLine.X + (disRatio * clickPos.X)), ((1 - disRatio) * startAimLine.Y + (disRatio * clickPos.Y)));

                // shot offset from mount
                float shotOffsetRatio = 30 / lineDistanceFull;
                shotOffsetPos = new Vector2(((1 - shotOffsetRatio) * startAimLine.X + (shotOffsetRatio * clickPos.X)), ((1 - shotOffsetRatio) * startAimLine.Y + (shotOffsetRatio * clickPos.Y)));

                // restrict aiming by shotRange
                if (lineDistanceFull > shotRange)
                {
                    endAimLineFull = maxPos;
                }
                else
                {
                    endAimLineFull = clickPos;
                }

                if (lineDistanceReload > lineDistanceFull || lineDistanceReload > shotRange)
                {
                    endAimLineReload = endAimLineFull;
                }
                else
                {
                    endAimLineReload = reloadSpot;
                }

                // rotate the mount
                float angleFull = (float)Math.Atan2(edgeFull.Y, edgeFull.X);
                rotation = angleFull + ((float)Math.PI / 2);
            }
            else
            {
                aiming = false;
            }

            // shooting
            if (aiming && kstate.IsKeyDown(Keys.Space) && timeSinceLastShot > millisecondsNewShot)
            {
                animateShot = true;
                // loading ammo
                if (ammoLoaded == null || actionInventory[ammoLoadedIndex] == null || actionInventory[ammoLoadedIndex].bbKey != ammoLoaded.bbKey) // ran out of ammo, or switched ammo type. Reload
                {
                    for (int i = 0; i < actionInventory.Count; i++)
                    {
                        var item = actionInventory[i];
                        if (item != null && item is IShipAmmoItem && ammoItemType == item.GetType()) // TODO: selects the first item in ship action inv to shoot
                        {
                            if (item.amountStacked > 0)
                            {
                                ammoLoaded      = item;
                                ammoLoadedIndex = i;
                                IShipAmmoItem sai = (IShipAmmoItem)item;
                                firedAmmoKey = sai.GetFiredAmmoKey();
                            }
                            break;
                        }
                    }
                }
                else
                {
                    Ammo  shot      = (Ammo)ItemUtility.CreateItem(firedAmmoKey, teamType, regionKey, shotOffsetPos, _content, _graphics);
                    float angleFull = (float)Math.Atan2(edgeFull.Y, edgeFull.X);
                    shot.rotation = angleFull + ((float)Math.PI / 2);
                    shot.SetFireAtDirection(endAimLineFull, RandomEvents.rand.Next(10, 25), 0);
                    shot.moving = true;
                    Shots.Add(shot);
                    timeSinceLastShot         = 0;
                    ammoLoaded.amountStacked -= 1;
                    if (ammoLoaded.amountStacked <= 0)
                    {
                        ammoLoaded = null;
                    }
                }
            }

            if (animateShot)
            {
                msAnimateShot += gameTime.ElapsedGameTime.Milliseconds;
                if (msAnimateShot > 70)
                {
                    currColumnFrame++;
                    msAnimateShot = 0;
                }
                if (currColumnFrame >= nColumns)
                {
                    currColumnFrame = 0;
                    animateShot     = false;
                }
            }
        }
예제 #44
0
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            if (playing)
            {
                //Winning:
                if (Fishies.Count == 0)
                {
                    playing = false;
                    MessageBox.Show("You won!", "Good job", new string[] { "Ok" });
                }
                if (!Bob.Alive && !Steve.Alive)
                {
                    playing = false;
                    MessageBox.Show("You lost!", "Good job", new string[] { "Ok" });
                }

                if (Keyboard.GetState().IsKeyDown(Keys.NumPad0))
                {
                    LaserSpeed = LaserSpeedCoefficient * 10;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.NumPad1))
                {
                    LaserSpeed = LaserSpeedCoefficient * 1;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.NumPad2))
                {
                    LaserSpeed = LaserSpeedCoefficient * 2;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.NumPad3))
                {
                    LaserSpeed = LaserSpeedCoefficient * 3;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.NumPad4))
                {
                    LaserSpeed = LaserSpeedCoefficient * 4;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.NumPad5))
                {
                    LaserSpeed = LaserSpeedCoefficient * 5;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.NumPad6))
                {
                    LaserSpeed = LaserSpeedCoefficient * 6;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.NumPad7))
                {
                    LaserSpeed = LaserSpeedCoefficient * 7;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.NumPad8))
                {
                    LaserSpeed = LaserSpeedCoefficient * 8;
                }
                if (Keyboard.GetState().IsKeyDown(Keys.NumPad9))
                {
                    LaserSpeed = LaserSpeedCoefficient * 9;
                }

                if (Bob.Alive)
                {
                    Bob.Update(Keyboard.GetState(), lastkb, gameTime, new Vector2(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight));
                }
                if (Steve.Alive)
                {
                    Steve.Update(Keyboard.GetState(), lastkb, gameTime, new Vector2(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight));
                }

                if (ElapsedFishTime >= FishSpawnTime)
                {
                    ElapsedFishTime = TimeSpan.Zero;

                    int thing = random.Next(0, 10);
                    //Generating a tank every 1 in 10 fish:
                    if (thing == 9)
                    {
                        //Add tankFish;
                        Fishies.Add(new AiFish(TankRectangles.Select((currentAiRectangle) => new AnimationFrame(currentAiRectangle)).ToArray(), TimeSpan.FromMilliseconds(100), Content.Load <Texture2D>("FishSheet2"), Content.Load <Texture2D>("Laser"), new Vector2(random.Next(50, graphics.PreferredBackBufferWidth - 50), random.Next(50, graphics.PreferredBackBufferHeight - 50)), new Vector2(7.5f, 13), Vector2.One, Color.White, PlayerKeyboardLayout.AI, 3));
                    }
                    else if (thing <= 8 && thing >= 7)
                    {
                        //Add Snekfish:
                        Fishies.Add(new SnekFish(SnekRectangles.Select((currentAiRectangle) => new AnimationFrame(currentAiRectangle)).ToArray(), TimeSpan.FromMilliseconds(100), Content.Load <Texture2D>("FishSheet2"), Content.Load <Texture2D>("Laser"), new Vector2(random.Next(50, graphics.PreferredBackBufferWidth - 50), random.Next(50, graphics.PreferredBackBufferHeight - 50)), new Vector2(7.5f, 13), Vector2.One, Color.White, PlayerKeyboardLayout.AI));
                    }
                    else
                    {
                        //Add normal AiFish:
                        Fishies.Add(new AiFish(AiRectangles.Select((currentAiRectangle) => new AnimationFrame(currentAiRectangle)).ToArray(), TimeSpan.FromMilliseconds(100), Content.Load <Texture2D>("FishSheet1"), Content.Load <Texture2D>("Laser"), new Vector2(random.Next(50, graphics.PreferredBackBufferWidth - 50), random.Next(50, graphics.PreferredBackBufferHeight - 50)), new Vector2(7.5f, 13), Vector2.One, Color.White, PlayerKeyboardLayout.AI));
                    }
                }


                for (int i = 0; i < Fishies.Count; i++)
                {
                    int value = Fishies[i].Update(gameTime, new Vector2(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight));
                    if (value == 1)
                    {
                        Fishies.RemoveAt(i);
                        i--;
                    }
                }


                ElapsedFishTime += gameTime.ElapsedGameTime;

                lastkb = Keyboard.GetState();

                Window.Title = Text;


                base.Update(gameTime);
            }
        }
예제 #45
0
        public void Update(GameTime gameTime, Tilemap tilemap)
        {
            float         dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
            KeyboardState ks = Keyboard.GetState();

            int speedX = 0;
            int speedY = 0;

            if (ks.IsKeyDown(Keys.Down))
            {
                Direction = 2;
                Y        += 5;
                speedY    = 5;
            }
            if (ks.IsKeyDown(Keys.Up))
            {
                Direction = 8;
                Y        -= 5;
                speedY    = -5;
            }
            if (ks.IsKeyDown(Keys.Right))
            {
                Direction = 6;
                X        += 5;
                speedX    = 5;
            }
            if (ks.IsKeyDown(Keys.Left))
            {
                Direction = 4;
                X        -= 5;
                speedX    = -5;
            }

            // Collision
            bool  firstCollision  = false;
            bool  secondCollision = false;
            float collisionOx     = X;
            float collisionOy     = Y;

            // Premiere collision
            if (Direction == 6 || Direction == 2)
            {
                collisionOx += image.Width;
                collisionOy += image.Height;
            }
            int nextTileCol = (int)Math.Floor((collisionOx + speedX) / (float)tilemap.Tileset.Tilesize);
            int nextTileRow = (int)Math.Floor((collisionOy + speedY) / (float)tilemap.Tileset.Tilesize);
            int tile        = tilemap.Data[nextTileRow][nextTileCol];

            if (tile == 1)
            {
                firstCollision = true;
            }

            // Seconde collision
            if (Direction == 2)
            {
                collisionOx -= image.Width;
            }
            else if (Direction == 4)
            {
                collisionOy += image.Height;
            }
            else if (Direction == 6)
            {
                collisionOy -= image.Height;
            }
            else if (Direction == 8)
            {
                collisionOx += image.Width;
            }
            nextTileCol = (int)Math.Floor((collisionOx + Speed.X * dt) / (float)tilemap.Tileset.Tilesize);
            nextTileRow = (int)Math.Floor((collisionOy + Speed.Y * dt) / (float)tilemap.Tileset.Tilesize);

            tile = tilemap.Data[nextTileRow][nextTileCol];
            if (tile == 1)
            {
                secondCollision = true;
            }

            // Resolution
            if (firstCollision || secondCollision)
            {
                X += -speedX;
                Y += -speedY;
            }
        }
예제 #46
0
 private static bool AltComboPressed(KeyboardState state, Microsoft.Xna.Framework.Input.Keys key)
 {
     return(state.IsKeyDown(key) && (state.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftAlt) || state.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.RightAlt)));
 }
예제 #47
0
        public void Update(GameTime pGameTime)
        {
            float totalSeconds = (float)pGameTime.ElapsedGameTime.TotalSeconds;

            GamePadState currentState = GamePad.GetState(PlayerIndex.One);

            if (currentState.IsConnected)
            {
                // TODO gamepad support
            }
            else
            {
                if (_camera.Type == Camera.ProjectionType.PERSPECTIVE_PROJECTION)
                {
                    // Handle mouse input
                    MouseState mouseState = Mouse.GetState();

                    if (mouseState.LeftButton == ButtonState.Pressed)
                    {
                        if (!_mlb)
                        {
                            _mlb             = true;
                            _currentMousePos = new Vector2(mouseState.X, mouseState.Y);
                        }
                        else
                        {
                            Vector2 mPos  = new Vector2(mouseState.X, mouseState.Y);
                            Vector2 delta = mPos - _currentMousePos;
                            _currentMousePos = mPos;

                            float yaw   = delta.X;
                            float pitch = delta.Y;

                            _camera.Rotate(yaw, pitch);
                        }
                    }
                    else
                    {
                        _mlb = false;
                    }

                    //Zoom
                    if (_msw)
                    {
                        _msw         = true;
                        _scrollWheel = mouseState.ScrollWheelValue;
                    }
                    else
                    {
                        int delta = _scrollWheel - mouseState.ScrollWheelValue;

                        _camera.Zoom(delta);

                        _scrollWheel = mouseState.ScrollWheelValue;
                    }
                }
                else
                {
                    KeyboardState keyState = Keyboard.GetState();

                    if (keyState.IsKeyDown(Keys.Left))
                    {
                        _camera.Horizontal(-.5f);
                    }
                    else if (keyState.IsKeyDown(Keys.Right))
                    {
                        _camera.Horizontal(.5f);
                    }
                    else if (keyState.IsKeyDown(Keys.Up))
                    {
                        _camera.Vertical(.5f);
                    }
                    else if (keyState.IsKeyDown(Keys.Down))
                    {
                        _camera.Vertical(-.5f);
                    }
                    else if (keyState.IsKeyDown(Keys.Add))
                    {
                        _camera.Zoom(-1f);
                    }
                    else if (keyState.IsKeyDown(Keys.Subtract))
                    {
                        _camera.Zoom(1f);
                    }
                    else if (keyState.IsKeyDown(Keys.Space))
                    {
                        _nextMode = true;
                    }
                    else if (_nextMode)
                    {
                        Instancing.nextMode();
                        _nextMode = false;
                    }
                }
            }
        }
예제 #48
0
        public static string GetInputText(string oldString)
        {
            if (!Main.hasFocus)
            {
                return(oldString);
            }
            inputTextEnter  = false;
            inputTextEscape = false;
            string text    = oldString;
            string newKeys = "";

            if (text == null)
            {
                text = "";
            }
            bool flag = false;

            if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl) || inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.RightControl))
            {
                if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Z) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Z))
                {
                    text = "";
                }
                else if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.X) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.X))
                {
                    PlatformUtilities.SetClipboard(oldString);
                    text = "";
                }
                else if ((inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.C) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.C)) || (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Insert) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Insert)))
                {
                    PlatformUtilities.SetClipboard(oldString);
                }
                else if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.V) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.V))
                {
                    newKeys += PlatformUtilities.GetClipboard();
                }
            }
            else
            {
                if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftShift) || inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.RightShift))
                {
                    if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Delete) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Delete))
                    {
                        Thread thread = new Thread((ThreadStart) delegate
                        {
                            if (oldString.Length > 0)
                            {
                                Clipboard.SetText(oldString);
                            }
                        });
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        while (thread.IsAlive)
                        {
                        }
                        text = "";
                    }
                    if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Insert) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Insert))
                    {
                        Thread thread2 = new Thread((ThreadStart) delegate
                        {
                            string text2 = Clipboard.GetText();
                            for (int l = 0; l < text2.Length; l++)
                            {
                                if (text2[l] < ' ' || text2[l] == '\u007f')
                                {
                                    text2 = text2.Replace(string.Concat(text2[l--]), "");
                                }
                            }
                            newKeys += text2;
                        });
                        thread2.SetApartmentState(ApartmentState.STA);
                        thread2.Start();
                        while (thread2.IsAlive)
                        {
                        }
                    }
                }
                for (int i = 0; i < Main.keyCount; i++)
                {
                    int    num = Main.keyInt[i];
                    string str = Main.keyString[i];
                    if (num == 13)
                    {
                        inputTextEnter = true;
                    }
                    else if (num == 27)
                    {
                        inputTextEscape = true;
                    }
                    else if (num >= 32 && num != 127)
                    {
                        newKeys += str;
                    }
                }
            }
            Main.keyCount = 0;
            text         += newKeys;
            oldInputText  = inputText;
            inputText     = Keyboard.GetState();
            Microsoft.Xna.Framework.Input.Keys[] pressedKeys  = inputText.GetPressedKeys();
            Microsoft.Xna.Framework.Input.Keys[] pressedKeys2 = oldInputText.GetPressedKeys();
            if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Back) && oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Back))
            {
                if (backSpaceCount == 0)
                {
                    backSpaceCount = 7;
                    flag           = true;
                }
                backSpaceCount--;
            }
            else
            {
                backSpaceCount = 15;
            }
            for (int j = 0; j < pressedKeys.Length; j++)
            {
                bool flag2 = true;
                for (int k = 0; k < pressedKeys2.Length; k++)
                {
                    if (pressedKeys[j] == pressedKeys2[k])
                    {
                        flag2 = false;
                    }
                }
                string a = string.Concat(pressedKeys[j]);
                if (a == "Back" && (flag2 || flag) && text.Length > 0)
                {
                    TextSnippet[] array = ChatManager.ParseMessage(text, Microsoft.Xna.Framework.Color.White);
                    if (array[array.Length - 1].DeleteWhole)
                    {
                        text = text.Substring(0, text.Length - array[array.Length - 1].TextOriginal.Length);
                    }
                    else
                    {
                        text = text.Substring(0, text.Length - 1);
                    }
                }
            }
            return(text);
        }
예제 #49
0
        /// <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 keyState = Keyboard.GetState();
            GamePadState  padState = GamePad.GetState(PlayerIndex.One);

            // Allows the game to exit
            if ((padState.Buttons.Back == ButtonState.Pressed) ||
                (keyState.IsKeyDown(Keys.Escape)))
            {
                this.Exit();
            }

            //Reset
            if (keyState.IsKeyDown(Keys.R))
            {
                gameResetKeyDown = true;
            }
            else if (keyState.IsKeyUp(Keys.R) && gameResetKeyDown)
            {
                gameResetKeyDown = false;

                //Reset The Game Here
                Reset();
            }

            CheckPauseMenu(keyState, Mouse.GetState());

            //Screenie
            if (keyState.IsKeyDown(Keys.PrintScreen))
            {
                gameScreenieKeyDown = true;
            }
            else if (keyState.IsKeyUp(Keys.PrintScreen) && gameScreenieKeyDown)
            {
                gameScreenieKeyDown = false;
                gamePaused          = true;

                ResolveTexture2D screenShot = new ResolveTexture2D(graphics.GraphicsDevice, 400, 600, 0, SurfaceFormat.Vector4);

                graphics.GraphicsDevice.ResolveBackBuffer(screenShot);

                //Find A Place TO Save Screenshot :)
                ulong append = 0;

                if (!Directory.Exists("Screenshots"))
                {
                    Directory.CreateDirectory("Screenshots");
                }

                while (File.Exists("Screenshots\\underAttackScreen-" + append + ".png"))
                {
                    append++;
                }

                screenShot.Save("Screenshots\\underAttackScreen-" + append + ".png", ImageFileFormat.Png);
            }

            if ((gameTime.TotalGameTime.TotalMilliseconds - lastAnimUpdate) > 100)
            {
                foreach (GameUnit unit in animations)
                {
                    if (unit.IsAnimating)
                    {
                        unit.CurrentFrame = unit.CurrentFrame + 1;
                        if (unit.CurrentFrame >= (sprites[unit.SpriteName].FrameCount))
                        {
                            deadAnims.Add(unit);
                        }
                    }
                }

                //Time Updating here too - ONLY when game is running
                if (!gameOver && !gamePaused)
                {
                    timePassed++;
                    timeParam.SetValue(timePassed / 20f);
                }
                lastAnimUpdate = gameTime.TotalGameTime.TotalMilliseconds;
            }

            if (!gameOver && !gamePaused)
            {
                //Count time alive
                timeAlive += gameTime.ElapsedGameTime.TotalSeconds;

                //Motion Input
                CheckPlayerInput(keyState);

                //Move all Units where auto-motion is req.
                MoveGameUnits();

                //Check For A Press And Release To Fire...Make Sure Every Release Is atleast 250 Ms apart
                if (keyState.IsKeyDown(Keys.Space) && !gameShootKeyDown && ((gameTime.TotalGameTime.TotalMilliseconds - lastShotUpdate) > 200))
                {
                    gameShootKeyDown = true;
                }
                else if (keyState.IsKeyUp(Keys.Space) && gameShootKeyDown)
                {
                    GameUnit bullet = new GameUnit("bullet", playerOne.Position - new Vector2(0, 32), new Vector2(4f, 4f));
                    bullet.Velocity = new Vector2(0, -2);
                    units.Add(bullet);

                    //Update last shot time
                    lastShotUpdate = gameTime.TotalGameTime.TotalMilliseconds;

                    //Reset Press variable
                    gameShootKeyDown = false;
                }

                //Remove Dead Units
                foreach (GameUnit e in deadBullets)
                {
                    units.Remove(e);
                }

                foreach (GameUnit e in deadUnits)
                {
                    units.Remove(e);
                }

                foreach (GameUnit e in deadAnims)
                {
                    units.Remove(e);
                }

                //Clear already dead units.
                deadBullets.Clear();
                deadUnits.Clear();
                deadAnims.Clear();
            }
            base.Update(gameTime);
        }
예제 #50
0
 public void Update()
 {
     _oldState = _newState;
     _newState = Keyboard.GetState();
 }
예제 #51
0
 public override void Update(GameTime gameTime)
 {
     PrevKBState = CurrKBState;
     CurrKBState = Keyboard.GetState();
 }
예제 #52
0
        public override void Update(GameTime gameTime)
        {
            #region move player

            KeyboardState keyPress = Keyboard.GetState();

            velocity.X = 0; //resetting velocity
            velocity.Z = 0;

            bool keyW     = false;
            bool keyA     = false;
            bool keyS     = false;
            bool keyD     = false;
            bool keyShift = false;
            bool keyAlt   = false;

            float runMod = 0;

            //movement depends on which keys are pressed, individually or together
            if (keyPress.IsKeyDown(Keys.W))
            {
                keyW = true;
            }
            if (keyPress.IsKeyDown(Keys.A))
            {
                keyA = true;
            }
            if (keyPress.IsKeyDown(Keys.S))
            {
                keyS = true;
            }
            if (keyPress.IsKeyDown(Keys.D))
            {
                keyD = true;
            }

            if (keyPress.IsKeyDown(Keys.LeftShift)) //for running
            {
                keyShift = true;
            }
            if (keyPress.IsKeyDown(Keys.LeftAlt)) //for walking slower
            {
                keyAlt = true;
            }

            if (keyShift)          //applying the appropreate move speed modifier
            {
                runMod = RUNSPEED; //move faster
            }
            else if (keyAlt)
            {
                runMod = -(RUNSPEED / 2); //move slower
            }

            if (keyW && !keyA && !keyD) //moving negative along x and positive z axis
            {
                velocity.X = -SPEED - runMod;
                velocity.Z = SPEED + runMod;
            }
            else if (keyA && !keyW && !keyS) //moving positive along x and z axis
            {
                velocity.X = SPEED + runMod;
                velocity.Z = SPEED + runMod;
            }
            else if (keyS && !keyA && !keyD) //moving positive along x axis and negative along z axis
            {
                velocity.X = SPEED + runMod;
                velocity.Z = -SPEED - runMod;
            }
            else if (keyD && !keyS && !keyW) //moving negative along x and z axis
            {
                velocity.X = -SPEED - runMod;
                velocity.Z = -SPEED - runMod;
            }
            else if (keyW && keyA) //moving positive along z axis
            {
                velocity.Z = (SPEED + runMod) * SPEEDMOD;
            }
            else if (keyW && keyD) //moving negative along x axis
            {
                velocity.X = (-SPEED - runMod) * SPEEDMOD;
            }
            else if (keyA && keyS) //moving positive along x axis
            {
                velocity.X = (SPEED + runMod) * SPEEDMOD;
            }
            else if (keyD && keyS) //moving negative along z axis
            {
                velocity.Z = (-SPEED - runMod) * SPEEDMOD;
            }

            if (velocity.X != 0 || velocity.Z != 0)
            {
                isMoving = true;
            }
            else
            {
                isMoving = false;
            }

            #endregion

            #region is colliding?

            Vector3 proposedLocation = new Vector3(modelPosition.X + velocity.X, 0f, modelPosition.Z + velocity.Z);

            foreach (Walls wall in basementWalls)
            {
                if (boundingBoxXNeg.Intersects(wall.BoundingBox) && !wall.CanWalkThrough)
                {
                    isCollidingXNeg = true;
                    if (velocity.X < 0)
                    {
                        proposedLocation.X = modelPosition.X - velocity.X;
                        //modelPosition.X += velocity.X * -0.1f;
                        velocity.X = 0;
                    }
                }
                else
                {
                    isCollidingXNeg = false;
                }
                if (boundingBoxXPos.Intersects(wall.BoundingBox) && !wall.CanWalkThrough)
                {
                    isCollidingXPos = true;
                    if (velocity.X > 0)
                    {
                        proposedLocation.X = modelPosition.X - velocity.X;
                        //modelPosition.X += velocity.X * -0.1f;
                        velocity.X = 0;
                    }
                }
                else
                {
                    isCollidingXPos = false;
                }
                if (boundingBoxZNeg.Intersects(wall.BoundingBox) && !wall.CanWalkThrough)
                {
                    isCollidingZNeg = true;
                    if (velocity.Z < 0)
                    {
                        proposedLocation.Z = modelPosition.Z - velocity.Z;
                        velocity.Z         = 0;
                    }
                }
                else
                {
                    isCollidingZNeg = false;
                }
                if (boundingBoxZPos.Intersects(wall.BoundingBox) && !wall.CanWalkThrough)
                {
                    isCollidingZPos = true;
                    if (velocity.Z > 0)
                    {
                        proposedLocation.Z = modelPosition.Z - velocity.Z;
                        velocity.Z         = 0;
                    }
                }
                else
                {
                    isCollidingZPos = false;
                }
            }

            #endregion

            if (!isPlayerDead) //while player is not dead, can move
            {
                //applying the move for the player
                modelPosition.X = proposedLocation.X;
                modelPosition.Z = proposedLocation.Z;
            }

            #region move camera

            cameraPosition   = modelPosition + cameraOffset; //camera is always fixed on the player
            cameraViewMatrix = Matrix.CreateLookAt(cameraPosition, modelPosition, cameraUpVector);

            #endregion

            #region getting mouse position

            //code modified from here
            //https://gamedev.stackexchange.com/questions/57625/getting-a-3d-mouse-position
            //https://gamedev.stackexchange.com/questions/23395/how-to-convert-screen-space-into-3d-world-space

            //need to create a fake world matrix where center of unproject will always be same as player character
            worldMatrix = Matrix.CreateTranslation(modelPosition);

            MouseState mouseState = Mouse.GetState();

            Vector3 nearSource = new Vector3((float)mouseState.X, (float)mouseState.Y, 0f);
            Vector3 farSource  = new Vector3((float)mouseState.X, (float)mouseState.Y, 1f);
            Vector3 nearPoint  = graphicsDevice.Viewport.Unproject(nearSource, _Initializations.GetProjectionMatrix(), cameraViewMatrix, worldMatrix);
            Vector3 farPoint   = graphicsDevice.Viewport.Unproject(farSource, _Initializations.GetProjectionMatrix(), cameraViewMatrix, worldMatrix);

            // Create a ray from the near clip plane to the far clip plane.
            Vector3 direction = farPoint - nearPoint;
            direction.Normalize();

            // Create a ray.
            Ray ray = new Ray(nearPoint, direction);

            // Calculate the ray-plane intersection point.
            Vector3 n = new Vector3(0f, 1f, 0f);
            Plane   p = new Plane(n, 0f);

            // Calculate distance of intersection point from r.origin.
            float denominator = Vector3.Dot(p.Normal, ray.Direction);
            float numerator   = Vector3.Dot(p.Normal, ray.Position) + p.D;
            float t           = -(numerator / denominator);

            // Calculate the picked position on the y = 0 plane.
            mousePosition = nearPoint + direction * t;

            #endregion

            #region player lighting

            playerLightDirection = -cameraPosition;

            #endregion

            base.Update(gameTime);
        }
예제 #53
0
        /// <summary>
        /// Checks if the player presses the Space bar, then checks if any monsters are in range.
        /// Those monsters then take damage.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public void Update(GameTime gameTime)
        {
            CurrentState = Keyboard.GetState();

            if (CurrentState.IsKeyDown(Keys.Space) && OldState.IsKeyUp(Keys.Space) && !player.Attacking)
            {
                player.Attacking = true;
                AttackTime       = gameTime.TotalGameTime;

                // An array of all monsters in the current room.
                List <Monster> monsters = GameManager.GameWorld.currentRoom.Monsters;

                foreach (Monster monster in monsters)
                {
                    double distToPlayer = monster.Distance(player.Position);
                    if (distToPlayer < player.AttackRange)
                    {
                        switch (player.PlayerDirection)
                        {
                        case Direction.Down:
                            if (monster.position.Y > player.Position.Y)
                            {
                                player.Attack(monster);
                            }
                            break;

                        case Direction.Up:
                            if (monster.position.Y < player.Position.Y)
                            {
                                player.Attack(monster);
                            }
                            break;

                        case Direction.Right:
                            if (monster.position.X > player.Position.X)
                            {
                                player.Attack(monster);
                            }
                            break;

                        case Direction.Left:
                            if (monster.position.X < player.Position.X)
                            {
                                player.Attack(monster);
                            }
                            break;
                        }
                    }
                }
            }

            if (player.Attacking)
            {
                if (gameTime.TotalGameTime - AttackTime > player.AttackTime)
                {
                    player.Attacking = false;
                }
            }

            OldState = CurrentState;
        }
예제 #54
0
파일: Snakeplayer2.cs 프로젝트: Alejanky/PR
        public void updatevector(int a, GameTime w, Rectangle x)
        {
            newState = Keyboard.GetState();

            switch (a)
            {
            case 0:
            {
                if (Position.Y > 64)
                {
                    Position.Y += -(0.6939f * w.ElapsedGameTime.Milliseconds);
                }
                else
                {
                    break;
                }
            }
            break;

            case 2:
            {
                if (Position.X > 64)
                {
                    Position.X -= 0.5939f * w.ElapsedGameTime.Milliseconds;
                    if (this.hitcollision(x, w, a))
                    {
                        Position += Veloctiy * w.ElapsedGameTime.Milliseconds;
                    }
                }
                else
                {
                    if (this.hitcollision(x, w, a))
                    {
                        Position += Veloctiy * w.ElapsedGameTime.Milliseconds;
                    }
                }
            }
            break;

            case 3:
            {
                if (Position.X < 900)
                {
                    Position.X += 0.5939f * w.ElapsedGameTime.Milliseconds;
                    if (this.hitcollision(x, w, a))
                    {
                        Position += Veloctiy * w.ElapsedGameTime.Milliseconds;
                    }
                }
                else
                {
                    if (this.hitcollision(x, w, a))
                    {
                        Position += Veloctiy * w.ElapsedGameTime.Milliseconds;
                    }
                }
            }
            break;

            case 4:
            {
                if (newState.IsKeyUp(Keys.Up) && this.hitcollision(x, w, a))
                {
                    Position += 2 * (Veloctiy * w.ElapsedGameTime.Milliseconds);
                }
                else
                {
                    break;
                }
            }
            break;

            case 5:
            {
                if (Position.Y > 64)
                {
                    Position += -(Veloctiy * w.ElapsedGameTime.Milliseconds);
                    if (Position.X > 64)
                    {
                        Position.X -= 0.5939f * w.ElapsedGameTime.Milliseconds;
                    }
                }

                else
                {
                    if (Position.X > 64)
                    {
                        Position.X -= 0.5939f * w.ElapsedGameTime.Milliseconds;
                    }
                }
                {
                }
            }
            break;

            case 6:
            {
                if (Position.Y > 64)
                {
                    Position += -(Veloctiy * w.ElapsedGameTime.Milliseconds);
                    if (Position.X < 900)
                    {
                        Position.X += 0.5939f * w.ElapsedGameTime.Milliseconds;
                    }
                }

                else
                {
                    if (Position.X < 900)
                    {
                        Position.X += 0.5939f * w.ElapsedGameTime.Milliseconds;
                    }
                }
                {
                }
            }
            break;

            case 7:
            {
                if (this.hitcollision(x, w, a))
                {
                    Position += Veloctiy * w.ElapsedGameTime.Milliseconds;
                    if (Position.X > 64)
                    {
                        Position.X -= 0.5939f * w.ElapsedGameTime.Milliseconds;
                    }
                }
                else
                {
                    if (Position.X > 64)
                    {
                        Position.X -= 0.5939f * w.ElapsedGameTime.Milliseconds;
                    }
                }
            }
            break;

            case 8:
            {
                if (this.hitcollision(x, w, a))
                {
                    Position += Veloctiy * w.ElapsedGameTime.Milliseconds;
                    if (Position.X < 900)
                    {
                        Position.X += 0.5939f * w.ElapsedGameTime.Milliseconds;
                    }
                }
                else
                {
                    if (Position.X < 900)
                    {
                        Position.X += 0.5939f * w.ElapsedGameTime.Milliseconds;
                    }
                }
            }
            break;
            }
        }        // fin de update vector
예제 #55
0
        /// <summary>
        /// Examine the currently pressed keys to determine what text has been typed
        /// </summary>
        /// <returns>The typed chars.</returns>
        /// <param name="CurrKeys">Curren keyboardstate.</param>
        /// <param name="PriorKeys">Prior keyboard state, how it was during a previous update.</param>
        public static string GetTypedChars(KeyboardState CurrKeys, KeyboardState PriorKeys)
        {
            Keys[] PressedList = CurrKeys.GetPressedKeys();
            string NewKeys     = "";
            bool   ShiftDown;

            if ((CurrKeys.IsKeyDown(Keys.LeftShift) == true) || (CurrKeys.IsKeyDown(Keys.RightShift) == true))
            {
                ShiftDown = true;
            }
            else
            {
                ShiftDown = false;
            }

            foreach (Keys CurrKey in PressedList)
            {
                if (PriorKeys.IsKeyDown(CurrKey) == false)
                {
                    if ((CurrKey >= Keys.A) && (CurrKey <= Keys.Z))
                    {
                        if (ShiftDown == true)
                        {
                            NewKeys += CurrKey.ToString();
                        }
                        else
                        {
                            NewKeys += CurrKey.ToString().ToLower();
                        }
                    }
                    else if ((CurrKey >= Keys.D0) && (CurrKey <= Keys.D9))
                    {
                        string Num = ((int)(CurrKey - Keys.D0)).ToString();

                        if (ShiftDown == true)
                        {
                            switch (Num)
                            {
                            case "1":
                                NewKeys += "!";
                                break;

                            case "2":
                                NewKeys += "@";
                                break;

                            case "3":
                                NewKeys += "#";
                                break;

                            case "4":
                                NewKeys += "$";
                                break;

                            case "5":
                                NewKeys += "%";
                                break;

                            case "6":
                                NewKeys += "^";
                                break;

                            case "7":
                                NewKeys += "&";
                                break;

                            case "8":
                                NewKeys += "*";
                                break;

                            case "9":
                                NewKeys += "(";
                                break;

                            case "0":
                                NewKeys += ")";
                                break;

                            default:
                                //wtf?
                                break;
                            }
                        }
                        else
                        {
                            NewKeys += ((int)(CurrKey - Keys.D0)).ToString();
                        }
                    }
                    else if ((CurrKey >= Keys.NumPad0) && (CurrKey <= Keys.NumPad9))
                    {
                        NewKeys += ((int)(CurrKey - Keys.NumPad0)).ToString();
                    }
                    else if (CurrKey == Keys.OemPlus)
                    {
                        if (ShiftDown == true)
                        {
                            NewKeys += "+";
                        }
                        else
                        {
                            NewKeys += "=";
                        }
                    }
                    else if (CurrKey == Keys.OemMinus)
                    {
                        if (ShiftDown == true)
                        {
                            NewKeys += "_";
                        }
                        else
                        {
                            NewKeys += "-";
                        }
                    }
                    else if (CurrKey == Keys.OemOpenBrackets)
                    {
                        if (ShiftDown == true)
                        {
                            NewKeys += "{";
                        }
                        else
                        {
                            NewKeys += "[";
                        }
                    }
                    else if (CurrKey == Keys.OemCloseBrackets)
                    {
                        if (ShiftDown == true)
                        {
                            NewKeys += "}";
                        }
                        else
                        {
                            NewKeys += "]";
                        }
                    }
                    else if (CurrKey == Keys.OemComma)
                    {
                        if (ShiftDown == true)
                        {
                            NewKeys += "<";
                        }
                        else
                        {
                            NewKeys += ",";
                        }
                    }
                    else if (CurrKey == Keys.OemPeriod)
                    {
                        if (ShiftDown == true)
                        {
                            NewKeys += ">";
                        }
                        else
                        {
                            NewKeys += ".";
                        }
                    }
                    else if (CurrKey == Keys.OemQuestion)
                    {
                        if (ShiftDown == true)
                        {
                            NewKeys += "?";
                        }
                        else
                        {
                            NewKeys += "/";
                        }
                    }
                    else if (CurrKey == Keys.Space)
                    {
                        NewKeys += " ";
                    }
                    else if (CurrKey == Keys.Enter)
                    {
                        NewKeys += "\n";
                    }
                    else if (CurrKey == Keys.Back)
                    {
                        NewKeys += "\b";
                    }
                }
            }

            return(NewKeys);
        }
예제 #56
0
        public void Update(out Screen screen, Screen screenIn)
        {
            mouseState    = Mouse.GetState();
            keyboardState = Keyboard.GetState();
            this.screen   = screenIn;

            if (!WriteMass)
            {
                if (previousKeyboardState.IsKeyDown(Keys.Back) && keyboardState.IsKeyUp(Keys.Back))
                {
                    this.screen = Screen.Main;
                }

                //Program Start

                switch (mode)
                {
                case Mode.Idle:
                    SelectVertix(mouseState, previousMouseState);
                    break;

                case Mode.VA:
                    AddVertix(mouseState, previousMouseState);
                    break;

                case Mode.VM:
                    MoveVertix(mouseState, previousMouseState);
                    break;

                case Mode.EA:
                    AddEdge();
                    break;

                case Mode.ER:
                    RemoveEdge();
                    break;

                case Mode.VR:
                    RemoveVertix();
                    break;
                }


                //End

                if (previousKeyboardState.IsKeyDown(Keys.A) && keyboardState.IsKeyUp(Keys.A) && (selectedX == -1 || selectedY == -1))
                {
                    mode = Mode.VA;
                }

                /* else if (previousKeyboardState.IsKeyDown(Keys.A) && keyboardState.IsKeyUp(Keys.A) && selectedX != -1 && selectedY != -1)
                 *   mode = Mode.EA;
                 *
                 * if (previousKeyboardState.IsKeyDown(Keys.R) && keyboardState.IsKeyUp(Keys.R) && (selectedX == -1 && selectedY != -1 || selectedX != -1 && selectedY == -1))
                 *   mode = Mode.VR;
                 * else if (previousKeyboardState.IsKeyDown(Keys.R) && keyboardState.IsKeyUp(Keys.R) && selectedX != -1 && selectedY != -1)
                 *   mode = Mode.ER;
                 */

                if (previousKeyboardState.IsKeyDown(Keys.I) && keyboardState.IsKeyUp(Keys.I))
                {
                    mode = Mode.Idle;
                }
                if (previousKeyboardState.IsKeyDown(Keys.R) && keyboardState.IsKeyUp(Keys.R))
                {
                    Randomize();
                }
                if (previousKeyboardState.IsKeyDown(Keys.C) && keyboardState.IsKeyUp(Keys.C))
                {
                    Clear();
                }

                /*if (previousKeyboardState.IsKeyDown(Keys.M) && keyboardState.IsKeyUp(Keys.M))
                 *  mode = Mode.VM;*/

                if (previousKeyboardState.IsKeyDown(Keys.Enter) && keyboardState.IsKeyUp(Keys.Enter) && selectedX != -1 && selectedY != -1)
                {
                    WriteMass = true;
                    foreach (Edge eg in edge)
                    {
                        if (eg.x == selectedX && eg.y == selectedY || eg.y == selectedX && eg.x == selectedY)
                        {
                            selectedEdge = edge.IndexOf(eg);
                        }
                    }
                    que = 0;
                }


                if (previousKeyboardState.IsKeyDown(Keys.F) && keyboardState.IsKeyUp(Keys.F))
                {
                    if (find)
                    {
                        find = false;
                    }
                    else
                    {
                        find = true;
                    }
                }

                if (find && primeVertix != -1)
                {
                    Execute();
                }
            }
            else
            {
                if (previousKeyboardState.IsKeyDown(Keys.NumPad0) && keyboardState.IsKeyUp(Keys.NumPad0))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad1) && keyboardState.IsKeyUp(Keys.NumPad1))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 1;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad2) && keyboardState.IsKeyUp(Keys.NumPad2))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 2;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad3) && keyboardState.IsKeyUp(Keys.NumPad3))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 3;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad4) && keyboardState.IsKeyUp(Keys.NumPad4))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 4;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad5) && keyboardState.IsKeyUp(Keys.NumPad5))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 5;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad6) && keyboardState.IsKeyUp(Keys.NumPad6))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 6;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad7) && keyboardState.IsKeyUp(Keys.NumPad7))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 7;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad8) && keyboardState.IsKeyUp(Keys.NumPad8))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 8;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad9) && keyboardState.IsKeyUp(Keys.NumPad9))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 9;
                }
                if (previousKeyboardState.IsKeyDown(Keys.Back) && keyboardState.IsKeyUp(Keys.Back))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass / 10;
                }
                if (previousKeyboardState.IsKeyDown(Keys.Enter) && keyboardState.IsKeyUp(Keys.Enter))
                {
                    WriteMass = false;
                    selectedX = -1;
                    selectedY = -1;
                }
            }



            screen                = this.screen;
            previousMouseState    = mouseState;
            previousKeyboardState = keyboardState;
        }
예제 #57
0
        public static void UpdateCamera(Camera camera, GameTime gameTime, StateSpaceComponents stateSpaceComponents, int cellSize, KeyboardState prevKey)
        {
            if (Mouse.GetState().RightButton == ButtonState.Pressed)
            {
                MessageDisplaySystem.SetRandomGlobalMessage(stateSpaceComponents, Messages.CameraDetatchedMessage);
                camera.Target           = Vector2.Transform(Mouse.GetState().Position.ToVector2(), camera.GetInverseMatrix());
                camera.AttachedToPlayer = false;
            }

            if (Keyboard.GetState().IsKeyDown(Keys.W))
            {
                camera.AttachedToPlayer = false;
                camera.Position.Y      -= camera.Velocity.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
                camera.Target           = camera.Position;
                MessageDisplaySystem.SetRandomGlobalMessage(stateSpaceComponents, Messages.CameraDetatchedMessage);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.A))
            {
                camera.AttachedToPlayer = false;
                camera.Position.X      -= camera.Velocity.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
                camera.Target           = camera.Position;
                MessageDisplaySystem.SetRandomGlobalMessage(stateSpaceComponents, Messages.CameraDetatchedMessage);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.S))
            {
                camera.AttachedToPlayer = false;
                camera.Position.Y      += camera.Velocity.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
                camera.Target           = camera.Position;
                MessageDisplaySystem.SetRandomGlobalMessage(stateSpaceComponents, Messages.CameraDetatchedMessage);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.D))
            {
                camera.AttachedToPlayer = false;
                camera.Position.X      += camera.Velocity.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
                camera.Target           = camera.Position;
                MessageDisplaySystem.SetRandomGlobalMessage(stateSpaceComponents, Messages.CameraDetatchedMessage);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.OemPlus) && prevKey.IsKeyUp(Keys.OemPlus))
            {
                if (camera.Scale + .25f < 4.25f)
                {
                    camera.Scale += .25f;
                }
            }
            if (Keyboard.GetState().IsKeyDown(Keys.OemMinus) && prevKey.IsKeyUp(Keys.OemMinus))
            {
                if (camera.Scale - .25f > 0f)
                {
                    camera.Scale -= .25f;
                }
            }

            if (Keyboard.GetState().IsKeyDown(Keys.R))
            {
                camera.AttachedToPlayer = true;
                MessageDisplaySystem.SetRandomGlobalMessage(stateSpaceComponents, new string[] { string.Empty });
            }

            if (camera.AttachedToPlayer)
            {
                Entity playerId = stateSpaceComponents.Entities.Where(x => (x.ComponentFlags & ComponentMasks.Player) == ComponentMasks.Player).FirstOrDefault();
                if (stateSpaceComponents.Entities.Where(x => (x.ComponentFlags & ComponentMasks.Observer) == ComponentMasks.Observer).FirstOrDefault() != null)
                {
                    playerId = stateSpaceComponents.Entities.Where(x => (x.ComponentFlags & ComponentMasks.Observer) == ComponentMasks.Observer).FirstOrDefault();
                }
                if (playerId != null)
                {
                    camera.Target = new Vector2((int)stateSpaceComponents.PositionComponents[playerId.Id].Position.X * cellSize + stateSpaceComponents.DisplayComponents[playerId.Id].SpriteSource.Width / 2,
                                                (int)stateSpaceComponents.PositionComponents[playerId.Id].Position.Y * cellSize + stateSpaceComponents.DisplayComponents[playerId.Id].SpriteSource.Height / 2);
                }
                if (stateSpaceComponents.PlayerComponent.PlayerJustLoaded)
                {
                    camera.Position = new Vector2((int)stateSpaceComponents.PositionComponents[playerId.Id].Position.X * cellSize + stateSpaceComponents.DisplayComponents[playerId.Id].SpriteSource.Width / 2,
                                                  (int)stateSpaceComponents.PositionComponents[playerId.Id].Position.Y * cellSize + stateSpaceComponents.DisplayComponents[playerId.Id].SpriteSource.Height / 2);
                }
            }
            if (Vector2.Distance(camera.Position, camera.Target) > 0)
            {
                float   distance  = Vector2.Distance(camera.Position, camera.Target);
                Vector2 direction = Vector2.Normalize(camera.Target - camera.Position);
                float   velocity  = distance * 2.5f;
                if (distance > 10f)
                {
                    camera.Position += direction * velocity * (camera.Scale >= 1 ? camera.Scale : 1) * (float)gameTime.ElapsedGameTime.TotalSeconds;
                }
            }
        }
예제 #58
0
 public void ClearStates()
 {
     _oldState = default(KeyboardState);
     _newState = default(KeyboardState);
 }
예제 #59
0
파일: Play.cs 프로젝트: Walray/4OldGames
        public override State update(GameTime gameTime, KeyboardState ks)
        {
            if (clear)
            {
                mTimeAfterClear += gameTime.ElapsedGameTime.TotalSeconds;
                if (mTimeAfterClear >= 3.0f)
                {
                    mTimeAfterClear = 0.0f;
                    return(State.SELECTION);
                }
                return(State.PLAY);
            }


            mTimeSinceLastInput += (float)gameTime.ElapsedGameTime.TotalSeconds;
            mTimeAfterMenu      -= gameTime.ElapsedGameTime.TotalSeconds;
            if (mTimeSinceLastInput >= MIN_TIME && mTimeAfterMenu <= 0)
            {
                KeyboardState newState = Keyboard.GetState();

                if (newState.IsKeyDown(Keys.Space))
                {
                    mTimeAfterMenu = WAIT_MENU;
                    return(State.MENU);
                }
                mTimeSinceLastInput = 0.0f;
            }
            MouseState mouse = Mouse.GetState();

            time.update(gameTime);

            timeSinceLastInput += (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (timeSinceLastInput >= MinTimeSinceLastInput)
            {
                for (int y = 0; y < 9; y++)
                {
                    for (int x = 0; x < 9; x++)
                    {
                        Rectangle currentSquare = new Rectangle(x * 53, y * 53, 53, 53);

                        if ((mouse.RightButton == ButtonState.Pressed))
                        {
                            map[y, x].update(mouse.X - 45, mouse.Y - 45, true);
                        }
                        else if ((mouse.LeftButton == ButtonState.Pressed))
                        {
                            map[y, x].update(mouse.X - 45, mouse.Y - 45, false);
                        }
                    }
                }


                timeSinceLastInput = 0.0f;
            }
            for (int y = 0; y < 9; y++)
            {
                for (int x = 0; x < 9; x++)
                {
                    if (map[y, x].checkclear())
                    {
                        checkFlagCount++;
                    }
                }
            }

            if (checkFlagCount == 81)
            {
                time.IsStop = true;
                clear       = true;
            }
            else
            {
                checkFlagCount = 0;
            }

            return(State.PLAY);
        }
예제 #60
0
파일: Input.cs 프로젝트: SvDvorak/Q19
 public static void Update(GameTime gt)
 {
     kbLast  = kbState;
     kbState = Keyboard.GetState();
 }