Ejemplo n.º 1
0
    void DrawState(GamePad.Index controller)
    {
        GUILayout.Space(45);

        GUILayout.BeginVertical();
        
        
        GamepadState state = GamePad.GetState(controller);

        // buttons
        GUILayout.Label("Gamepad " + controller);
        
        GUILayout.Label("");

        // triggers
        GUILayout.Label("" + System.Math.Round(state.LeftTrigger, 2));
        GUILayout.Label("" +  System.Math.Round(state.RightTrigger, 2));

        GUILayout.Label("");

        // Axes
        GUILayout.Label("" + state.LeftStickAxis);
        GUILayout.Label("" + state.rightStickAxis);
        GUILayout.Label("" + state.dPadAxis);
        

        //GUILayout.EndArea();
        GUILayout.EndVertical();

    }
 private bool PlayerJoined(GamePad.Index controllerIndex)
 {
     if (GamePad.GetButtonDown(JoinButton, controllerIndex))
     {
         return true;
     }
     return false;
 }
Ejemplo n.º 3
0
	/*
		Initializes Game pads with all possible buttons.
	*/
	void Start() {
		_gamePadList = new GamePad[controllerList.Length];
		for (int i = 0; i < controllerList.Length; i++) {
			_gamePadList[i] = new GamePad(controllerList[i]);
			_gamePadList[i].SetRestictedPolling(restrictPollingGlobal);
			_gamePadList[i].SetDisablePolling(disablePollingGlobal);
		}
	}
Ejemplo n.º 4
0
 /// <summary>
 /// Static constructor of GamePad class
 /// </summary>
 static GamePad()
 {
     for (short i = 0; i < GamePadCount; i++)
     {
         GamePad pad = new GamePad((XnaPlayerIndex)i);
         GamePads[i] = pad;
     }
     AllDigital = EnumExtension.GetValues<Buttons>();
 }
Ejemplo n.º 5
0
 public Command Response(GamePad pad)
 {
     if (pad == null) return null;
     return new EchoCommand()
     {
         TargetAddress = Payload[0],
         Length = Length,
         Payload = Payload
     };
 }
 public static Vector2 GetAxis(GamePadKey key, GamePad.Index controller)
 {
     // Button
     if ((int)key >= 13 && (int)key <= 15)
     {
         return GamePad.GetAxis(TranslateAxis(key), controller);
     }
     // Anything else is not an axis and should not be passed as an argument to this method
     else
     {
         return Vector2.zero;
     }
 }
Ejemplo n.º 7
0
 public MainWindow()
 {
     InitializeComponent();
     controlDevices = new IControl[3];
     controlDevices[0] = new GamePad(PadStatusChanged);
     controlDevices[1] = new Keyboard();
     controlDevices[2] = new Kinect();
     currentDevice = Device.Keyboard;
     connection = new Connection(controlDevices, currentDevice);
     this.Closing += OnWindowClosing;
     ((Kinect) controlDevices[2]).SkeletonTracked += KinectSkeletonTracked;
     DataContext = controlDevices[2];
 }
 public static bool GetButtonUp(GamePadKey key, GamePad.Index controller)
 {
     // Button
     if ((int)key <= 10 && (int)key >= 1)
     {
         return GamePad.GetButtonUp(TranslateButton(key), controller);
     }
     // Anything else is not a button and should not be passed as an argument to this method
     else
     {
         return false;
     }
 }
Ejemplo n.º 9
0
 public static float GetAnyAxis(bool isHorizontal, GamePad pad = GamePad.One, bool sum = false)
 {
     if (pad == GamePad.None) return 0;
     if (pad == GamePad.All)
     {
         float value = 0;
         foreach (var controller in controllers)
         {
             value = value + controller.GetAnyAxis(isHorizontal);
         }
         if (!sum && Mathf.Abs(value) > 1) value = value / Mathf.Abs(value);
         return value;
     }
     else
         return controllers[(int)pad].GetAnyAxis(isHorizontal);
 }
    public void Init( Texture aTexture , int aiMaxIndex, int iDotSize, float afTimeBetweenMoves, GamePad.Index aGamepadIndex)
    {
        texture = aTexture;
        iMaxIndex = aiMaxIndex;

        dotLeft = new Dot();
        dotLeft.vSize = new Vector2(iDotSize,iDotSize);
        dotLeft.vPosition = Vector2.zero;

        dotRight = new Dot();
        dotRight.vSize = new Vector2(iDotSize,iDotSize);
        dotRight.vPosition = Vector2.zero;

        fTimeBetweenMoves = afTimeBetweenMoves;

        controllerIndex = aGamepadIndex;
    }
Ejemplo n.º 11
0
    public void Init()
    {
        GamePads = new GamePad[1];

        GamePads[0] = new GamePad();

        GamePads[0].Keymap = new UnityButtonToSFKey[4];
        GamePads[0].Keymap[0] = new UnityButtonToSFKey("Fire1", SFKey.Code.A);
        GamePads[0].Keymap[1] = new UnityButtonToSFKey("Fire2", SFKey.Code.B);
        GamePads[0].Keymap[2] = new UnityButtonToSFKey("Fire3", SFKey.Code.X);
        GamePads[0].Keymap[3] = new UnityButtonToSFKey("Jump", SFKey.Code.Y);
        GamePads[0].ControllerIndex = 0;

        GamePads[0].Joysticks = new Joystick[1];
        GamePads[0].Joysticks[0] = new Joystick();
        GamePads[0].Joysticks[0].HorizontalAxisName = "Horizontal";
        GamePads[0].Joysticks[0].VerticalAxisName = "Vertical";
        GamePads[0].Joysticks[0].HorizontalAxisThresholdD = this.HorizontalAxisThresholdD;
        GamePads[0].Joysticks[0].VerticalAxisThresholdD = this.VerticalAxisThresholdD;
    }
Ejemplo n.º 12
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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }


            // TODO: Add your update logic here
            switch (gameState)
            {
            case GameStates.TitleScreen:
                KeyboardState kb = Keyboard.GetState();

                if (kb.IsKeyDown(Keys.Space))
                {
                    gameState = GameStates.Playing;
                }

                break;

            case GameStates.Playing:

                ball.Velocity += new Vector2(0, 55);

                MouseState ms  = Mouse.GetState();
                Vector2    clk = new Vector2(ms.X, ms.Y);

                if ((ms.LeftButton == ButtonState.Pressed && Vector2.Distance(clk, ball.Center) < ball.BoundingBoxRect.Width / 2 && ball.Velocity.Y > 0))
                {
                    ball.Velocity *= new Vector2(1, -1);
                    Vector2 move = ball.Center - clk;
                    move.Normalize();
                    move          *= 300;  // Scale the vector by the speed you want
                    move.Y         = -150; // Set the
                    ball.Velocity += move;
                    score++;
                }

                if (ball.Location.Y > this.Window.ClientBounds.Height - ball.BoundingBoxRect.Height)
                {
                    //ball.Velocity *= new Vector2(1, -1);
                    gameState = GameStates.Gameover;
                }

                // Enforce a maximum speed
                Vector2 vel   = ball.Velocity;
                float   speed = vel.Length();
                vel.Normalize();
                vel          *= MathHelper.Clamp(speed, 0, 1200);
                ball.Velocity = vel;

                ball.Update(gameTime);

                break;

            case GameStates.FailedAtLife:
                break;

            case GameStates.Gameover:

                break;
            }



            base.Update(gameTime);
        }
Ejemplo n.º 13
0
 public MainMenuState(Game game) : base(game)
 {
     this.gameOptions = new GameOptions();
     this.player1pad  = GamePad.GetState(PlayerIndex.One);
     game.Services.AddService(typeof(IMainMenuState), this);
 }
Ejemplo n.º 14
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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                menuManager.ChangePage(MenuManager.MenuState.Main);
                menuManager.gameStates    = GameStates.Menu;
                inGame.player.lifes       = 6;
                inGame.player.playerAlive = true;
                inGame.player.ResetGame();
            }
            // Toggle fullscreen when pressing F
            if (Keyboard.GetState().IsKeyDown(Keys.F))
            {
                graphics.IsFullScreen = !graphics.IsFullScreen;
                graphics.ApplyChanges();
            }

            switch (menuManager.gameStates)
            {
            case GameStates.Menu:
                menuManager.Update(gameTime);
                break;

            case GameStates.Game:
                inGame.Update(gameTime);
                if (inGame.player.playerAlive == false)
                {
                    SoundManager.Hurt.Play();
                    if (inGame.player.lifes <= 1)
                    {
                        menuManager.ChangePage(MenuManager.MenuState.GameOver);
                        menuManager.gameStates = GameStates.Menu;
                        inGame.player.lifes    = 6;
                    }
                    inGame.player.playerAlive = true;
                    inGame.player.ResetGame();
                }
                break;

            case GameStates.PreLevel1:
                InGame.Level           = InGame.Levels.preLevel1;
                InGame.Timer           = 0;
                menuManager.gameStates = GameStates.Game;
                break;

            case GameStates.PreLevel2:
                InGame.Level = InGame.Levels.preLevel1;
                // Set timer to 999999 which disables it. // Olle A 20-04-18
                InGame.Timer           = 999999;
                menuManager.gameStates = GameStates.Game;
                break;

            case GameStates.PreLevel3:
                InGame.Level = InGame.Levels.preLevel3;
                // Set timer to 999999 which disables it. // Olle A 20-04-18
                InGame.Timer           = 999999;
                menuManager.gameStates = GameStates.Game;
                break;

            case GameStates.PreLevel4:
                InGame.Level = InGame.Levels.preLevel4;
                // Set timer to 999999 which disables it. // Olle A 20-04-18
                InGame.Timer           = 999999;
                menuManager.gameStates = GameStates.Game;
                break;

            case GameStates.PreLevel5:
                InGame.Level = InGame.Levels.preLevel5;
                // Set timer to 999999 which disables it. // Olle A 20-04-18
                InGame.Timer           = 999999;
                menuManager.gameStates = GameStates.Game;
                break;

            case GameStates.PreLevel6:
                InGame.Level = InGame.Levels.preLevel6;
                // Set timer to 999999 which disables it. // Olle A 20-04-18
                InGame.Timer           = 999999;
                menuManager.gameStates = GameStates.Game;
                break;

            case GameStates.PreLevel7:
                InGame.Level = InGame.Levels.preLevel7;
                // Set timer to 999999 which disables it. // Olle A 20-04-18
                InGame.Timer           = 999999;
                menuManager.gameStates = GameStates.Game;
                break;

            case GameStates.PreLevel8:
                InGame.Level = InGame.Levels.preLevel8;
                // Set timer to 999999 which disables it. // Olle A 20-04-18
                InGame.Timer           = 999999;
                menuManager.gameStates = GameStates.Game;
                break;

            //case GameStates.InsertName:
            //    // Updates the various code in the nameselect class
            //    nameSelect.Update(gameTime);
            //    break;
            default:
                throw new ArgumentOutOfRangeException();
            }
            //if (menuManager.menuState == MenuManager.MenuState.GameOver || menuManager.menuState == MenuManager.MenuState.Victory)
            //    inGame.player.ResetGame();

            base.Update(gameTime);
        }
