Опубликован: 01.11.2011 | Доступ: свободный | Студентов: 1425 / 63 | Оценка: 3.84 / 3.44 | Длительность: 15:38:00
Специальности: Программист
Практическая работа 11:

Обработка жестов в XNA

Аннотация: Класс TouchPanel включает возможности распознавания жестов. В данной работе мы продемонстрируем возможности таких жестов, как Tap (касание), DoubleTap (двойное касание), Hold (удержание), Pinch (сведение), PinchComplete (сведение завершено), FreeDrag (произвольное перетягивание), HorizontalDrag (перетягивание по горизонтали), VerticalDrag (перетягивание по вертикали), DragComplete (перетягивание завершено). На данном занятии мы поработаем с жестам в XNA.

Дополнительные материалы к занятию можно скачать здесь.

В технологии XNA существует класс TouchPanel, позволяющий распознавать жесты, такие, как Tap (касание), DoubleTap (двойное касание), Hold (удержание), Pinch (сведение), PinchComplete (сведение завершено), FreeDrag (произвольное перетягивание), HorizontalDrag (перетягивание по горизонтали), VerticalDrag (перетягивание по вертикали), DragComplete (перетягивание завершено).

В предлагаемом примере приложение будет распознавать жест tap (касание). За основу был взят пример из книги Ч. Петзольда (2010).

Вначале мы создаем проект XNA Windows Phone 7. Проект назовем p11. После этого добавляем шрифт Lindsey:

<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">
    <FontName>Lindsey</FontName>
    <Size>48</Size>
    <Spacing>0</Spacing>
    <UseKerning>true</UseKerning>
    <Style>Bold</Style>
    <CharacterRegions>
      <CharacterRegion>
        <Start>&#32;</Start>
        <End>&#126;</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>
    

Вносим изменения в файл Game1.cs:

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 p11
{

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Random rand = new Random();
        string text = "Touch Me!";
        SpriteFont Lindsey;
        Vector2 textSize;
        Vector2 textPosition;
        Color textColor = Color.White;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            TargetElapsedTime = TimeSpan.FromTicks(333333);
        }


        protected override void Initialize()
        {

            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Lindsey = this.Content.Load<SpriteFont>("Lindsey");
            textSize = Lindsey.MeasureString(text);
            Viewport viewport = this.GraphicsDevice.Viewport;
            textPosition = new Vector2((viewport.Width - textSize.X) / 2,
            (viewport.Height - textSize.Y) / 2);
            TouchPanel.EnabledGestures = GestureType.Tap;
        }

        protected override void UnloadContent()
        {

        }

        protected override void Update(GameTime gameTime)
        {
            // Обеспечивает возможность выхода из игры
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gestureSample = TouchPanel.ReadGesture();
                if (gestureSample.GestureType == GestureType.Tap)
                {
                    Vector2 touchPosition = gestureSample.Position;
                    if (touchPosition.X >= textPosition.X &&
                    touchPosition.X < textPosition.X + textSize.X &&
                    touchPosition.Y >= textPosition.Y &&
                    touchPosition.Y < textPosition.Y + textSize.Y)
                    {
                        textColor = new Color((byte)(10), (byte)(50), (byte)(100));
                        text = "You've tapped!";
                    }
                    else
                    {
                        textColor = Color.White;
                    }
                }
            }
            base.Update(gameTime);
        }
        protected override void Draw(GameTime gameTime)
        {
            this.GraphicsDevice.Clear(Color.Coral);
            spriteBatch.Begin();
            spriteBatch.DrawString(Lindsey, text, textPosition, textColor);
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}
    
Листинг .

До прикосновения:


После прикосновения: