天天看點

XNA遊戲:手勢觸控

在XNA遊戲中使用到手勢觸控操作時,需要引入using Microsoft.Xna.Framework.Input.Touch; 

空間,在該空間下下面兩個類在觸控程式設計中會用到。

TouchLocation 用來儲存某一個觸摸點的狀态資訊。

TouchCollection 是儲存了目前所有觸控狀态(TouchLocation)的集合。

當我們把一個指頭在螢幕上操作,可能會有這樣三種動作:按,移動,移開。那麼這三個操作在WP7的XNA裡如何擷取呢?我們就需要了解XNA裡的TouchPanel和TouchCollection這兩個類

TouchCollection touchState= TouchPanel.GetState();  

       Foreach(TouchLocation location in touchState)  

       {  

               switch(location.State)  

               {  

                   case TouchLocationState.Pressed://按下  

                    ……  

                   break;  

       case TouchLocationState.Moved://移動  

       case TouchLocationState.Released://釋放  

       }  

       } 

TouchLocation :

State 觸摸狀态,包含4個狀态

> TouchLocationState.Pressed 表示螢幕被觸摸時手指按下的一瞬間

> TouchLocationState.Moved 表示手指按下後正在移動,經過測試可知,在手指按下的一瞬間State為Pressed ,在手指按下後擡起前這段時間内的狀态均是Moved

> TouchLocationState.Invalid 無效狀态

> TouchLocationState.Released 表示手指擡起的一瞬間

ID 表示目前觸摸事件的ID,一個完成的觸控事件的過程應該是“Pressed -> Moved -> Released ”在這個過程中ID是一緻的,用來在多點觸摸時區分觸摸的每個點。

Position 觸摸位置,包含兩個屬性

> X 目前觸摸位置的X軸坐标

> Y 目前觸摸位置的Y軸坐标

(橫屏全屏情況下,螢幕的左上角坐标為(0,0)右下角坐标為(800,480))

和觸控操作類似的還有叫“手勢”的,也算複雜的觸控吧。

TouchPanel.EnabledGestures = GestureType.FreeDrag;//用來指定手勢,必須要先設定,否則  

報錯  

if (TouchPanel.EnabledGestures != GestureType.None)  

{  

switch (TouchPanel.ReadGesture())  

case GestureType.Tap: //單擊  

break;  

case GestureType.DoubleTap://輕按兩下  

case GestureType.FreeDrag://自由拖動  

case GestureType.DragComplete://拖動完成  

case GestureType.Flick://輕彈  

case GestureType.Hold://按住不動  

case GestureType.HorizontalDrag://橫向拖動  

case GestureType.None://無手勢  

case GestureType.Pinch://捏  

case GestureType.PinchComplete://捏完  

case GestureType.VerticalDrag://縱向拖動  

}  

示例一各種手勢的測試:

using System;  

using System.Collections.Generic;  

using System.Linq;  

using Microsoft.Xna.Framework;  

using Microsoft.Xna.Framework.Audio;  

using Microsoft.Xna.Framework.Content;  

using Microsoft.Xna.Framework.GamerServices;  

using Microsoft.Xna.Framework.Graphics;  

using Microsoft.Xna.Framework.Input;  

using Microsoft.Xna.Framework.Input.Touch;  

using Microsoft.Xna.Framework.Media;  