Ejemplo n.º 15
0
        public override void Update(GameTime gameTime)
        {
            var delta = Delta;

            var gamePad =
                GamePad.GetState(PlayerIndex.One);                 // TODO: Can this stuff be done effectively in the GamePadHandler?

            if (gamePad.IsConnected && gamePad.ThumbSticks.Left.Length() != 0)
            {
                delta = new Vector3(gamePad.ThumbSticks.Left.X, 0, gamePad.ThumbSticks.Left.Y);
            }

            var digging = Digging;

            if (gamePad.IsConnected && gamePad.Triggers.Right > 0.5f)
            {
                digging = true;
            }
            if (gamePad.IsConnected && gamePad.Triggers.Left > 0.5f && GamePadState.Triggers.Left < 0.5f)
            {
                var item = Game.Client.Inventory.Hotbar[Game.Client.HotBarSelection];
                Game.Client.QueuePacket(new PlayerBlockPlacementPacket(
                                            Game.HighlightedBlock.X, (sbyte)Game.HighlightedBlock.Y, Game.HighlightedBlock.Z,
                                            Game.HighlightedBlockFace, item.Id, item.Count, item.Metadata));
            }

            if (gamePad.IsConnected && Math.Abs(gamePad.ThumbSticks.Right.Length()) > 0)
            {
                var look = -(gamePad.ThumbSticks.Right * 8) * (float)(gameTime.ElapsedGameTime.TotalSeconds * 30);

                Game.Client.Yaw   -= look.X;
                Game.Client.Pitch -= look.Y;
                Game.Client.Yaw   %= 360;
                Game.Client.Pitch  = Microsoft.Xna.Framework.MathHelper.Clamp(Game.Client.Pitch, -89.9f, 89.9f);
            }

            if (digging)
            {
                if (Game.StartDigging == DateTime.MinValue)                 // Would like to start digging a block
                {
                    var target = Game.HighlightedBlock;
                    if (target != -Coordinates3D.One)
                    {
                        BeginDigging(target);
                    }
                }
                else                 // Currently digging a block
                {
                    var target = Game.HighlightedBlock;
                    if (target == -Coordinates3D.One)                     // Cancel
                    {
                        Game.StartDigging = DateTime.MinValue;
                        Game.EndDigging   = DateTime.MaxValue;
                        Game.TargetBlock  = -Coordinates3D.One;
                    }
                    else if (target != Game.TargetBlock)                     // Change target
                    {
                        BeginDigging(target);
                    }
                }
            }
            else
            {
                Game.StartDigging = DateTime.MinValue;
                Game.EndDigging   = DateTime.MaxValue;
                Game.TargetBlock  = -Coordinates3D.One;
            }

            if (delta != Vector3.Zero)
            {
                var lookAt = Vector3.Transform(-delta, Matrix.CreateRotationY(Microsoft.Xna.Framework.MathHelper.ToRadians(-(Game.Client.Yaw - 180) + 180)));

                lookAt.X *= (float)(gameTime.ElapsedGameTime.TotalSeconds * 4.3717);
                lookAt.Z *= (float)(gameTime.ElapsedGameTime.TotalSeconds * 4.3717);

                var bobbing = Game.Bobbing;
                Game.Bobbing += Math.Max(Math.Abs(lookAt.X), Math.Abs(lookAt.Z));

                Game.Client.Velocity = new Vector3(lookAt.X, Game.Client.Velocity.Y, lookAt.Z);

                if ((int)bobbing % 2 == 0 && (int)Game.Bobbing % 2 != 0)
                {
                    PlayFootstep();
                }
            }
            else
            {
                Game.Client.Velocity *= new Vector3(0, 1, 0);
            }

            if (Game.EndDigging != DateTime.MaxValue)
            {
                if (NextAnimation < DateTime.UtcNow)
                {
                    NextAnimation = DateTime.UtcNow.AddSeconds(0.25);
                    Game.Client.QueuePacket(new AnimationPacket(Game.Client.EntityId,
                                                                AnimationPacket.PlayerAnimation.SwingArm));
                }

                if (DateTime.UtcNow > Game.EndDigging && Game.HighlightedBlock == Game.TargetBlock)
                {
                    Game.Client.QueuePacket(new PlayerDiggingPacket(
                                                PlayerDiggingPacket.Action.StopDigging,
                                                Game.TargetBlock.X, (sbyte)Game.TargetBlock.Y, Game.TargetBlock.Z,
                                                Game.HighlightedBlockFace));
                    Game.EndDigging = DateTime.MaxValue;
                }
            }

            GamePadState = gamePad;
        }
        /// <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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            // TODO: Add your update logic here
            float horScaling = (float)graphics.PreferredBackBufferWidth / baseResolution.X;
            float verScaling = (float)graphics.PreferredBackBufferHeight / baseResolution.Y;

            scalingFactor = new Vector3(horScaling, verScaling, 1);

            mousePos = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
            if (sprites != null)
            {
                if (sprites.Count > 0)
                {
                    foreach (Sprite s in sprites)
                    {
                        s.Update(gameTime);
                    }
                    //sprites[0].Rotation += rotationSpeed;
                    data = sprites[0].OpaqueData;
                }

                if (sprites.Count > 1)
                {
                    //sprites[1].Rotation -= (float)(2.0 * Math.PI * gameTime.ElapsedGameTime.Milliseconds * 0.001);
                    sprites[1].Position = mousePos;
                    boundsCollide       = sprites[0].Bounds.Intersects(sprites[1].Bounds);
                    collision           = sprites[0].Collide(sprites[1]);
                    pointsOfCollision.Clear();
                    if (collision)
                    {
                        pointsOfCollision.AddRange(sprites[0].PointsOfCollision(sprites[1]));
                        if (sprites[0].Effect == null)
                        {
                            sprites[0].Effect = collideEffect;
                        }
                        //sprites[0].Effect.Parameters["Projection"].SetValue(Projection);
                        //sprites[0].Effect.Parameters["Time"].SetValue((float)gameTime.TotalGameTime.TotalSeconds);
                    }
                    else
                    {
                        sprites[0].Effect = null;
                    }
                }
            }

            milliseconds += gameTime.ElapsedGameTime.Milliseconds;
            if (milliseconds > 999)
            {
                seconds      += 1;
                milliseconds -= 1000;

                if (seconds > 59)
                {
                    minutes += 1;
                    seconds -= 60;
                }
            }

            base.Update(gameTime);
        }
Ejemplo n.º 17
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)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            switch (gameState)
            {
            case GameStates.TitleScreen:
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    this.Exit();      //exit the game if the back button is pressed from the titlescreen
                }
                if (isTapped(startGameButton))
                {
                    gameState = GameStates.Playing; //switch to the playing state if the start game button is tapped
                    ResetGame();                    //reset all game values to their starting values
                }
                else if (isTapped(howToButton))
                {
                    gameState = GameStates.HowTo;      //switch to the how to screen if the how to button is tapped
                }
                else if (isTapped(highScoresButton))
                {
                    gameState = GameStates.HighScores;      //switch to the high scores state if the high scores button is tapped
                }
                else if (isTapped(contactInfoButton))
                {
                    gameState = GameStates.ContactInfo;      //switch to the contact info state if the contact info button is tapped
                }
                else if (isTapped(myScoresButton))
                {
                    gameState = GameStates.MyScores;      //switch to the personal scores state if the my scores button is tapped
                }
                else if (isTapped(soundButton))
                {
                    if (SoundManager.PlaySounds)
                    {
                        SoundManager.PlaySounds = false;
                    }
                    else
                    {
                        SoundManager.PlaySounds = true;
                    }
                    ScoresData.soundOn = SoundManager.PlaySounds;
                    personalScoresSaver.SaveMyData(ScoresData, "LocalScores");
                }
                tapLocation = Vector2.Zero;      //reset the tap location before switching states!
                break;

            case GameStates.MyScores:
            case GameStates.ContactInfo:
            case GameStates.HowTo:
            case GameStates.HighScores:
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    gameState = GameStates.TitleScreen;      //go back to the title screen state if back is pressed on the above 4 cases
                }
                break;

            case GameStates.Paused:
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    gameState = GameStates.Playing;      //close the paused menu and go back into the game
                }
                else if (isTapped(noExit))
                {
                    gameState = GameStates.Playing;      //go back to the game
                }
                else if (isTapped(yesExit))
                {
                    gameState = GameStates.TitleScreen;      //go back to the title screen
                }
                tapLocation      = Vector2.Zero;
                bannerAd.Visible = true;
                break;

            case GameStates.GameOver:
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || isTapped(noScore))
                {
                    gameState        = GameStates.TitleScreen; //go back to the title screen if we press back or select not to submit score when the game is over
                    bannerAd.Visible = true;
                    ScoresData.AddScore(PlayerManager.Score);
                    personalScoresSaver.SaveMyData(ScoresData, "LocalScores");
                }
                else if (isTapped(yesScore))
                {
                    ScoresData.AddScore(PlayerManager.Score);
                    personalScoresSaver.SaveMyData(ScoresData, "LocalScores");
                    ShowKeyboard();         //show the keyboard if score is to be submitted
                }
                tapLocation = Vector2.Zero; //reset the tap location before switching states!
                break;

            case GameStates.Playing:
                //Update the player, items, and background while the game is playing
                bannerAd.Visible = false;      //turn off the ads while the game is playing
                PlayerManager.Update(gameTime);
                ItemManager.Update(gameTime);
                BackgroundManager.Update(gameTime);

                if (PlayerManager.PlayerDestroyed)
                {
                    gameState = GameStates.GameOver;      //if the player has fallen too far below the grass, switch to the game over state
                }
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    gameState = GameStates.Paused;      //open the paused menu if the back button is pressed during the game
                }
                break;
            }

            //Update ad banner every 30 secs and only if it's visible
            adDuration += elapsed;
            if (adDuration > 30 && bannerAd.Visible == true)
            {
                bannerAd.RequestNextAd();
                adDuration = 0;
            }

            base.Update(gameTime);
        }
Ejemplo n.º 18
0
 public static int GetAnyAxisDown(bool isHorizontal, GamePad pad = GamePad.One)
 {
     if (pad == GamePad.None) return 0;
     if (pad == GamePad.All)
     {
         int down = 0;
         foreach (var controller in controllers)
         {
             down = down + controller.GetAnyAxisDown(isHorizontal);
         }
         if (Mathf.Abs(down) > 1) down = down / Mathf.Abs(down);
         return down;
     }
     else
         return controllers[(int)pad].GetAnyAxisDown(isHorizontal);
 }
