当前位置: 首页 > news >正文

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://移动
                     ……
                    break;

        case TouchLocationState.Released://释放
                     ……
                    break;

        }
        }


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://双击
break;
case GestureType.FreeDrag://自由拖动
break;
case GestureType.DragComplete://拖动完成
break;
case GestureType.Flick://轻弹
break;
case GestureType.Hold://按住不动
break;
case GestureType.HorizontalDrag://横向拖动
break;
case GestureType.None://无手势
break;
case GestureType.Pinch://
break;
case GestureType.PinchComplete://捏完
break;
case GestureType.VerticalDrag://纵向拖动
break;
}
}

示例一各种手势的测试:

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

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            //记载字体资源
            spriteFont = Content.Load<SpriteFont>("SpriteFont1");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

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

            //判断手势的类别
            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;
                        break;

                    case GestureType.Hold:
                        message = "That was a Hold";
                        color = Color.Yellow;
                        break;

                    case GestureType.HorizontalDrag:
                        message = "That was a Horizontal Drag";
                        color = Color.Blue;
                        break;

                    case GestureType.VerticalDrag:
                        message = "That was a Vertical Drag";
                        color = Color.Indigo;
                        break;

                    case GestureType.FreeDrag:
                        message = "That was a Free Drag";
                        color = Color.Green;
                        break;

                    case GestureType.DragComplete:
                        message = "Drag gesture complete";
                        color = Color.Gold;
                        break;

                    case GestureType.Flick:
                        message = "That was a Flick";
                        color = Color.Violet;
                        break;

                    case GestureType.Pinch:
                        message = "That was a Pinch";
                        color = Color.Violet;
                        break;

                    case GestureType.PinchComplete:
                        message = "Pinch gesture complete";
                        color = Color.Silver;
                        break;
                }

                messagePos = gesture.Position;
            }

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            //绘制屏幕的文字
            spriteBatch.Begin();
            spriteBatch.DrawString(spriteFont, message, messagePos, color);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

 

示例二多点触控的测试:


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 MultiTouchMe
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        SpriteFont spriteFont;
        TouchCollection touchCollection;

        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()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            spriteFont = Content.Load<SpriteFont>("SpriteFont1");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <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
            touchCollection = TouchPanel.GetState();

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin();

            foreach (TouchLocation touch in touchCollection)
                spriteBatch.DrawString(spriteFont, "ID: " + touch.Id.ToString() + " (" +
                    (int)touch.Position.X + "," + (int)touch.Position.Y + ")", touch.Position, Color.White);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

相关文章:

  • 基于corosync和pacemaker实现配置nginx的高可用集群
  • shell文本操作的实际应用
  • 分享memcache和memcached安装过程(转)
  • 域控服务器上安装Lync标准版记录
  • Sqlserver 数据库高级查询和设计
  • 麦肯锡:中国拥有3亿社交媒体用户为全球之最
  • ubuntu下面编译ffmpeg
  • 两个类相互包含对方成员的问题(2)
  • Python运算符重载
  • 五月规划
  • ubuntu 12.04 配置小记
  • java例程练习(图像编程[FramePanel])
  • C/C++左值性精髓(二)哪些表达式是左值,哪些是右值?--- 函数调用表达式和强制转换...
  • 图数据库现状简介
  • 为了不重复_nav
  • [ JavaScript ] 数据结构与算法 —— 链表
  • canvas绘制圆角头像
  • github指令
  • leetcode378. Kth Smallest Element in a Sorted Matrix
  • Linux CTF 逆向入门
  • Mocha测试初探
  • mockjs让前端开发独立于后端
  • mysql外键的使用
  • node入门
  • swift基础之_对象 实例方法 对象方法。
  • webpack4 一点通
  • 阿里云Kubernetes容器服务上体验Knative
  • 短视频宝贝=慢?阿里巴巴工程师这样秒开短视频
  • 分享几个不错的工具
  • 后端_ThinkPHP5
  • 记一次和乔布斯合作最难忘的经历
  • 精益 React 学习指南 (Lean React)- 1.5 React 与 DOM
  • 理解IaaS, PaaS, SaaS等云模型 (Cloud Models)
  • 如何优雅的使用vue+Dcloud(Hbuild)开发混合app
  • 微服务核心架构梳理
  • 用简单代码看卷积组块发展
  • FaaS 的简单实践
  • ​DB-Engines 11月数据库排名:PostgreSQL坐稳同期涨幅榜冠军宝座
  • ​软考-高级-系统架构设计师教程(清华第2版)【第1章-绪论-思维导图】​
  • ## 临床数据 两两比较 加显著性boxplot加显著性
  • (06)金属布线——为半导体注入生命的连接
  • (1)常见O(n^2)排序算法解析
  • (4.10~4.16)
  • (delphi11最新学习资料) Object Pascal 学习笔记---第7章第3节(封装和窗体)
  • (vue)el-checkbox 实现展示区分 label 和 value(展示值与选中获取值需不同)
  • (八)Flask之app.route装饰器函数的参数
  • (差分)胡桃爱原石
  • (二)springcloud实战之config配置中心
  • (欧拉)openEuler系统添加网卡文件配置流程、(欧拉)openEuler系统手动配置ipv6地址流程、(欧拉)openEuler系统网络管理说明
  • (三)mysql_MYSQL(三)
  • (四)Linux Shell编程——输入输出重定向
  • (转)Linux整合apache和tomcat构建Web服务器
  • .NET Micro Framework 4.2 beta 源码探析
  • .net 使用$.ajax实现从前台调用后台方法(包含静态方法和非静态方法调用)
  • .net 无限分类