namespace Gestures  

    /// <summary> 

    /// This is the main type for your game  

    /// </summary> 

    public class Game1 : Microsoft.Xna.Framework.Game  

    {  

        GraphicsDeviceManager graphics;  

        SpriteBatch spriteBatch;  

        SpriteFont spriteFont;  

        String message = "Do something";  

        Vector2 messagePos = Vector2.Zero;  

        Color color = Color.Black;  

        public Game1()  

        {  

            graphics = new GraphicsDeviceManager(this);  

            Content.RootDirectory = "Content";  

            // Frame rate is 30 fps by default for Windows Phone.  

            TargetElapsedTime = TimeSpan.FromTicks(333333);  

        }  

        /// <summary> 

        /// Allows the game to perform any initialization it needs to before starting to run.  

        /// This is where it can query for any required services and load any non-graphic  

        /// related content.  Calling base.Initialize will enumerate through any components  

        /// and initialize them as well.  

        /// </summary> 

        protected override void Initialize()  

            //添加各種手勢的支援  

            TouchPanel.EnabledGestures = GestureType.Tap | GestureType.DoubleTap | GestureType.Hold | GestureType.HorizontalDrag  

                | GestureType.VerticalDrag | GestureType.FreeDrag | GestureType.DragComplete | GestureType.Pinch  

                | GestureType.PinchComplete | GestureType.Flick;  

            base.Initialize();  

        /// LoadContent will be called once per game and is the place to load  

        /// all of your content.  

        protected override void LoadContent()  

            // Create a new SpriteBatch, which can be used to draw textures.  

            spriteBatch = new SpriteBatch(GraphicsDevice);  

            //記載字型資源  

            spriteFont = Content.Load<SpriteFont>("SpriteFont1");  

        /// UnloadContent will be called once per game and is the place to unload  

        /// all content.  

        protected override void UnloadContent()  

            // TODO: Unload any non ContentManager content here  

        /// Allows the game to run logic such as updating the world,  

        /// checking for collisions, gathering input, and playing audio.  

        /// <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();  

            //判斷手勢的類别  

            if (TouchPanel.IsGestureAvailable)  

            {  

                GestureSample gesture = TouchPanel.ReadGesture();  

                switch (gesture.GestureType)  

                {  

                    case GestureType.Tap:  

                        message = "That was a Tap";  

                        color = Color.Red;  

                        break;  

                    case GestureType.DoubleTap:  

                        message = "That was a Double Tap";  

                        color = Color.Orange;  

                    case GestureType.Hold:  

                        message = "That was a Hold";  

                        color = Color.Yellow;  

                    case GestureType.HorizontalDrag:  

                        message = "That was a Horizontal Drag";  

                        color = Color.Blue;  

                    case GestureType.VerticalDrag:  

                        message = "That was a Vertical Drag";  

                        color = Color.Indigo;  

                    case GestureType.FreeDrag:  

                        message = "That was a Free Drag";  

                        color = Color.Green;  

                    case GestureType.DragComplete:  

                        message = "Drag gesture complete";  

                        color = Color.Gold;  

                    case GestureType.Flick:  

                        message = "That was a Flick";  

                        color = Color.Violet;  

                    case GestureType.Pinch:  

                        message = "That was a Pinch";  

                    case GestureType.PinchComplete:  

                        message = "Pinch gesture complete";  

                        color = Color.Silver;  

                }  

                messagePos = gesture.Position;  

            }  

            base.Update(gameTime);  

        /// This is called when the game should draw itself.  

        protected override void Draw(GameTime gameTime)  

            GraphicsDevice.Clear(Color.CornflowerBlue);  

            //繪制螢幕的文字  

            spriteBatch.Begin();  

            spriteBatch.DrawString(spriteFont, message, messagePos, color);  

            spriteBatch.End();  

            base.Draw(gameTime);  

    }  

示例二多點觸控的測試:

namespace MultiTouchMe  

        TouchCollection touchCollection;  

            // TODO: Add your initialization logic here  

            // TODO: use this.Content to load your game content here  

            // TODO: Add your update logic here  

            touchCollection = TouchPanel.GetState();  

            // TODO: Add your drawing code here  

            foreach (TouchLocation touch in touchCollection)  

                spriteBatch.DrawString(spriteFont, "ID: " + touch.Id.ToString() + " (" +  

                    (int)touch.Position.X + "," + (int)touch.Position.Y + ")", touch.Position, Color.White);  

本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1078389

繼續閱讀