Ejemplo n.º 19
0
        public override void Update(GameTime gameTime)
        {
            EMenuInput new_input = EMenuInput.None;

            if (m_enabled)
            {
                GamePadState  gamePad  = GamePad.GetState(PlayerIndex.One);
                KeyboardState keyboard = Keyboard.GetState();

                if ((gamePad.ThumbSticks.Left.Y > 0.2f) ||
                    (gamePad.ThumbSticks.Right.Y > 0.2f) ||
                    (gamePad.DPad.Up == ButtonState.Pressed) ||
                    (keyboard.IsKeyDown(Keys.Up)))
                {
                    new_input = EMenuInput.Up;
                }
                else if ((gamePad.ThumbSticks.Left.Y < -0.2f) ||
                         (gamePad.ThumbSticks.Right.Y < -0.2f) ||
                         (gamePad.DPad.Down == ButtonState.Pressed) ||
                         (keyboard.IsKeyDown(Keys.Down)))
                {
                    new_input = EMenuInput.Down;
                }
                else if ((gamePad.Buttons.A == ButtonState.Pressed) ||
                         keyboard.IsKeyDown(Keys.Space) ||
                         keyboard.IsKeyDown(Keys.Enter))
                {
                    new_input = EMenuInput.Select;
                }
                else if ((gamePad.Buttons.B == ButtonState.Pressed) ||
                         (gamePad.Buttons.Back == ButtonState.Pressed) ||
                         keyboard.IsKeyDown(Keys.Escape) ||
                         keyboard.IsKeyDown(Keys.Back))
                {
                    new_input = EMenuInput.Back;
                }
                else if ((gamePad.Buttons.Start == ButtonState.Pressed) ||
                         keyboard.IsKeyDown(Keys.F1))
                {
                    new_input = EMenuInput.Start;
                }

                if (new_input == EMenuInput.None)
                {
                    // Nothing pressed. Reset the debounce so that tapping keys is still nice and fast.
                    m_debounce = 0;
                }
                else if (m_debounce == 0)
                {
                    // Register this reading
                    m_last_input = new_input;
                }
            }

            // Decay the debounce value. Ignore this new reading
            if (m_debounce > 0)
            {
                m_debounce -= gameTime.ElapsedGameTime.Milliseconds;
                if (m_debounce < 0)
                {
                    m_debounce = 0;
                }
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// GetAxisDownなどをする場合の閾値を設定するぞ!!
 /// デフォルトは迷ったけど0.8にしたぞ!!
 /// </summary>
 /// <param name="threshold"></param>
 public static void SetThreshold(double threshold, GamePad pad = GamePad.One)
 {
     if (pad == GamePad.None) return;
     if (pad == GamePad.All)
     {
         for (var i = 0; i < controllers.Count; i++)
         {
             controllers[i].SetThreshold(threshold);
         }
     }
     else
         controllers[(int)pad].SetThreshold(threshold);
 }
Ejemplo n.º 21
0
 public static bool GetButtonStayPeriodicly(Button button, GamePad pad = GamePad.One)
 {
     if (pad == GamePad.None) return false;
     if (pad == GamePad.All)
     {
         bool stay = false;
         foreach (var controller in controllers)
         {
             stay = stay || controller.GetButtonStayPeriodicly(button);
         }
         return stay;
     }
     else
         return controllers[(int)pad].GetButtonStayPeriodicly(button);
 }
Ejemplo n.º 22
0
 public static void SetSensitivity(double sensitivity,  GamePad pad = GamePad.One)
 {
     if (pad == GamePad.None) return;
     if (pad == GamePad.All)
     {
         for (var i = 0; i < controllers.Count; i++)
         {
             controllers[i].SetAxisSensitivity(sensitivity);
         }
     }
     else
         controllers[(int)pad].SetAxisSensitivity(sensitivity);
 }
Ejemplo n.º 23
0
    /// <summary>
    /// padで指定されたコントローラーのbutton_num番目のボタンを、buttonボタンに割り当てる
    /// </summary>
    /// <param name="pad"></param>
    /// <param name="button"></param>
    /// <param name="button_num">実際に押されるボタンの番号</param>
    public static void SetPadButton(GamePad pad, Button button, int button_num)
    {
        if (gamePads == null) InitializeGamePads();

        if((int)pad < (int)GamePad.All)
        {
            gamePads[(int)pad][button] = button_num;
        }
        else if(pad == GamePad.All)
        {
            for(var i = 0;i < (int)GamePad.All;i++)
            {
                gamePads[i][button] = button_num;
            }
        }

        SetGamePads();
    }
Ejemplo n.º 24
0
 public static void SetDead(double dead, GamePad pad = GamePad.One)
 {
     if (pad == GamePad.None) return;
     if (pad == GamePad.All)
     {
         for (var i = 0; i < controllers.Count; i++)
         {
             controllers[i].SetAxisDead(dead);
         }
     }
     else
         controllers[(int)pad].SetAxisDead(dead);
 }
Ejemplo n.º 25
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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            //  Background.SetRectangle(new Rectangle(0, 0, displayWidth, displayHeight));

            GamePadState  pad1 = GamePad.GetState(PlayerIndex.One);
            KeyboardState KB   = Keyboard.GetState();

            chosenBGpic = backgroundPic[0];
            chosenFOpic = flyingitemtex[0];
            numposition = rand.Next(GraphicsDevice.Viewport.Height - 50);

            /*// Move the bread
             * bread.X = bread.X + (bread.XSpeed * gamePad1.ThumbSticks.Left.X);
             * bread.Y = bread.Y - (bread.YSpeed * gamePad1.ThumbSticks.Left.Y);
             * bread.SpriteRectangle.X = (int)bread.X;
             * bread.SpriteRectangle.Y = (int)bread.Y;
             */
            {
                //if press thumbstick up then players y value increases
                if (KB.IsKeyDown(Keys.Up) || GamePad.GetState(PlayerIndex.One).ThumbSticks.Right.Y == 1.0f)
                {
                    //move up on screen
                    pan.spriteRectangle.Y--;
                }

                //if presses thumbstick down then players y value decreases
                if (KB.IsKeyDown(Keys.Down) || GamePad.GetState(PlayerIndex.One).ThumbSticks.Right.Y == -1.0f)
                {
                    //move down screen
                    pan.spriteRectangle.Y++;
                }


                if (flyingitem[level].Visible)
                {
                    noItems = false;
                }

                //
                if (pan.spriteRectangle.Intersects(flyingitem[level].spriteRectangle))
                {
                    if (health > 0)
                    {
                        health--;
                    }

                    flyingitem[level].Visible = false;

                    setupSprite(ref flyingitem[level], 0.05f, 1000, 0, numposition, true);

                    //  noItems = true;
                    // ENEMY COLLIDE
                }

                if (pan.spriteRectangle.Intersects(magic.spriteRectangle))
                {
                    score++;
                    magic.Visible = false;
                    setupSprite(ref magic, 0.05f, 100.0f, 0, numposition + 10, true);

                    // MAGIC COLLIDE
                }


                if (noItems)
                {
                    //resetItems;
                    //changes y position so flying objects arent coming out of same spot each time
                    flyingitem[level].spriteRectangle.Y = (int)flyingitem[level].Ypos + numposition;
                    //moving the objects
                    flyingitem[level].Xpos = flyingitem[level].Xpos + flyingitem[level].Xspeed;
                    flyingitem[level].spriteRectangle.X = (int)(flyingitem[level].Xpos + 0.5f);

                    flyingitem[level].Visible = true;
                }
                if (flyingitem[level].Xpos + flyingitem[level].spriteRectangle.Width >= GraphicsDevice.Viewport.Width)
                {
                    setupSprite(ref flyingitem[level], 0.05f, 1000, 0, numposition, true);

                    //  flyingitem[level].spriteRectangle.X = (int)flyingitem[level].Xpos;
                    // flyingitem[level].spriteRectangle.Y = (int)flyingitem[level].Ypos;
                }

                if (magic.Xpos + magic.spriteRectangle.Width >= GraphicsDevice.Viewport.Width)
                {
                    setupSprite(ref magic, 0.05f, 100.0f, 0, numposition, true);
                }
            }


            if (health <= 0)
            {
                return;
            }

            //moving the objects
            flyingitem[level].Xpos = flyingitem[level].Xpos + flyingitem[level].Xspeed;
            flyingitem[level].spriteRectangle.X = (int)(flyingitem[level].Xpos + 0.5f);

            //moving the magic fairy across the screen
            magic.Xpos = magic.Xpos + magic.Xspeed;
            magic.spriteRectangle.X = (int)(magic.Xpos + 0.5f);



            if (score >= 10)
            {
                level = 1;

                chosenBGpic = backgroundPic[level];
                chosenFOpic = flyingitemtex[level];
            }

            else if (score >= 20)
            {
                level = 2;

                chosenBGpic = backgroundPic[level];
                chosenFOpic = flyingitemtex[level];
            }
            else if (score >= 30)
            {
                level = 3;

                chosenBGpic = backgroundPic[level];
                chosenFOpic = flyingitemtex[level];
            }
            else if (score >= 40)
            {
                level = 4;

                chosenBGpic = backgroundPic[level];
                chosenFOpic = flyingitemtex[level];
            }
            else if (score >= 50)
            {
                level = 0;

                chosenBGpic = backgroundPic[level];
                chosenFOpic = flyingitemtex[level];
            }
            if (level > 4)
            {
                level = 0;
            }

            base.Update(gameTime);
        }
Ejemplo n.º 26
0
 private bool CanStartRitual(GamePad.Button button, out int ritualIndex)
 {
     ritualIndex = -1;
     for (int i = 0; i < RitualList.Count; i++)
     {
         if (RitualList[i][0] == button)
         {
             ritualIndex = i;
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 27
0
        public override void Update(GameTime gameTime)
        {
            float timeDelta = (float)(gameTime.ElapsedGameTime.Milliseconds / 1000.0f);

            keyboardState = Keyboard.GetState();
            mouseState    = Mouse.GetState();

#if WINDOWS
            int mouseX = mouseState.X;
            int mouseY = mouseState.Y;

            int midX = GraphicsDeviceManager.DefaultBackBufferHeight / 2;
            int midY = GraphicsDeviceManager.DefaultBackBufferWidth / 2;

            int deltaX = mouseX - midX;
            int deltaY = mouseY - midY;

            yaw(-(float)deltaX / 1000.0f);
            pitch(-(float)deltaY / 1000.0f);
            Mouse.SetPosition(midX, midY);
#elif WINDOWS_PHONE
            if (mouseState.LeftButton == ButtonState.Pressed)
            {
                int mouseX = mouseState.X;
                int mouseY = mouseState.Y;

                int midX = GraphicsDeviceManager.DefaultBackBufferHeight / 2;
                int midY = GraphicsDeviceManager.DefaultBackBufferWidth / 2;

                int deltaX = mouseX - midX;
                int deltaY = mouseY - midY;

                yaw(-(float)deltaX / 1000.0f);
                pitch(-(float)deltaY / 1000.0f);
                Mouse.SetPosition(midX, midY);
            }
#endif


            if (keyboardState.IsKeyDown(Keys.LeftShift))
            {
                timeDelta *= 20.0f;
            }

            if (keyboardState.IsKeyDown(Keys.W))
            {
                walk(timeDelta);
            }

            if (keyboardState.IsKeyDown(Keys.S))
            {
                walk(-timeDelta);
            }

            if (keyboardState.IsKeyDown(Keys.A))
            {
                strafe(-timeDelta);
            }

            if (keyboardState.IsKeyDown(Keys.D))
            {
                strafe(timeDelta);
            }

            GamePadState gpState = GamePad.GetState(PlayerIndex.One);
            l.X = -gpState.ThumbSticks.Left.X;
            l.Z = gpState.ThumbSticks.Left.Y;
            l.Y = 0;
            if (l.Length() > 0)
            {
                Look = Vector3.Normalize(l);
                walk(l.Length());
            }

            view       = Matrix.CreateLookAt(Position, Position + Look, Up);
            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), XNAGame.Instance.GraphicsDeviceManager.GraphicsDevice.Viewport.AspectRatio, 1.0f, 10000.0f);
        }
Ejemplo n.º 28
0
 private bool CanContinueRitual(GamePad.Button button, int ritualIndex, int ritualButtonIndex)
 {
     return RitualList[ritualIndex][ritualButtonIndex] == button;
 }
Ejemplo n.º 29
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)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            //Si se presiona el botón f1 instancia el form de ayuda, y cierra la ventana de simulación
            if (Keyboard.GetState().IsKeyDown(Keys.F1))
            {
                Ayuda form = new Ayuda();

                form.Show();
                form.Refresh();
                this.Exit();
            }
            // si se activa la simulación empieza a ejecutar el método UpDate de la entidad
            if (Iniciar.Pressed() && !active && ellapsedTimeButton > delayStartButton)
            {
                ellapsedTimeButton = 0;
                this.active        = true;
                Iniciar.input      = "pausar";
                int vx, vy, ax, ay;
                if (tbVelocidadX.input == "")
                {
                    vx = 0;
                }
                else
                {
                    vx = int.Parse(tbVelocidadX.input);
                }

                if (tbVelocidadY.input == "")
                {
                    vy = 0;
                }
                else
                {
                    vy = int.Parse(tbVelocidadY.input);
                }

                if (tbAceleracionX.input == "")
                {
                    ax = 0;
                }
                else
                {
                    ax = int.Parse(tbAceleracionX.input);
                }
                if (tbAceleracionY.input == "")
                {
                    ay = 0;
                }
                else
                {
                    ay = int.Parse(tbAceleracionY.input);
                }



                entity.Initialize(new Vector2(0, 150),
                                  new Vector2(vx, vy),
                                  new Vector2(ax, ay),
                                  new Rectangle(),
                                  0.0f);
                entity.InitializeHistory();
            }
            //Si se se presiona el botón PAUSAR, se reinicia el botón y se desactiva la simulación
            if (active && Iniciar.Pressed() && ellapsedTimeButton > delayStartButton)
            {
                this.active        = false;
                Iniciar.input      = "iniciar";
                ellapsedTimeButton = 0;
            }

            ellapsedTimeButton += gameTime.ElapsedGameTime.Milliseconds;

            if (active)
            {
                entity.Update(gameTime);
            }
            //text.input = i.ToString();
            //Si no está activa la simulación, permite abrir el buffer para la entrada de los datos a los text boxes.
            if (!active)
            {
                tbAceleracionX.TurnOnBuffer();
                tbAceleracionY.TurnOnBuffer();
                tbVelocidadX.TurnOnBuffer();
                tbVelocidadY.TurnOnBuffer();
            }

            //Si se presiona el botón de VER REPORTE, se instancia el form de reportes, y se cierra la ventana de simulación
            if (Reporte.Pressed() && !active && ellapsedTimeButton > delayStartButton)
            {
                ellapsedTimeButton = 0;
                form = new Reportes(entity.History);

                form.Show();
                form.Refresh();
                this.Exit();
            }

            // mousex.input = Mouse.GetState().X.ToString();
            //mousey.input = Mouse.GetState().Y.ToString();
            if (entity.position.X > 1300 || entity.position.Y > 950)
            {
                this.active        = false;
                Iniciar.input      = "iniciar";
                ellapsedTimeButton = 0;
            }
            base.Update(gameTime);
        }
Ejemplo n.º 30
0
 public NotJoinState(Cursol parent, GamePad pad)
     : base(parent)
 {
     gamePad = pad;
 }
Ejemplo n.º 31
0
 public SimpleGamePad(PlayerIndex playerNumber)
 {
     this.playerNumber   = playerNumber;
     lastGamePadState    = GamePad.GetState(playerNumber);
     currentGamePadState = GamePad.GetState(playerNumber);
 }
        public GamePad.Index whichController; // = GamePad.Index.One;

        #endregion Fields

        #region Constructors

        public PlayerBrain(GamePad.Index controllerIdx)
        {
            whichController = controllerIdx;
        }
Ejemplo n.º 33
0
 /// <summary>
 /// ボタンが離された瞬間だけtrueを返すぞ!!
 /// </summary>
 /// <param name="button"></param>
 /// <param name="controller">何番目のコントローラーか、0オリジンのデフォルト0</param>
 /// <returns></returns>
 public static bool GetButtonUp(Button button, GamePad pad = GamePad.One)
 {
     if (pad == GamePad.None) return false;
     if (pad == GamePad.All)
     {
         bool up = false;
         foreach (var controller in controllers)
         {
             up = up || controller.GetButtonUp(button);
         }
         return up;
     }
     else
         return controllers[(int)pad].GetButtonUp(button);
 }
Ejemplo n.º 34
0
 private List<Buttons> GetPressedButtons(GamePad pad)
 {
     GamePadComponent[] comps = GamePadComponent.RightTrigger.GetEnumValues<GamePadComponent>();
     List<Buttons> but = new List<Buttons>();
     foreach (GamePadComponent com in comps)
     {
         if (pad.IsButtonPressed(com))
         {
             but.Add(GamePad.Component2Button(com));
         }
     }
     return but;
 }
Ejemplo n.º 35
0
        public override void Update(GameTime gameTime, bool covered)
        {
            InputManager input   = ScreenManager.InputSystem;
            float        elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; // game time

            TotalElapsedTime  += elapsed;
            loadingScreenTime += elapsed;
            loadingCountTime   = (loadingScreenTime * 25);


            if (GameState == GameStates.Normal)
            {
                //
                //

                /*      Put all of your demostration stuff around here to allow it to run while the game
                 *      is not paused. Let me know if you have issues working out how this works and I
                 *      will get back to you ASAP       -       Shaun
                 */
                //
                //

                //Quit key
                KeyboardState keyboard = Keyboard.GetState();
                if (allownext == true)
                {
                    if ((GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) || keyboard.IsKeyDown(Keys.Enter))
                    {
                        Remove();
                        ScreenManager.AddScreen(new Demo01());
                    }
                }

                foreach (AnimatedSprite d in sprites.Sprites)
                {
                    d.Update(gameTime, viewportRect);                           // updates all sprites in list
                }


                // Only Update the game when the game is UNPAUSED
                base.Update(gameTime, covered);

                if (TotalElapsedTime >= KeyPressCheckDelay)
                {
                    if (input.MenuCancel)                                       // if escape is pressed
                    {
                        GameState        = GameStates.Paused;                   // pause game
                        TotalElapsedTime = 0.0f;
                        //ScreenManager.AddScreen(new DemoMenuOptions());       // display ingame menu
                    }
                }
            }
            else
            {
                if (TotalElapsedTime >= KeyPressCheckDelay)
                {
                    // UnPause the current game
                    if (input.MenuCancel || input.MenuSelect)                   // if escape or enter is pressed
                    {
                        GameState        = GameStates.Normal;                   // resume game
                        TotalElapsedTime = 0.0f;
                    }
                }
            }
        }
Ejemplo n.º 36
0
 /// <summary>
 /// ボタンが押された瞬間だけtrueを返すぞ
 /// </summary>
 /// <param name="button"></param>
 /// <param name="controller">何番目のコントローラーか、0オリジンのデフォルト0</param>
 /// <returns></returns>
 public static bool GetButtonDown(Button button, GamePad pad = GamePad.One)
 {
     if (pad == GamePad.None) return false;
     if (pad == GamePad.All)
     {
         bool down = false;
         foreach (var controller in controllers)
         {
             down = down || controller.GetButtonDown(button);
         }
         return down;
     }
     else
         return controllers[(int)pad].GetButtonDown(button);
 }
Ejemplo n.º 37
0
        private void processInput(float amount)
        {
            KeyboardState keyState = Keyboard.GetState();
            GamePadState  padState = GamePad.GetState(PlayerIndex.One);

            //arms
            leftArmRotX  = 0f;
            rightArmRotX = 0f;

            if (padState.IsConnected && padState.ThumbSticks.Left != Vector2.Zero && padState.ThumbSticks.Left.Y > 0)
            {
                updownRot = padState.ThumbSticks.Left.Y * 0.153f * -1f;
            }

            //downforce
            float downforce = ((float)Math.Sin(updownRot) * (-1f)) + 0.05f;

            moveSpeed = currentWing.Speed;

            //acceleration
            float leftAcceleration  = ((float)Math.Sin(updownRot) * -9.8f) + 0.25f;
            float rightAcceleration = ((float)Math.Sin(updownRot) * -9.8f) + 0.25f;
            float dragX             = 3f / 8f;

            //Keyboard
            if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
            {
                leftArmRotX      = -maxArmRot;
                leftAcceleration = 0;
            }
            if (keyState.IsKeyDown(Keys.Right) || keyState.IsKeyDown(Keys.D))
            {
                rightArmRotX      = -maxArmRot;
                rightAcceleration = 0;
            }
            if (keyState.IsKeyDown(Keys.R))
            {
                OculusClient.ResetSensorOrientation(0);
            }

            //gamepad
            if (padState.IsConnected && padState.Triggers.Left != 0)
            {
                leftArmRotX       = -maxArmRot * padState.Triggers.Left;
                leftAcceleration -= leftAcceleration * padState.Triggers.Left;
            }

            if (padState.IsConnected && padState.Triggers.Right != 0)
            {
                rightArmRotX       = -maxArmRot * padState.Triggers.Right;
                rightAcceleration -= rightAcceleration * padState.Triggers.Right;
            }

            if (padState.IsConnected && padState.Buttons.A == ButtonState.Pressed)
            {
                OculusClient.ResetSensorOrientation(0);
            }

            //Beveger glideren og henter ut rotasjon
            currentWing.move(wind, game.Terrain.getUpdraft(playerPosition), downforce, leftAcceleration, rightAcceleration, amount, dragX);
            lefrightRot += currentWing.getRotationY();
            rotZ         = currentWing.getRotationZ();

            Vector3 upDraft = new Vector3(0, 1, 0) * game.Terrain.getUpdraft(playerPosition);

            if (game.currentGameState == gameState.Playing)
            {
                AddToPlayerPosition(currentWing.getMovementVector() + (upDraft * amount));
            }

            UpdateViewMatrix();
        }
Ejemplo n.º 38
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)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            // TODO: Add your update logic here

            // create new view Matrix

            this.rotation += gameTime.ElapsedGameTime.TotalSeconds;
            //Console.WriteLine($"{rotation}");

            var ks = Keyboard.GetState();

            if (ks.IsKeyDown(Keys.Z))
            {
                xzPlaneViewAngle += 1 * gameTime.ElapsedGameTime.TotalSeconds;
            }
            if (ks.IsKeyDown(Keys.C))
            {
                xzPlaneViewAngle += -1 * gameTime.ElapsedGameTime.TotalSeconds;
            }

            Vector3 target = new Vector3((float)Math.Cos(xzPlaneViewAngle), 0, (float)Math.Sin(xzPlaneViewAngle));

            target.Normalize();

            Vector3 forward   = target;
            Vector3 backwards = -forward;

            Vector3 right = new Vector3(forward.Z, 0, -forward.X);
            Vector3 left  = -right;

            var movementVector = new Vector3();

            if (ks.IsKeyDown(Keys.W))
            {
                movementVector += forward;
            }
            if (ks.IsKeyDown(Keys.S))
            {
                movementVector += backwards;
            }
            if (ks.IsKeyDown(Keys.A))
            {
                movementVector += right;
            }
            if (ks.IsKeyDown(Keys.D))
            {
                movementVector += left;
            }

            if (ks.IsKeyDown(Keys.Q))
            {
                movementVector += new Vector3(0, 1, 0);
            }
            if (ks.IsKeyDown(Keys.E))
            {
                movementVector += new Vector3(0, -1, 0);
            }

            if (movementVector.LengthSquared() > 0f)
            {
                movementVector.Normalize();
            }
            movementVector *= 5.0f;

            this.cameraPosition += movementVector * (float)gameTime.ElapsedGameTime.TotalSeconds;


            // create target vector

            this.view = Matrix.CreateLookAt(this.cameraPosition, this.cameraPosition + 5f * target, Vector3.UnitY);

            base.Update(gameTime);
        }
Ejemplo n.º 39
0
        public void HandleInput()
        {
            // Get the status of input devices for the current frame, and store the values from last frame
            KeyboardPrevious = KeyboardCurrent;
            MousePrevious    = MouseCurrent;
            GamepadPrevious  = GamepadCurrent;
            KeyboardCurrent  = Keyboard.GetState();
            MouseCurrent     = Mouse.GetState();
            GamepadCurrent   = GamePad.GetState(PlayerIndex.One);

            PreviousKeyState = CurrentKeyState;
            CurrentKeyState  = KeyboardCurrent.GetPressedKeys();
            // All keys K are currently pressed in this frame
            // TODO make this actually send modifiers and keys at the same time
            InputStateEventArgs args = new InputStateEventArgs();

            ModifierKeys ModKey = ModifierKeys.None;

            foreach (Keys K in CurrentKeyState)
            {
                ModifierKeys MK = mapKeytoModifier(K);
                if (MK != ModifierKeys.None)
                {
                    ModKey |= MK;
                }
            }
            args.Modifier = ModKey;
            args.MousePos = MouseCurrent.Position;

            #region Mouse Movement
            Point mouseDiff = (MouseCurrent.Position - MousePrevious.Position);
            if (mouseDiff != new Point())
            {
                args.MouseDelta = mouseDiff;
                if (MouseMovement != null)
                {
                    MouseMovement(this, args);
                }
            }

            #endregion

            #region Keyboard inputs
            foreach (Keys K in CurrentKeyState)
            {
                args.Button = mapKeytoButton(K);
                if (KeyboardPrevious.IsKeyUp(K))
                {
                    if (ButtonPressed != null)
                    {
                        ButtonPressed(this, args);
                    }
                }
                if (KeyboardPrevious.IsKeyDown(K))
                {
                    if (ButtonHeld != null)
                    {
                        ButtonHeld(this, args);
                    }
                }
            }

            // This gets all the ButtonReleased events
            foreach (Keys K in PreviousKeyState)
            {
                if (KeyboardCurrent.IsKeyUp(K))
                {
                    args.Button = mapKeytoButton(K);
                    if (ButtonReleased != null)
                    {
                        ButtonReleased(this, args);
                    }
                }
            }
            #endregion

            #region Mouse inputs
            args.Button = AllButtons.MouseButtonLeft;
            if (MouseCurrent.LeftButton == ButtonState.Pressed && MousePrevious.LeftButton == ButtonState.Released)
            {
                if (ButtonPressed != null)
                {
                    ButtonPressed(this, args);
                }
            }
            else if (MouseCurrent.LeftButton == ButtonState.Pressed)
            {
                if (ButtonHeld != null)
                {
                    ButtonHeld(this, args);
                }
            }
            else if (MouseCurrent.LeftButton == ButtonState.Released && MousePrevious.LeftButton == ButtonState.Pressed)
            {
                if (ButtonReleased != null)
                {
                    ButtonReleased(this, args);
                }
            }

            args.Button = AllButtons.MouseButtonMiddle;
            if (MouseCurrent.MiddleButton == ButtonState.Pressed && MousePrevious.MiddleButton == ButtonState.Released)
            {
                if (ButtonPressed != null)
                {
                    ButtonPressed(this, args);
                }
            }
            else if (MouseCurrent.MiddleButton == ButtonState.Pressed)
            {
                if (ButtonHeld != null)
                {
                    ButtonHeld(this, args);
                }
            }
            else if (MouseCurrent.MiddleButton == ButtonState.Released && MousePrevious.MiddleButton == ButtonState.Pressed)
            {
                if (ButtonReleased != null)
                {
                    ButtonReleased(this, args);
                }
            }

            args.Button = AllButtons.MouseButtonRight;
            if (MouseCurrent.RightButton == ButtonState.Pressed && MousePrevious.RightButton == ButtonState.Released)
            {
                if (ButtonPressed != null)
                {
                    ButtonPressed(this, args);
                }
            }
            else if (MouseCurrent.RightButton == ButtonState.Pressed)
            {
                if (ButtonHeld != null)
                {
                    ButtonHeld(this, args);
                }
            }
            else if (MouseCurrent.RightButton == ButtonState.Released && MousePrevious.RightButton == ButtonState.Pressed)
            {
                if (ButtonReleased != null)
                {
                    ButtonReleased(this, args);
                }
            }
            // I feel dirty
            #endregion
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Update the ship.
        /// </summary>
        /// <param name="elapsedTime">The amount of elapsed time, in seconds.</param>
        public override void Update(float elapsedTime)
        {
            // process all input
            ProcessInput(elapsedTime, false);

            // if this player isn't in the game, then quit now
            if (playing == false)
            {
                return;
            }

            if (dead == true)
            {
            // if we've died, then we're counting down to respawning
                if (respawnTimer > 0f)
                {
                    respawnTimer = Math.Max(respawnTimer - elapsedTime, 0f);
                }
                if (respawnTimer <= 0f)
                {
                    Spawn(true);
                }
            }
            else
            {
                // apply drag to the velocity
                velocity -= velocity * (elapsedTime * dragPerSecond);
                if (velocity.LengthSquared() <= 0f)
                {
                    velocity = Vector2.Zero;
                }
                // decrement the heal timer if necessary
                if (shieldRechargeTimer > 0f)
                {
                    shieldRechargeTimer = Math.Max(shieldRechargeTimer - elapsedTime, 
                        0f);
                }
                // recharge the shields if the timer has come up
                if (shieldRechargeTimer <= 0f)
                {
                    if (shield < 100f)
                    {
                        shield = Math.Min(100f,
                            shield + shieldRechargePerSecond * elapsedTime);
                    }
                }
            }

            // update the weapons
            if (weapon != null)
            {
                weapon.Update(elapsedTime);
            }
            if (mineWeapon != null)
            {
                mineWeapon.Update(elapsedTime);
            }

            // decrement the safe timer
            if (safeTimer > 0f)
            {
                safeTimer = Math.Max(safeTimer - elapsedTime, 0f);
            }

            // update the radius based on the shield
            radius = (shield > 0f) ? 20f : 14f;

            // update the spawn-in timer
            if (fadeInTimer < fadeInTimerMaximum)
            {
                fadeInTimer = Math.Min(fadeInTimer + elapsedTime,
                    fadeInTimerMaximum);
            }

            // update and apply the vibration
            smallMotorTimer -= elapsedTime;
            largeMotorTimer -= elapsedTime;
            GamePad.SetVibration(playerIndex,
                (largeMotorTimer > 0f) ? largeMotorSpeed : 0f,
                (smallMotorTimer > 0f) ? smallMotorSpeed : 0f);
            
            base.Update(elapsedTime);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Read keyboard and gamepad input
        /// </summary>
        private void HandleInput(float elapsedTime)
        {
            previousGamePadState  = currentGamePadState;
            previousKeyboardState = currentKeyboardState;
            currentGamePadState   = GamePad.GetState(PlayerIndex.One);
            currentKeyboardState  = Keyboard.GetState();

            currentTouchCollection = TouchPanel.GetState();

            //bool touched = false;
            int touchCount = 0;

            // tap the screen to select
            foreach (TouchLocation location in currentTouchCollection)
            {
                switch (location.State)
                {
                case TouchLocationState.Pressed:
                    //touched = true;
                    touchCount++;
                    cursorLocation = location.Position;
                    break;

                case TouchLocationState.Moved:
                    break;

                case TouchLocationState.Released:
                    break;
                }
            }

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

            // Update the cursor location by listening for left thumbstick input on
            // the GamePad and direction key input on the Keyboard, making sure to
            // keep the cursor inside the screen boundary
            cursorLocation.X +=
                currentGamePadState.ThumbSticks.Left.X * cursorMoveSpeed * elapsedTime;
            cursorLocation.Y -=
                currentGamePadState.ThumbSticks.Left.Y * cursorMoveSpeed * elapsedTime;

            if (currentKeyboardState.IsKeyDown(Keys.Up))
            {
                cursorLocation.Y -= elapsedTime * cursorMoveSpeed;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Down))
            {
                cursorLocation.Y += elapsedTime * cursorMoveSpeed;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Left))
            {
                cursorLocation.X -= elapsedTime * cursorMoveSpeed;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Right))
            {
                cursorLocation.X += elapsedTime * cursorMoveSpeed;
            }
            cursorLocation.X = MathHelper.Clamp(cursorLocation.X, 0f, screenWidth);
            cursorLocation.Y = MathHelper.Clamp(cursorLocation.Y, 0f, screenHeight);

            // Change the tank move behavior if the user pressed B on
            // the GamePad or on the Keyboard.
            if ((previousGamePadState.Buttons.B == ButtonState.Released &&
                 currentGamePadState.Buttons.B == ButtonState.Pressed) ||
                (previousKeyboardState.IsKeyUp(Keys.B) &&
                 currentKeyboardState.IsKeyDown(Keys.B)) || (touchCount == 2))
            {
                tank.CycleBehaviorType();
            }

            // Add the cursor's location to the WaypointList if the user pressed A on
            // the GamePad or on the Keyboard.
            if ((previousGamePadState.Buttons.A == ButtonState.Released &&
                 currentGamePadState.Buttons.A == ButtonState.Pressed) ||
                (previousKeyboardState.IsKeyUp(Keys.A) &&
                 currentKeyboardState.IsKeyDown(Keys.A)) || (touchCount == 1))
            {
                tank.Waypoints.Enqueue(cursorLocation);
            }

            // Delete all the current waypoints and reset the tanks’ location if
            // the user pressed X on the GamePad or on the Keyboard.
            if ((previousGamePadState.Buttons.X == ButtonState.Released &&
                 currentGamePadState.Buttons.X == ButtonState.Pressed) ||
                (previousKeyboardState.IsKeyUp(Keys.X) &&
                 currentKeyboardState.IsKeyDown(Keys.X)) || (touchCount == 3))
            {
                tank.Reset(
                    new Vector2((float)screenWidth / 4, (float)screenHeight / 4));
            }
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Process the input for this ship, from the gamepad assigned to it.
        /// </summary>
        /// <param name="elapsedTime">The amount of elapsed time, in seconds.</param>
        /// <para
        public virtual void ProcessInput(float elapsedTime, bool overlayPresent)
        {
            currentGamePadState = GamePad.GetState(playerIndex);
            if (overlayPresent == false)
            {
                if (playing == false)
                {
                    // trying to join - update the a-button timer
                    if (currentGamePadState.Buttons.A == ButtonState.Pressed)
                    {
                        aButtonTimer += elapsedTime;
                    }
                    else
                    {
                        aButtonTimer = 0f;
                    }

                    // if the timer has exceeded the expected value, join the game
                    if (aButtonTimer > aButtonHeldToPlay)
                    {
                        JoinGame();
                    }
                }
                else
                {
                    // check if we're trying to leave
                    if (currentGamePadState.Buttons.B == ButtonState.Pressed)
                    {
                        bButtonTimer += elapsedTime;
                    }
                    else
                    {
                        bButtonTimer = 0f;
                    }
                    // if the timer has exceeded the expected value, leave the game
                    if (bButtonTimer > bButtonHeldToLeave)
                    {
                        LeaveGame();
                    }
                    else if (dead == false)
                    {
                        //
                        // the ship is alive, so process movement and firing
                        //
                        // calculate the current forward vector
                        Vector2 forward = new Vector2((float)Math.Sin(Rotation),
                            -(float)Math.Cos(Rotation));
                        Vector2 right = new Vector2(-forward.Y, forward.X);
                        // calculate the current left stick value
                        Vector2 leftStick = currentGamePadState.ThumbSticks.Left;
                        leftStick.Y *= -1f;
                        if (leftStick.LengthSquared() > 0f)
                        {
                            Vector2 wantedForward = Vector2.Normalize(leftStick);
                            float angleDiff = (float)Math.Acos(
                                Vector2.Dot(wantedForward, forward));
                            float facing = (Vector2.Dot(wantedForward, right) > 0f) ?
                                1f : -1f;
                            if (angleDiff > 0f)
                            {
                                Rotation += Math.Min(angleDiff, facing * elapsedTime *
                                    rotationRadiansPerSecond);
                            }
                            // add velocity
                            Velocity += leftStick * (elapsedTime * speed);
                            if (Velocity.Length() > velocityLengthMaximum)
                            {
                                Velocity = Vector2.Normalize(Velocity) *
                                    velocityLengthMaximum;
                            }

                        }
                        // check for firing with the right stick
                        Vector2 rightStick = currentGamePadState.ThumbSticks.Right;
                        rightStick.Y *= -1f;
                        if (rightStick.LengthSquared() > fireThresholdSquared)
                        {
                            weapon.Fire(Vector2.Normalize(rightStick));
                        }
                        // check for laying mines
                        if ((currentGamePadState.Buttons.B == ButtonState.Pressed) &&
                            (lastGamePadState.Buttons.B == ButtonState.Released))
                        {
                            // fire behind the ship
                            mineWeapon.Fire(-forward);
                        }
                    }
                }
            }

            // update the gamepad state
            lastGamePadState = currentGamePadState;
            return;
        }
Ejemplo n.º 43
0
 public void Update(GameTime gameTime)
 {
     prevState = currState;
     currState = GamePad.GetState(playerIndex);
 }
    private bool AnyButtonPressed(out GamePad.Button? button, out GamePad.Trigger? trigger)
    {
        // Trigger pressed threshold.
        const float triggerThreshold = .5f;
        // Defaults.
        button = null;
        trigger = null;
        // Check for buttons.
        if (GamePad.GetButtonDown(GamePad.Button.A, ControllerIndex))
        {
            button = GamePad.Button.A;
            return true;
        }
        if (GamePad.GetButtonDown(GamePad.Button.B, ControllerIndex))
        {
            button = GamePad.Button.B;
            return true;
        }
        if (GamePad.GetButtonDown(GamePad.Button.X, ControllerIndex))
        {
            button = GamePad.Button.X;
            return true;
        }
        if (GamePad.GetButtonDown(GamePad.Button.Y, ControllerIndex))
        {
            button = GamePad.Button.Y;
            return true;
        }
        if (GamePad.GetButtonDown(GamePad.Button.Back, ControllerIndex))
        {
            button = GamePad.Button.Back;
            return true;
        }
        if (GamePad.GetButtonDown(GamePad.Button.Start, ControllerIndex))
        {
            button = GamePad.Button.Start;
            return true;
        }
        if (GamePad.GetButtonDown(GamePad.Button.LeftShoulder, ControllerIndex))
        {
            button = GamePad.Button.LeftShoulder;
            return true;
        }
        if (GamePad.GetButtonDown(GamePad.Button.RightShoulder, ControllerIndex))
        {
            button = GamePad.Button.RightShoulder;
            return true;
        }

        // Check for triggers. // TODO Right now, if a trigger is held down before this method. It will think it was pressed.
        if (GamePad.GetTrigger(GamePad.Trigger.LeftTrigger, ControllerIndex) > triggerThreshold)
        {
            trigger = GamePad.Trigger.LeftTrigger;
            return true;
        }
        if (GamePad.GetTrigger(GamePad.Trigger.RightTrigger, ControllerIndex) > triggerThreshold)
        {
            trigger = GamePad.Trigger.RightTrigger;
            return true;
        }

        // No button pressed.
        return false;
    }
Ejemplo n.º 45
0
 public static bool ButtonPressed(Buttons button)
 {
     return(GamePad.GetState(0).IsButtonDown(button) && !prevGamePadState.IsButtonDown(button));
 }
Ejemplo n.º 46
0
 /// <summary>
 /// 軸の方向が変わった時だけ1か-1を返すぞ!!
 /// 例えば、右入力を離すと1を、左入力を離すと-1を返すぞ!!
 /// </summary>
 /// <param name="axis"></param>
 /// <param name="controller">軸の方向が変わった時だけ1か-1を返すぞ!!</param>
 /// <returns></returns>
 public static int GetAxisUp(Axis axis, GamePad pad = GamePad.One)
 {
     if (pad == GamePad.None) return 0;
     if (pad == GamePad.All)
     {
         int up = 0;
         foreach (var controller in controllers)
         {
             up = up + controller.GetAxisUp(axis);
         }
         if (Mathf.Abs(up) > 1) up = up / Mathf.Abs(up);
         return up;
     }
     else
         return controllers[(int)pad].GetAxisUp(axis);
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Handle controler and keyboad input to move the cat the camera and to allow
        /// the user to exit the sample
        /// </summary>
        private void HandleInput(GameTime gameTime)
        {
            float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            // Save current input states as the previous states for the next update.
            prevGamePadState  = currentGamePadState;
            prevKeyboardState = currentKeyboardState;

            //Get the new input states
            currentGamePadState  = GamePad.GetState(PlayerIndex.One);
            currentKeyboardState = Keyboard.GetState();

            // Allows the game to exit
            if (IsDown(Buttons.Back) || IsDown(Keys.Escape))
            {
                this.Exit();
            }

            // Allow the user to reset the camera and cat.
            if (IsTriggered(Buttons.LeftStick) ||
                IsTriggered(Buttons.RightStick) ||
                IsTriggered(Keys.R))
            {
                Reset();
            }

            // Allow the user to start and stop the IK simulation
            if (IsTriggered(Buttons.A) || IsTriggered(Keys.P))
            {
                runSimulation = !runSimulation;
            }

            // If the user presses B he/she want's to pause and step through
            // the simulation
            if (IsTriggered(Buttons.B) || IsTriggered(Keys.Space))
            {
                runSimulation = false;
            }

            // Allow the user to toggle single step mode
            if (IsTriggered(Buttons.Start) || IsTriggered(Keys.Enter))
            {
                singleStep = !singleStep;
            }

            // Handle input that will control the cat
            float   moveSpeed = .1f;
            Vector2 movement  = currentGamePadState.ThumbSticks.Left * moveSpeed;

            if (IsDown(Keys.W))
            {
                movement.Y += moveSpeed;
            }
            if (IsDown(Keys.S))
            {
                movement.Y -= moveSpeed;
            }
            if (IsDown(Keys.A))
            {
                movement.X -= moveSpeed;
            }
            if (IsDown(Keys.D))
            {
                movement.X += moveSpeed;
            }

            // Allow the cat to be moved toward and away from the center
            float zoom = 0;

            if (IsDown(Buttons.Y) || IsDown(Keys.Q))
            {
                zoom = .008f;
            }
            if (IsDown(Buttons.X) || IsDown(Keys.E))
            {
                zoom = -.008f;
            }

            // Update the radius and rotation angels of the cat
            movement.X    = -movement.X;
            cat.Position += new Vector3(movement, zoom * time);

            // Handle input that will control the camera
            moveSpeed = .1f;
            movement  = currentGamePadState.ThumbSticks.Right * moveSpeed;
            if (IsDown(Keys.Up))
            {
                movement.Y += moveSpeed;
            }
            if (IsDown(Keys.Down))
            {
                movement.Y -= moveSpeed;
            }
            if (IsDown(Keys.Left))
            {
                movement.X -= moveSpeed;
            }
            if (IsDown(Keys.Right))
            {
                movement.X += moveSpeed;
            }

            // Allow the camera to be zoomed in and out
            zoom  = 0;
            zoom += currentGamePadState.Triggers.Right * .01f;
            zoom -= currentGamePadState.Triggers.Left * .01f;
            if (IsDown(Keys.Z))
            {
                zoom = .007f;
            }
            if (IsDown(Keys.X))
            {
                zoom = -.007f;
            }

            // Update the rotation angles and radius of the camera
            cameraRotX   += movement.Y * time;
            cameraRotY   += movement.X * time;
            cameraRadius += zoom * time;
        }
Ejemplo n.º 48
0
 public static float GetAxisStayTime(Axis axis, GamePad pad = GamePad.One)
 {
     if (pad < GamePad.All)
     {
         return controllers[(int)pad].GetAxisStayTime(axis);
     }
     else
         return 0;
 }
Ejemplo n.º 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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            switch (gameState)
            {
            case GameStates.TitleScreen:
                if (Keyboard.GetState().IsKeyDown(Keys.Space))
                {
                    gameBoard.ClearBoard();
                    gameBoard.GenerateNewPieces(false);
                    playerScore         = 0;
                    currentLevel        = 0;
                    floodIncreaseAmount = 0.0f;
                    StartNewLevel();
                    gameState = GameStates.Playing;
                }
                break;

            case GameStates.Playing:
                timeSinceLastInput         += (float)gameTime.ElapsedGameTime.TotalSeconds;
                timeSinceLastFloodIncrease += (float)gameTime.ElapsedGameTime.TotalSeconds;

                if (timeSinceLastFloodIncrease >= timeBetweenFloodIncreases)
                {
                    floodCount += floodIncreaseAmount;
                    timeSinceLastFloodIncrease = 0.0f;
                    if (floodCount >= MaxFloodCounter)
                    {
                        gameOverTimer = 8.0f;
                        gameState     = GameStates.GameOver;
                    }
                }
                if (gameBoard.ArePiecesAnimating())
                {
                    gameBoard.UpdateAnimatedPieces();
                }
                else
                {
                    gameBoard.ResetWater();

                    for (int y = 0; y < GameBoard.GameBoardHeight; y++)
                    {
                        CheckScoringChain(gameBoard.GetWaterChain(y));
                    }

                    gameBoard.GenerateNewPieces(true);

                    if (timeSinceLastInput >= MinTimeSinceLastInput)
                    {
                        HandleMouseInput(Mouse.GetState());
                    }
                }
                UpdateScoreZooms();
                break;

            case GameStates.GameOver:
                gameOverTimer -= (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (gameOverTimer <= 0)
                {
                    gameState = GameStates.TitleScreen;
                }
                break;
            }

            base.Update(gameTime);
        }
Ejemplo n.º 50
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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            // TODO: Add your update logic here
            Global.MouseManager.Update(gameTime);
            Global.KeyboardManager.Update(gameTime);

            if (Global.KeyboardManager.IsKeyDown(Keys.LeftAlt) && Global.KeyboardManager.IsKeyPressedAndReleased(Keys.Enter))
            {
                Global.Graphics.ToggleFullScreen();
                if (graphics.IsFullScreen)
                {
                    Global.ScreenWidth  = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
                    Global.ScreenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;

                    Global.BoardScaleH *= Global.ScreenHeight / 480f;
                    Global.BoardScaleV *= Global.ScreenHeight / 480f;
                }
                else
                {
                    Global.BoardScaleH *= 480f / Global.ScreenHeight;
                    Global.BoardScaleV *= 480f / Global.ScreenHeight;

                    Global.ScreenWidth  = 640;
                    Global.ScreenHeight = 480;
                }
                Global.Graphics.ApplyChanges();
            }

            if (Global.KeyboardManager.IsKeyPressedAndReleased(Keys.Tab))
            {
                if (Global.ScreenWidth == 1200)
                {
                    Global.ScreenWidth  = 640;
                    Global.ScreenHeight = 480;
                    Global.BoardScaleH *= 640f / 1200;
                    Global.BoardScaleV *= 480f / 900;
                }
                else
                {
                    Global.ScreenWidth  = 1200;
                    Global.ScreenHeight = 900;
                    Global.BoardScaleH *= 1200f / 640;
                    Global.BoardScaleV *= 900f / 480;
                }
                Global.Graphics.ApplyChanges();
            }

            if (Global.KeyboardManager.IsKeyPressedAndReleased(Keys.PrintScreen))
            {
                Global.SceneManager.SaveSnapshot(gameTime);
            }

            Global.SceneManager.UpdateCurrentScene(gameTime);
            base.Update(gameTime);
        }
Ejemplo n.º 51
0
 public void StopVibrating()
 {
     GamePad.SetVibration(playerNumber, 0, 0);
     vibrationDuration = 0;
     vibratingTime     = 0;
 }
Ejemplo n.º 52
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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            // TODO: Add your update logic here

            switch (gameState)
            {
            case GameStates.TitleScreen:
                titleScreenTimer +=
                    (float)gameTime.ElapsedGameTime.TotalSeconds;

                if (titleScreenTimer >= titleScreenDelayTime)
                {
                    if ((Keyboard.GetState().IsKeyDown(Keys.Space)) ||
                        (GamePad.GetState(PlayerIndex.One).Buttons.A ==
                         ButtonState.Pressed))
                    {
                        playerManager.LivesRemaining = playerStartingLives;
                        playerManager.PlayerScore    = 0;
                        resetGame();
                        gameState = GameStates.Playing;
                    }
                }
                break;

            case GameStates.Playing:

                starField.Update(gameTime);
                asteroidManager.Update(gameTime);
                playerManager.Update(gameTime);
                enemyManager.Update(gameTime);
                explosionManager.Update(gameTime);
                collisionManager.CheckCollisions();

                if (playerManager.Destroyed)
                {
                    playerDeathTimer    = 0f;
                    enemyManager.Active = false;
                    playerManager.LivesRemaining--;
                    if (playerManager.LivesRemaining < 0)
                    {
                        gameState = GameStates.GameOver;
                    }
                    else
                    {
                        gameState = GameStates.PlayerDead;
                    }
                }

                break;

            case GameStates.PlayerDead:
                playerDeathTimer +=
                    (float)gameTime.ElapsedGameTime.TotalSeconds;

                starField.Update(gameTime);
                asteroidManager.Update(gameTime);
                enemyManager.Update(gameTime);
                playerManager.PlayerShotManager.Update(gameTime);
                explosionManager.Update(gameTime);

                if (playerDeathTimer >= playerDeathDelayTime)
                {
                    resetGame();
                    gameState = GameStates.Playing;
                }
                break;

            case GameStates.GameOver:
                playerDeathTimer +=
                    (float)gameTime.ElapsedGameTime.TotalSeconds;
                starField.Update(gameTime);
                asteroidManager.Update(gameTime);
                enemyManager.Update(gameTime);
                playerManager.PlayerShotManager.Update(gameTime);
                explosionManager.Update(gameTime);
                if (playerDeathTimer >= playerDeathDelayTime)
                {
                    gameState = GameStates.TitleScreen;
                }
                break;
            }

            base.Update(gameTime);
        }
 public void SetVibration(GamepadVibration vibration, GamepadIndex gamepad)
 {
     m_vibration[(int)gamepad] = vibration;
     GamePad.SetVibration(ToPlayerIndex(gamepad), vibration.LeftMotor, vibration.RightMotor);
 }
Ejemplo n.º 54
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)
        {
            #region PADCONTROL
            // Allows the game to exit
            if ((GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) ||
                Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                this.Exit();
            }

            /*if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed)
             *  colorin = Color.Green;
             * if (GamePad.GetState(PlayerIndex.One).Buttons.B == ButtonState.Pressed)
             *  colorin = Color.Red;
             * if (GamePad.GetState(PlayerIndex.One).Buttons.Y == ButtonState.Pressed)
             *  colorin = Color.Yellow;
             * if (GamePad.GetState(PlayerIndex.One).Buttons.X == ButtonState.Pressed)
             *  colorin = Color.Blue;
             * if (GamePad.GetState(PlayerIndex.One).Buttons.RightShoulder == ButtonState.Pressed)
             *  colorin = Color.Violet;
             * if (GamePad.GetState(PlayerIndex.One).Buttons.LeftShoulder == ButtonState.Pressed)
             *  colorin = Color.Purple;
             * if (GamePad.GetState(PlayerIndex.One).Buttons.Start == ButtonState.Pressed)
             *  colorin = Color.White;
             * if (GamePad.GetState(PlayerIndex.One).Triggers.Right == 1f)
             *  colorin = Color.Pink;
             * if (GamePad.GetState(PlayerIndex.One).Triggers.Left == 1f)
             *  colorin = Color.Orange;
             * /*     if (GamePad.GetState(PlayerIndex.One).DPad.Right == ButtonState.Pressed)
             *  colorin = Color.Orchid;
             * if (GamePad.GetState(PlayerIndex.One).DPad.Down == ButtonState.Pressed)
             *  colorin = Color.Maroon;
             * if (GamePad.GetState(PlayerIndex.One).DPad.Left == ButtonState.Pressed)
             *  colorin = Color.Gold;
             * if (GamePad.GetState(PlayerIndex.One).DPad.Up == ButtonState.Pressed)
             *  colorin = Color.Cyan;*/
            #endregion
            // TODO: Add your update logic here

            DoLogic();

            int            count         = 0;
            int            countInvasor  = 0;
            int            countComplete = 0;
            int            countShoot    = 0;
            int            countTank     = 0;
            List <Invasor> list          = new List <Invasor>();

            #region CONTADOR COMPONENTES
            foreach (GameComponent gc in Components)
            {
                if (gc is Background)
                {
                    count++;
                }
                if (gc is Shoot)
                {
                    countShoot++;
                }
                if (gc is Invasor)
                {
                    countInvasor++;
                    if (countInvasor == 1 &&
                        ((Invasor)gc).die)
                    {
                        // countInvasor = 0;
                        //    list.Add((Invasor)gc);
                    }
                }
                if (gc is Tank)
                {
                    countTank++;
                }
            }
            if (countTank == 0)
            {
                player = new Tank(this, ref tank, screen);
                Components.Add(player);
                player.PutinStartPosition();
            }

            if (count == 0)
            {
                Exit();
            }
            if (countInvasor == 0)
            {
                //countComplete++;
                countComplete = 1;
                invasorsManager.SheetInvaders(this, ref invasor);
                #region SELECT DIFFICULTY
                switch (countComplete)
                {
                case 1:
                {
                    invasorsManager.SelectDifficult(difficult.normal.ToString());
                    break;
                }

                case 2:
                {
                    invasorsManager.SelectDifficult(difficult.hard.ToString());
                    break;
                }

                default:
                {
                    invasorsManager.SelectDifficult(difficult.insane.ToString());
                    break;
                }
                }
                #endregion
            }

            #endregion

            if (ufoBonus)
            {
                UfoBonusYes();
            }

            base.Update(gameTime);
        }
Ejemplo n.º 55
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)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            newMousePoint = oldMousePoint;

            // TODO: Add your update logic here
            if (Mouse.GetState().LeftButton == ButtonState.Pressed)
            {
                newMousePoint = new Point(Mouse.GetState().X, Mouse.GetState().Y);
            }

            switch (state)
            {
            case GameState.MainMenu:
                t1 = new TimeSpan(0, 0, 0);
                //set state of the game based on button selected
                if (playRectangle.Contains(newMousePoint))
                {
                    state = GameState.PlayGame;
                }

                if (endRectangle.Contains(newMousePoint))
                {
                    state = GameState.EndGame;
                }

                if (helpRectangle.Contains(newMousePoint))
                {
                    state = GameState.HelpScreen;
                }

                if (choose_colorRectangle.Contains(newMousePoint))
                {
                    state = GameState.ChooseColor;
                }

                break;

            case GameState.HelpScreen:

                //go back to main menu if back button is clicked on
                if (backRectangle.Contains(newMousePoint))
                {
                    state = GameState.MainMenu;
                }

                break;

            case GameState.ChooseColor:

                if (yellowRectangle.Contains(newMousePoint))
                {
                    r             = 255; g = 255; b = 0;
                    colorSelected = true;
                }
                if (pinkRectangle.Contains(newMousePoint))
                {
                    r             = 252; g = 142; b = 172;
                    colorSelected = true;
                }
                if (redRectangle.Contains(newMousePoint))
                {
                    r             = 255; g = 0; b = 0;
                    colorSelected = true;
                }
                if (orangeRectangle.Contains(newMousePoint))
                {
                    r             = 255; g = 102; b = 0;
                    colorSelected = true;
                }
                if (greenRectangle.Contains(newMousePoint))
                {
                    g             = 255; r = 0; b = 0;
                    colorSelected = true;
                }
                if (aquaRectangle.Contains(newMousePoint))
                {
                    g             = 255; r = 0; b = 255;
                    colorSelected = true;
                }
                if (blueRectangle.Contains(newMousePoint))
                {
                    b             = 255; r = 0; g = 0;
                    colorSelected = true;
                }
                if (whiteRectangle.Contains(newMousePoint))
                {
                    b             = 255; r = 255; g = 255;
                    colorSelected = true;
                }

                if (colorSelected && (newMousePoint.X > 0 && newMousePoint.Y > 0))
                {
                    state         = GameState.MainMenu;
                    colorSelected = false;
                }

                break;

            case GameState.EndEndGame:
                if (endRectangle.Contains(newMousePoint))
                {
                    state = GameState.EndGame;
                }
                if (playRectangle2.Contains(newMousePoint))
                {
                    state = GameState.MainMenu;
                }
                gameTime.ElapsedGameTime.Negate();

                break;

            case GameState.PlayGame:
                Console.WriteLine(Mouse.GetState().X + " " + Mouse.GetState().Y);

                road1.Update();
                road2.Update();
                t1 += gameTime.ElapsedGameTime;
                if (road1.rectangle.X < (-1) * GraphicsDevice.Viewport.Width)
                {
                    road1.rectangle.X = GraphicsDevice.Viewport.Width;
                }

                if (road2.rectangle.X < (-1) * GraphicsDevice.Viewport.Width)
                {
                    road2.rectangle.X = GraphicsDevice.Viewport.Width;
                }
                playerRectangle = new Rectangle(playerRectangle.X, playerRectangle.Y, 150, 75);

                if (playerRectangle.Contains(newMousePoint))
                {
                    if (Mouse.GetState().LeftButton == ButtonState.Pressed)    //new feature - hard mode day one dlc
                    {
                        mousePressed = true;
                    }
                }

                if (mousePressed)
                {
                    playerRectangle.X = Mouse.GetState().X - 90;
                    playerRectangle.Y = Mouse.GetState().Y - 35;

                    if (playerRectangle.X >= GraphicsDevice.Viewport.Width - 150)
                    {
                        playerRectangle.X = GraphicsDevice.Viewport.Width - 150;
                    }
                    if (playerRectangle.X < 0)
                    {
                        playerRectangle.X = 0;
                    }
                    if (playerRectangle.Y >= GraphicsDevice.Viewport.Height - 75)
                    {
                        playerRectangle.Y = GraphicsDevice.Viewport.Height - 75;
                    }
                    if (playerRectangle.Y < 125)
                    {
                        playerRectangle.Y = 125;
                    }

                    if (Mouse.GetState().LeftButton == ButtonState.Released)
                    {
                        mousePressed = false;
                    }
                }

                //set location of top lines
                line1Rectangle.X  -= speedoflines;
                line1Rectangle2.X -= speedoflines;
                line1Rectangle3.X -= speedoflines;
                line1Rectangle4.X -= speedoflines;

                if (line1Rectangle.X < -100)
                {
                    line1Rectangle.X = GraphicsDevice.Viewport.Width - 50;
                }
                if (line1Rectangle2.X < -100)
                {
                    line1Rectangle2.X = GraphicsDevice.Viewport.Width - 50;
                }
                if (line1Rectangle3.X < -100)
                {
                    line1Rectangle3.X = GraphicsDevice.Viewport.Width - 50;
                }
                if (line1Rectangle4.X < -100)
                {
                    line1Rectangle4.X = GraphicsDevice.Viewport.Width - 50;
                }

                //set location of bottom lines
                line2Rectangle.X  -= speedoflines;
                line2Rectangle2.X -= speedoflines;
                line2Rectangle3.X -= speedoflines;
                line2Rectangle4.X -= speedoflines;

                if (line2Rectangle2.X < -100)
                {
                    line2Rectangle2.X = GraphicsDevice.Viewport.Width - 50;
                }
                if (line2Rectangle.X < -100)
                {
                    line2Rectangle.X = GraphicsDevice.Viewport.Width - 50;
                }
                if (line2Rectangle3.X < -100)
                {
                    line2Rectangle3.X = GraphicsDevice.Viewport.Width - 50;
                }
                if (line2Rectangle4.X < -100)
                {
                    line2Rectangle4.X = GraphicsDevice.Viewport.Width - 50;
                }

                //move the trees
                treeRectangle1.X -= speedoflines;
                treeRectangle2.X -= speedoflines;
                treeRectangle3.X -= speedoflines;
                treeRectangle4.X -= speedoflines;
                treeRectangle5.X -= speedoflines;

                //reset the trees
                if (treeRectangle1.X < -80)
                {
                    int test = rnd1.Next() % GraphicsDevice.Viewport.Width;
                    treeRectangle1.X = GraphicsDevice.Viewport.Width + test;
                }
                if (treeRectangle2.X < -80)
                {
                    int test = rnd1.Next() % GraphicsDevice.Viewport.Width;
                    treeRectangle2.X = GraphicsDevice.Viewport.Width + test;
                }
                if (treeRectangle3.X < -80)
                {
                    int test = rnd1.Next() % GraphicsDevice.Viewport.Width;
                    treeRectangle3.X = GraphicsDevice.Viewport.Width + test;
                }
                if (treeRectangle4.X < -80)
                {
                    int test = rnd1.Next() % GraphicsDevice.Viewport.Width;
                    treeRectangle4.X = GraphicsDevice.Viewport.Width + test;
                }
                if (treeRectangle5.X < -80)
                {
                    int test = rnd1.Next() % GraphicsDevice.Viewport.Width;
                    treeRectangle5.X = GraphicsDevice.Viewport.Width + test;
                }

                double x = t1.TotalSeconds;

                // make the cars move
                Lane4.X  += speedoflines + (int)(.06 * x) + 1;
                Lane4b.X += speedoflines + (int)(.06 * x) + 1;
                Lane3.X  += speedoflines + (int)(.08 * x) + 1;
                Lane2.X  -= speedoflines + (int)(.07 * x) + 1;
                Lane1.X  -= speedoflines + (int)(.06 * x) + 1;
                Lane1b.X -= speedoflines + (int)(.06 * x) + 1;



                if (playerRectangle.Intersects(Lane1) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(Lane1b) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(Lane2) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(Lane4b) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(Lane3) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(Lane4) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(treeRectangle1) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(treeRectangle2) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(treeRectangle3) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(treeRectangle4) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }
                if (playerRectangle.Intersects(treeRectangle5) && t1.TotalSeconds > 2)
                {
                    state = GameState.EndEndGame;
                }


                // Reset Cars
                if (Lane4.X > 2000)
                {
                    Lane4.X = -100;
                }
                if (Lane4b.X > 2000)
                {
                    Lane4b.X = -400;
                }
                if (Lane4.X == Lane4b.X)
                {
                    Lane4b.X -= 200;
                }
                if (Lane3.X > 2000)
                {
                    Lane3.X = -200;
                }
                if (Lane2.X < -200)
                {
                    Lane2.X = 2000;
                }
                if (Lane1.X < -200)
                {
                    Lane1.X = 2000;
                }
                if (Lane1b.X < -200)
                {
                    Lane1b.X = 2500;
                }
                if (Lane1.Intersects(Lane1b) || Lane1b.Intersects(Lane1))
                {
                    Lane1.X  += 100;
                    Lane1b.X -= 100;
                }

                if (Lane4.Intersects(Lane4b) || Lane4b.Intersects(Lane4))
                {
                    Lane4b.X -= 100;
                    Lane4.X  += 100;
                }
                break;

            case GameState.EndGame:

                if (backRectangle.Contains(newMousePoint))
                {
                    state = GameState.MainMenu;
                }

                break;
            }

            if (t1.Equals(100))
            {
                sec100.Play();
            }

            if (t1.Equals(130))
            {
                sec130.Play();
            }

            base.Update(gameTime);
        }
Ejemplo n.º 56
0
 public static float GetButtonStayTime(Button button, GamePad pad = GamePad.One)
 {
     if (pad < GamePad.All)
     {
         return controllers[(int)pad].GetButtonStayTime(button);
     }
     else
     {
         return 0;
     }
 }
    public void GotHit(Vector2 punchPosition, float damageM, GamePad.Index player, float pshake)
    {
        Vector3 punchDirection = Vector3.zero;
        if (punchPosition.x > transform.position.x)
            punchDirection.x = 1;
        else if (punchPosition.x < transform.position.x)
            punchDirection.x = -1;

        if (!isBlocking)
        {
            isHit = true;
            if (punchDirection.x >= .5 && Direction == Facing.LEFT)
                Flip();
            else if (punchDirection.x <= -.5 && Direction == Facing.RIGHT)
                Flip();
        }
        playerObject.rigidbody2D.AddForce(new Vector2(-punchDirection.x * maxVelocity.x * 8, maxVelocity.y / 3.5f));
        PunchShake(punchDirection, pshake, .4f, false);

        GameObject particles = Instantiate(Resources.Load("Prefabs/Objects/Particles/Particles_BloodAndGore"), transform.position - (punchDirection / 1.3f), Quaternion.identity) as GameObject;
        if (punchDirection.x == 1)
        {
            Vector3 rot = particles.transform.localEulerAngles;
            rot.z += 180;
            particles.transform.localEulerAngles = rot;
        }
        Destroy(particles.gameObject, 1f);


        if (!isBlocking && !IsDead && ((int)(1 * damageM)) >= health)
        {
            Damage((int)(1 * damageM));

            switch (player)
            {
                case GamePad.Index.One:
                    Global.leprechauns[0].gameObject.transform.parent.gameObject.GetComponent<Player>().kills += 1;
                    break;
                case GamePad.Index.Two:
                    Global.leprechauns[1].gameObject.transform.parent.gameObject.GetComponent<Player>().kills += 1;
                    break;
                case GamePad.Index.Three:
                    Global.leprechauns[2].gameObject.transform.parent.gameObject.GetComponent<Player>().kills += 1;
                    break;
                case GamePad.Index.Four:
                    Global.leprechauns[3].gameObject.transform.parent.gameObject.GetComponent<Player>().kills += 1;
                    break;
                default:
                    break;
            }
        }
        else if (!isBlocking && !IsDead)
            Damage((int)(1 * damageM));

    }
Ejemplo n.º 58
0
 protected override GamePadState GetCurrentState()
 {
     return(GamePad.GetState(PlayerIndex));
 }
Ejemplo n.º 59
0
    // Use this for initialization
    void Start()
    {
        pad = new GamePad(playerNumber);
        parent = new Player(playerNumber);
        parent.gamepad = pad;
        parent.team = new Team((TEAMCODE)playerNumber);

        sprite.color = new Color(1F, 1F, 1F, 0.7F);

        state = new NotJoinState(this, pad);
    }
Ejemplo n.º 60
0
 protected override void OnUpdate(GameTime gameTime)
 {
     _gamePadCapabilities = GamePad.GetCapabilities(PlayerIndex);
 }