XNA中编写的Zune HD Level程序(译文)
By robot-v1.0
本文链接 https://www.kyfws.com/games/zune-hd-level-program-written-in-xna-zh/
版权声明 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
- 25 分钟阅读 - 12217 个词 阅读量 0XNA中编写的Zune HD Level程序(译文)
原文地址:https://www.codeproject.com/Articles/42647/Zune-HD-Level-Program-Written-in-XNA
原文作者:Joel Ivory Johnson
译文由本站 robot-v1.0 翻译
前言
A level program written for the Zune using the XNA framework.
使用XNA框架为Zune编写的级别程序.
介绍(Introduction)
发布后的第二天,我收到了ZuneHD.所有的Zunes都可以通过XNA框架进行用户编程.因此,在"因为我能"类别中,我决定制作一个关卡程序.编写完程序后,我发现其他一些人想要源代码,并且知道如何在他们的计算机上获取XNA框架.我已经有一些关于编写以前的Zunes编程的文字,所以我接受了这些文字,并在其中添加了有关加速度计和多点触摸面板的一些信息,结果就是本文档.(I received a ZuneHD the day after release. All of the Zunes are user programmable via the XNA framework. So in the “Because I Can” category, I decided to make a level program. After making the program, I found that some others wanted the source code and know how to get the XNA framework on their computers. I already had some text that I had written on programming the previous Zunes, so I’ve taken that text, added some information on the accelerometer and multi-touch panel to it, and the result is this document.) 您可以在YouTube上观看实际水平的视频(You can see a video of the level in action on YouTube) 这里(here) .(.)
先决条件(Prerequisites)
要使用本文,您应该已经对.NET和C#基础概念有所了解.您还应该具有Windows窗体编程的经验.虽然此处显示的代码未使用Windows Forms命名空间(Zune不支持),但此处使用了在开发Windows Forms应用程序时可能遇到的一些概念(例如隔离存储).(To make use of this article, you should already have an understanding of .NET and C# foundational concepts. You should also have experience with Windows Forms programming. While the code presented here doesn’t make use of the Windows Forms namespace (it’s not supported on the Zune), some of the concepts that you may have encountered while developing Windows Forms applications (such as isolated storage) are used here.)
所需的软件和硬件(Required Software and Hardware)
要开始为Zune进行编程,您需要做一些事情:(To get started on programming for a Zune, there are a few things that you will need:)
- 运行Windows XP或更高版本的PC(PC running Windows XP or later)
- 带有2.5版或更高版本固件的Microsoft Zune(第一代或第二代)(Microsoft Zune (first or second gen) with version 2.5 or later firmware)
- XNA Game Studio 3.1((XNA Game Studio 3.1 () http://creators.xna.com/zh-CN/downloads(http://creators.xna.com/en-US/downloads) )())
- Visual Studio 2008或Visual Studio 2008 C#Express或更高版本(不支持Visual Basic!)((Visual Studio 2008 or Visual Studio 2008 C# Express or better (Visual Basic not supported!) () http://microsoft.com/express/download(http://microsoft.com/express/download) )())
- Zune软件((Zune software () http://Zune.net(http://Zune.net) )())
硬件变化(Hardware Variations)
在撰写本文时,可以使用三个Zune代.第一代Zune(也称为Zune 30)具有5向方向键,播放按钮和后退按钮.第二代Zunes提供多种容量,从4演出到120演出. 80和120 gig型号使用硬盘驱动器,而其他型号使用闪存.在这些Zunes上,四向方向键盘已由我最能形容为双模式鼠标键盘的内容所取代.可以将手指滑过垫子,也可以按手指以将其用作5向方向垫.方向键的区别不是主要的,但在设计用户交互时应注意它们;您将需要考虑两种硬件的差异. Zune系列的最新成员只有三个按钮(后退,电源和媒体控制按钮).它没有方向盘,但是有一个加速度计和多点触摸面板进行输入.屏幕最多支持4个同时触摸.(At the time of this writing, there are three Zune generations available. The first generation Zune (also known as the Zune 30) has a 5 way directional pad, a play button, and a back button. The second generation Zunes are available in a number of different capacities from 4 gigs to 120 gigs. The 80 and 120 gig models use hard drives while the others use flash memory. On these Zunes, the 4-way directional pad has been replaced by what I can best describe as being a dual-mode mouse pad. One can either slide a finger over the pad or press on it to use it as a 5-way directional pad. The differences in the directional pads aren’t major, but you should be aware of them when designing user interactions; you will need to account for both hardware variations. The latest addition to the Zune family has only three buttons (back, power, and a media control button). It lacks the directional pad, but has an accelerometer and multi-touch panel for input. The screen supports up to 4 simultaneous touches.)
重新启动Zune(Rebooting the Zune)
它将最终发生;您将编写一些使Zune陷入无限循环的代码,并且无法退出应用程序.如果按住返回按钮两秒钟,则该应用程序将退出.如果由于某种原因您无法退出,则也可以重新启动Zune.如果Zune有触摸板,请在按住方向键的同时按住返回按钮,如果有ZuneHD,则按住电源和后退按钮.几秒钟后,Zune将重新启动.(It’s going to happen eventually; you’ll write some code that gets the Zune stuck in an infinite loop and you have no way to exit your application. If you press and hold the back button for two seconds, the application will exit. If for some reason you are unable to exit, you can also reboot the Zune. Press and hold the back button while pressing up on the directional pad if your Zune has a touch pad, or hold down the power and back button if you have a ZuneHD. After a few seconds, the Zune will reboot.)
创建一个新的Zune项目(Creating a New Zune Project)
在Visual Studio中创建新的XNA项目时,可以将XBox 360,PC或Zune定位为目标.对于本文,我们将只关注Zune项目类型,而忽略其他类型. Zune项目类型包括" Zune游戏(3.1)“和” Zune游戏库(3.1)". (虽然很明显,Microsoft打算将这些项目类型用于游戏,但请记住,您不限于将这些项目类型用于游戏.如果您能想到Zune要做的其他一些生产力任务,那就是而不是游戏,请务必继续编写!)将" Zune Game(3.1)“项目类型像制作应用程序一样,而” Zune Game Library(3.1)“就像DLL.(When you create a new XNA project in Visual Studio, you can target the XBox 360, the PC, or the Zune. For this article, we will only be concerned with the Zune project types, and will ignore the others. The Zune project types include “Zune Game (3.1)” and the “Zune Game Library (3.1)”. (While it’s clear that Microsoft intends for these project types to be used for games, keep in mind that you aren’t limited to using them for that purpose. If you can think of some other productivity tasks that you want your Zune to do that’s not a game, by all means go ahead and write it!) Think of the “Zune Game (3.1)” project type being like making an application, while the “Zune Game Library (3.1)” is like a DLL.)
继续,在Visual Studio中为名为” Hello World"的Zune Game(3.1)项目创建一个新项目.该项目将自动包含许多存根方法.不用担心他们会做什么,我们将在以后进行检查.该程序只需要渲染矢车菊蓝色背景(微软最喜欢的颜色!).将您的Zune连接到您的计算机并运行该项目.您会得到一个错误.(Go ahead and create a new project in Visual Studio for a Zune Game (3.1) project called “Hello World.” The project will contain a number of stub methods automatically. Don’t worry about what they do, we will examine that later. This program does nothing more than render a cornflower blue background (Microsoft’s favourite colour!). Connect your Zune to your computer and run the project. You’ll get an error.)
No devices are available to deploy the project ‘HelloWorld’.
Register a device using the XNA Game Studio Device Center.
如果Zune客户端软件正在运行,请关闭它.一次只能将一个程序同步到Zune,如果正在运行,则在以下步骤中您将遇到失败.您可以在程序组的" Microsoft XNA Game Studio(3.1)“下找到” XNA Game Studio设备中心".启动程序,然后选择选项"添加设备".系统将询问您是否要添加Zune或XBox360.选择" Zune".您的Zune名称将显示出来,您可以选择它.选择"完成"后,返回Visual Studio并尝试再次运行您的项目.如果这是您第一次在Zune上运行XNA游戏,则将部署.NET Framework,然后部署您的应用程序.当应用程序运行时,您会看到屏幕变成矢车菊蓝色(此程序所做的一切).要退出程序,请按返回按钮.(If the Zune client software is running, close it. Only one program can sync to the Zune at a time, and if it is running, you’ll encounter failure in the following steps. You’ll find the “XNA Game Studio Device Center” under “Microsoft XNA Game Studio (3.1)” in the programs group. Start the program and select the option to “Add Device”. You’ll be asked whether you want to add a Zune or an XBox 360. Select “Zune”. Your Zune’s name will be displayed and you can select it. After you select “Finish”, go back to Visual Studio and try to run your project again. If this is your first time running an XNA game on your Zune, then the .NET Framework will deploy followed by your application. When the application runs, you’ll see the screen turn cornflower blue (which is all this program does). To exit the program, press down the back button.) 恭喜你!您已经编译并运行了第一个Zune应用程序.(Congratulations! You’ve compiled and run your first Zune application.)
分开申请(Taking the Application Apart)
我们的第一个程序做得并不多.我们将为其添加功能,但在此之前,让我们先进行分解.了解XNA应用程序的结构将有助于创建新的应用程序.(Our first program didn’t do much. We’ll add functionality to it, but before doing so, let’s take apart. Having an understanding of the structure of an XNA application will help in creating new applications.) Microsoft.Xna.Framework.Game
是XNA应用程序的基类.通过从此类派生然后覆盖其方法来创建应用程序. Visual Studio为我们生成的应用程序类为我们覆盖了五个方法:(is the base class for an XNA application. You create your application by deriving from this class and then overriding its methods. The application class generated for us by Visual Studio overrides five methods for us:)
Initialize
–包含初始化逻辑(– Contains the initialization logic)LoadContent
–之后直接致电(– Called directly after)Initialize
.(.)Update
–包含游戏的逻辑.(– Contains your game’s logic.)Draw
–包含应用程序的呈现代码.(– Contains the rendering code for your application.)Unload
–在应用程序退出之前释放所有资源(通常是内容).(– Releases any resources (usually content) before the application exits.) 的(The)Update
和(and)Draw
循环调用方法,直到应用程序终止.这些方法调用的图形表示如下所示:(methods are called cyclically until the application is terminating. A graphical representation of these method calls looks like the following:)
绘图/更新周期在第一代Zune上每秒最多发生60次,在第二代Zune上每秒最多发生30次(有关更多信息,请参见"硬件变化"部分).(The Draw/Update cycle will occur up to 60 times per second on the first generation Zune, and up to 30 times per second on the second generation Zune (for more information, see the Hardware Variation section).)
阅读按钮(Reading the Buttons)
XNA框架在设计时就考虑了XBox控制器. XBox控制器(和XNA)在XBox 360和PC上均可使用. Zune上的按钮已映射到某些XBox控制器按钮,因此您可以与XBox控制器进行交互的方式进行交互.(The XNA Framework was designed with the XBox controller in mind. The XBox controller (and XNA) are usable on both the XBox 360 and the PC. The buttons on the Zune are mapped to some of the XBox controller buttons so that you can interact with it in the same way that you would interact with an XBox controller.)
XBox 360控制器上的后退按钮映射到Zune上的后退按钮.在Zune HD上,这是屏幕正下方的按钮.在其他两个Zune型号上,这是方向键盘左侧的按钮.其他按钮均未映射到ZuneHD. XBox 360控制器上的A按钮映射到方向盘中央的Action按钮. B按钮映射到Zune上的"播放"按钮.对于原始的Zune,方向盘被映射为与XBox 360控制器上的4向方向盘一样.在第二代Zune上,如果用户按下Zune垫的边缘,则将其视为方向控制器.但是,如果用户在Zune垫的表面上移动手指,则将其与左操纵杆一样.(The back button on the XBox 360 controller is mapped to the back button on the Zune. On the Zune HD, this is the button directly under the screen. On the other two Zune models, this is the button to the left of the directional pad. None of the other buttons are mapped to the ZuneHD. The A button on the XBox 360 controller is mapped to the Action button in the center of the directional pad. The B button is mapped to the Play button on the Zune. For the original Zune, the directional pad is mapped to be treated like the 4-way directional pad on the XBox 360 controller. On the second generation Zune, if the user presses down on the edges of the Zune pad, it is treated as a directional controller. But, if the user moves a finger over the surface of the Zune pad, it will be treated the same as the left joy stick.)
现在,我已经介绍了按钮映射,接下来将讨论如何实际读取控制器.此信息适用于Zune(具有XBox 360控制器的PC),当然也适用于XBox 360上的XNA.用于与控制器进行交互的主要类是(Now that I’ve covered the button mappings, I’ll talk about how to actually read the controller. This information is true for the Zune, a PC with an XBox 360 controller, and of course, for XNA on the XBox 360. The main class used for interacting with the controller is the) GamePad
类.这是一个静态类,几乎所有方法都需要一个枚举类型的变量(class. It’s a static class, and almost all of the methods require an enumerated variable of type) PlayerIndex
.的(. The) PlayerIndex
枚举具有值(enumeration has the values) One
,(,) Two
,(,) Three
和(, and) Four
.该数字用于标识一个控制器要与之交互.仅对于Zune,(. This number is used to identify which controller one wishes to interact with. For Zune only,) PlayerIndex.One
已验证.(is valid.)
游戏手柄(GamePad)
像许多XNA类一样,(Like many of the XNA classes, the) GamePad
类有一个名为(class has a method named) GetCapabilities
为您提供有关控制器功能的信息.如果我没有提到上面的按钮映射,(that gives you information on the capabilities of the controller. Had I not mentioned the button mappings above, the) GamePadCapabilities
此方法返回的对象会通知您存在哪些按钮映射.的(object returned by this method would have informed you which button mappings were present. The) GamePad
另一个感兴趣的方法是(’s other method of interest is the) GetState
方法.它将返回控制器中所有按钮和方向输入的状态.(method. It will return the state of all of the buttons and directional inputs on the controller in a) GamePadState
目的.的(object. The) Buttons
的成员(member of the) GamePadState
对象有一组(object has a group of) ButtonState
其值可以是(members whose value can be) Pressed
要么(or) Released
(如果不存在按钮,则其状态始终为((if a button is not present, then its state is always) Released
).的(). The) ThumbSticks
成员包含两个(member contains two) Vector2
成员命名(members named) Left
和(and) Right
.的(. The) Right
成员永远不会对Zune感兴趣,但是(member will never have anything of interest on the Zune, but the) Left
成员将通知您用户正在ZunePad上触摸的位置.(member will inform you of the position on the ZunePad that the user is touching.)
我在示例程序中使用的Zune上唯一的按钮是"后退"按钮,用于退出程序.(The only button on the Zune that I use in the example program is the Back button for exiting the program.)
将您的Zune连接到Visual Studio(Connecting your Zune to Visual Studio)
您需要将Zune指定为XNA可以定位的设备.首先将您的Zune连接到计算机.为了将程序部署到您的Zune,Visual Studio(或Visual Studio Express)将需要能够通过XNA Game Studio连接器与Zune通信.必须安装Zune软件,以确保存在正确的Zune驱动程序.但是,如果Zune软件在PC上运行,则Visual Studio无法与Zune通信.确保它没有打开.启动XNA Game Studio连接器,然后选择选项以(You’ll need to designate your Zune as a device that XNA can target. Start by connecting your Zune to the computer. In order to deploy programs to your Zune, Visual Studio (or Visual Studio Express) will need to be able to communicate with the Zune through the XNA Game Studio Connector. The Zune software must be installed to ensure the proper drivers are present for the Zune. However, Visual Studio cannot communicate with the Zune if the Zune software is running on the PC. Make sure that it isn’t open. Start the XNA Game Studio Connector, and select the option to)添加设备(Add Device).您可以选择添加XBox 360或Zune.选择(. You’ll be given an option to add an XBox 360 or a Zune. Select)Zune(Zune)然后单击下一步.(and click Next.)
如果您的Zune连接到计算机,则它将列为您可以定位的设备.选择它,然后单击下一步.另一个屏幕会询问您是否要将此Zune设置为默认Zune.您可以安全地保留此选项的默认值,然后单击"下一步"完成该过程.对您要添加的任何其他Zune重复相同的过程.(If your Zune is connected to the computer, then it will be listed as a device you can target. Select it and click Next. Another screen will ask you if you would like to set this Zune to be the default Zune. You can safely leave this option with its default value, and click Next to complete the process. Repeat the same process for any other Zune you would like to add.)
完成一个或多个Zunes的过程后,XNA Game Studio设备中心将显示您的所有Zunes.奇怪的是,ZuneHD的显示图标与Zune80/120相同. Zune30和Zune4显示正确的图标.(After you’ve completed the process for one or more Zunes, the XNA Game Studio Device Center will display all of your Zunes. Oddly enough, the ZuneHD is displayed with the same icon as the Zune80/120. The Zune30 and Zune4 display with the correct icons.)
显示文字(Displaying Text)
在XNA Game Studio for Zune的版本3之前,如果要在屏幕上绘制文本,则必须加载一组字母图像,并有选择地从字体图像到屏幕绘制部分.从3.1版开始,其中的某些流程已由(Before version 3 of XNA Game Studio for Zune, if you wanted to draw text on the screen, you had to load a set of images of the letters and selectively draw sections from your font image to the screen. As of the 3.1 version, some of this process has been automated by the) SpriteMap
类.我们将更新HelloWorld程序,以便显示时间.为了显示时间,我们首先需要将字体导入我们的应用程序.然后,我们必须使用该字体来呈现文本.(class. We are going to update our HelloWorld program so that it will display the time. To display the time, we first need to import a font into our application. Then, we must use that font to render text.)
要导入字体,请执行以下操作:(To import a font, do the following:)
-
右键单击项目的"内容"区域,然后选择"添加新项".(Right-click on the “Content” area of the project and select “Add New Item”.)
-
选择(Select)
SpriteFont
作为新项目类型,然后输入(as the new item type, and enter)MyFont.spritemap
作为名称.(as the name.) -
XML文件打开.在里面(An XML file opens. In the)
<FontName>
该文件的元素,用您要使用的字体名称替换文本. (可选)更改字体大小和间距的设置.(element of this file, replace the text with the name of the font you want to use. Optionally, change the settings for the font size and spacing.) -
在里面(In the)
CharacterRegion
区域,确保(area, ensure that the)Start
和(and)End
元素设置为要包含在您的Unicode字符范围内(elements are set to the range of Unicode characters that are to be included in your)SpriteFont
.(.) 现在,使用字体:(Now, to use the font :) -
添加类型的新成员(Add a new member of type)
SpriteFont
作为应用程序的成员.命名(as a member of the application. Name it)MyFont
.(.) -
在里面(In the)
LoadContent
方法,键入以下内容:(method, type the following:) -
替换内容(Replace the contents of the)
Draw
方法如下:(method with the following:) -
运行程序.(Run the program.) 程序运行时,它将显示当前日期和时间,直到第二秒为止.您可以随时按"后退"按钮退出程序.(When the program runs, it will display the current date and time up to the second. You can exit the program at any time by pressing the Back button.) 请注意以下几点:字体(如软件)是知识产权,并且由于潜在的版权侵权,您可能无法使用某些字体.还要注意,字体和其他资源一样会占用空间.只要有可能,就严格限制仅包括程序使用的字体的字符范围.(A few words of warning: Fonts, like software, are intellectual property, and you may not be able to use certain fonts because of potential copyright infringement. Also note that fonts, like any other resource, take up space. Whenever possible, strictly limit the character range of fonts included only to those that your program will use.)
显示内容(Displaying Content)
使用Zune上的XNA可以显示许多不同的文件格式.我建议在大多数情况下使用PNG.这是您可以使用的图像格式的详尽列表:(There are a number of different file formats that can be displayed using XNA on the Zune. I would suggest using PNG in most cases. Here is a non-exhaustive list of the image formats that you can use:)
-
骨形态发生蛋白(BMP)
-
JPG格式(JPG)
-
PNG(PNG)
-
PPM(PPM) 当前的Zunes都具有240x320或272x480的分辨率.调整资源大小时,请记住这一点.由于我们才刚刚起步,因此我想简化图像的操作.我想使用已有的程序并将图像加载到后台.我将使用(The current Zunes all have a resolution of 240x320 or 272x480. Keep that in mind when sizing resources. Since we are just getting started, I want to keep my operations with images simple. I want to take the program that I already have and load an image into the background. I’ll be using a)
Texture
对象来处理我的图像.使用任何绘画编辑器,创建尺寸为240x320的图像.将图片添加到您项目的(object to handle my image. Using any paint editor, create an image of size 240x320. Add the image to your project’s)**内容(Content)**夹. XNA Game Studio将自动使其成为纹理类型的内容资源.我将图片命名为"(folder. The XNA Game Studio will automatically make it a content resource of type texture. I named my image “)Background.png(Background.png)".一旦添加到项目中,应应用以下代码更改:(”. Once added to the project, the following code changes should be applied:) -
添加类型的成员(Add a member of type)
Texture
到应用程序类.命名(to the application class. Name it)MyTexture
.(.) -
在里面(In the)
LoadContent
方法,添加以下内容:(method, add the following:) -
在里面(In the)
Draw()
方法,删除对(method, erase the call to)Clear()
.(.) -
使用以下代码作为方法中的呈现代码:(Use the following as the rendering code in the method:) 现在,当您运行该程序时,您将看到时间的背景.(Now, when you run the program, you will see your background behind the time.)
条件编译(Conditional Compiling)
可以在Zune,XBox 360和PC之间共享相同的源代码.但是,XNA的某些方面特定于这些设备中的每一个.条件编译可用于保留单个代码库,而在不支持它们的平台上不使用功能.对于Zune项目,将定义ZUNE符号.(It is possible to share the same source code between the Zune, XBox 360, and PC. However, there are aspects of XNA that are specific to each of these devices. Conditional compiling can be used to keep a single code base while not using features on platforms that don’t support them. For Zune projects, the ZUNE symbol is defined.)
#if ZUNE
局限性(Limitations)
与为许多其他移动设备进行编程一样,对于Zune,您必须记住,您所使用的编程资源与台式机开发所用的资源不同.在XNA程序中,您将被限制为16 MB的RAM,并且ZuneHD上的屏幕大小为272x480,其他Zunes上的屏幕大小为240x320.另外,Zunes上的颜色深度为16位.(Like programming for many other mobile devices, for the Zune, you must remember that you are not programming with the same resources that you would have when developing for a desktop. In an XNA program, you will be limited to 16 megabytes of RAM, and the screen size will be 272x480 on the ZuneHD, or 240x320 on the other Zunes. Also, the colour depth on the Zunes is 16-bit.) 由于Zune没有键盘或鼠标,因此如果您尝试查询Zune上这些设备中任何一个的状态,您会发现它们始终报告没有按键被按下,并且鼠标的X和Y值始终为零. .(Since the Zune has no keyboard or mouse, if you try to query the states of either of these devices on the Zune, you will find that they always report that no keys are being pressed and the X and Y values for the mouse are always zero.)
与加速度计交互(Interacting with the Accelerometer)
当前,ZuneHD是唯一支持加速度计的XNA平台.如果您是一般性地编写代码(以便可以在PC,XBox 360和Zune的变体上运行),那么您将希望能够检测您是否在具有加速度计的设备上运行.您可以从适当命名的加速度计中获得所有想要了解的有关加速度计的信息.(Currently, ZuneHD is the only XNA platform that supports the accelerometer. If you are writing your code generically (so that it will run on a PC, XBox 360, and variations of the Zune), then you’ll want to be able to detect whether or not you are running on a device that has an accelerometer. You can get all the information that you want to know about the accelerometer from the appropriately named) Accelerometer
类.的(class. The) Accelerometer
该类是静态的,因此您可以立即开始使用它.的(class is static so you can immediately begin using it. The) GetCapabilities
方法将通过以下方式让您知道是否有加速度计(method will let you know whether or not an accelerometer is present through the) IsConnected
的成员(member of the) AccelerometerCapabilities
它返回的实例.的(instance that it returns. The) AccelerometerCapabilities
该班还有三名成员((class also has three members () HasXAxis
,(,) HasYAxis
,(,) HasZAxis
),这表明在将来的某个时刻可能存在无法检测到所有三个平面上的加速度的设备.我可以看到以这种方式实现了方向盘类型的界面.可以通过以下方式查询设备加速度检测的极限值:() that suggest at some point in the future there could exist devices that don’t detect accelerations along all three planes. I could see a steering wheel type interface being implemented in that manner. The limits of the device’s acceleration detection can be queried through the) AccelerationResolution
和(and the) MaximumAcceleration
和(and) MinimumAcceleration
价值观.(values.)
要读取加速度计的状态,请使用(To read the state of the accelerometer, use the) GetState
的方法(method of the) Accelerometer
类.它返回一个(class. It returns an) AccelerometerState
目的.该实例包含一个名为的布尔属性(object. The instance contains a Boolean property named) IsConnected
让您知道是否存在加速度计,并且(that lets you know whether or not an accelerometer is present, and a) Vector3
实例,可以告诉您加速度计沿X轴,Y轴和Z轴的读数.(instance that tells you the readings of the accelerometer along the X-axis, Y-axis, and Z-axis.)
与触摸屏互动(Interacting with the Touch Panel)
触摸屏是该程序的次要组件.如果按屏幕上后退按钮的图标,则它将退出.此程序中未以任何其他方式使用触摸面板.但是使用触摸面板类似于使用游戏手柄或加速计.您有一个带有(The touch panel is a minor component of this program. If you press the icon of the back button on the screen, then it will exit. The touch panel is not used in any other way in this program. But using the touch panel is similar to using the game pad or the accelerometer. You have a static class with a) GetCapabilities
方法(用于检测硬件是否可用),以及(method (for detecting whether or not the hardware is available), and a) GetState
读取硬件实际状态的方法.您可能会注意到,我一直将表面称为触摸面板而不是触摸屏.从理论上讲,触摸表面不必在屏幕上.考虑一下鼠标垫或数位板,它们都是一种触摸表面,但不在屏幕上.术语"触摸面板"更多地涵盖了将来可能添加到XNA支持中的其他类型的触摸表面.(method for reading the actual state of the hardware. You may notice that I keep referring to the surface as a touch panel instead of a touch screen. In theory, the touch surface does not have to be on the screen. Think of a mouse pad or a pen tablet, both of which are touch surfaces of a type but are not on the screen. The term “Touch Panel” is more encompassing of other types of touch surfaces that could be added to XNA support in the future.)
静态类名为(The static class is named) TouchPanel
.的(. The) TouchCapabilities
由其返回的对象(object returned by its) GetCapabilities
方法有一个名为(method has a member named) IsConnected
通知您是否有触摸屏,以及(to inform you whether or not a touch panel is available, and) MaxTouchCount
通知您面板可以检测到多少触摸.的(to inform you how many touches the panel can detect. The) TouchPanel
的(’s) GetState
方法返回一个(method returns a) TouchCollection
目的.的(object. The) TouchCollection
包含清单(contains a list of) TouchLocation
除其他事项外,还包含坐标(如(s that, among other things, contains the coordinates (as a) Vector2
)触摸屏幕上的区域. ZuneHD上的触摸面板最多可以检测到四个触摸,因此该成员中最多不能包含四个成员.() of the areas on the screen being touched. The touch panel on the ZuneHD can detect up to four touches, so this member will never have more than four members in it.)
对于附带的程序,我仅检查是否有任何躺椅点与出口按钮相交.此处未以其他任何方式使用触摸.(For the attached program, I only check to see if any of the couch points are intersecting the exit button. Touch is not used in any other way here.)
重现气泡水平(Remaking the Bubble Level)
规划设计(Planning and Design)
似乎对于任何装有加速度计的移动设备,您都可以找到气泡水平仪程序.这是具有加速度计功能的非官方" Hello World"应用程序.因此,按照传统,我为ZuneHD编写了一个气泡级程序.该程序的创建从一张方格纸开始.我标记了一个矩形,该矩形可以缩放到ZuneHD的272x480屏幕,然后用它来决定可视元素的布局方式.我想要水平,垂直和圆形.这是我想到的布局:(It seems that for any mobile device with an accelerometer out there, you can find a bubble level program. It’s the unofficial “Hello World” app of devices with accelerometer capabilities. So in sticking with tradition, I’ve written a bubble level program for my ZuneHD. The creation of the program started off on a sheet of graph paper. I marked off a rectangle that was to scale for the ZuneHD’s 272x480 screen, and then used it to decide how the visual elements would be laid out. I wanted to have a horizontal level, a vertical level, and a circular level. This is the layout that I came out with:)
现在,我知道所需的布局,可以开始创建图形资产了.由于草图是按比例绘制的,因此我可以用它来确定我的每项资产的确切尺寸.由于我只计划对该程序投资不超过几个小时,所以我想将这些图形快速组合在一起.但是同时,我也不想让它们看起来很糟.因此,我使用Expressions Design来快速组合所需的图形.几年前,我已经从个人项目中保存了刷过的金属图像,所以我重复使用了它.得到的图像资产如下:(Now that I knew the desired layout, I could begin creating my graphical assets. Since the sketch was drawn to scale, I could use it to decide on the exact sizes for each one of my assets. Since I had only planned to invest no more than a couple of hours into this program, I wanted to put the graphics together quickly. But at the same time, I didn’t want them to look bad. So, I used Expressions Design to quickly put together the graphics I needed. I already had a brushed metal image saved from a personal project from years ago, so I reused it. The resulting image assets follow:)
图形已作为内容添加到程序中.我还为内容添加了字体,以便可以呈现文本.有了所有需要的资产后,下一步就是编写代码.但是在编写代码之前,需要了解一些数学知识.(The graphics were added as content to the program. I also added a font to the content so that I could render text. With all of the needed assets present, the next step was to write the code. But before writing the code, some math needs to be understood.)
加速度计如何工作?(How Does an Accelerometer Work?)
加速度计可测量设备相对于自由落体所经历的加速度.换句话说,它测量的是设备的加速度减去物体所承受的重力.(An accelerometer measures the acceleration that a device experiences relative to freefall. In other words, it measures a device’s acceleration minus the force of gravity that the object is experiencing.)
的(The) Accelerometer
类返回一个(class returns a) Vector3
包含X,Y和Z组件的对象,可用于描述设备的方向.对于固定设备,这三个数字描述的向量的长度将接近于一.如果你还记得(object that contains an X, Y, and Z component that can be used to describe the orientation of the device. For a stationary device, the vector described by these three numbers will have a length close to one. If you remember the) 勾股定理(Pythagorean theorem) (通常以((which is usually written in the form of)
),那么您还将意识到x * x + y * y + z * z大约等于1.如果将ZuneHD正面朝上放在水平表上,则加速度计读数将为{X :0,Y:0,Z:-1}.如果将本机正面朝下放置,则加速度计读数将为{X:0,Y:0,Z:1}.如果我将Zune放在地板上,左侧在天花板上,那么矢量将接近{X:-1,Y:0,Z:0}.如果我将ZuneHD放在桌子上,并开始向左或向右倾斜,那么随着X轴上的读数增大,沿Z轴的读数将开始减小.这可能很难可视化.因此,我鼓励您运行本文随附的" AccelerometerTestTest"程序,以了解加速度计对运动的响应.(), then you’ll also realize that this means that xx+yy+zz will be equal to about 1. If I place the ZuneHD face-up on a level table, the accelerometer reading would be {X:0, Y:0, Z:-1}. If I place the unit face down, the accelerometer reading would be {X:0, Y:0, Z:1}. If I stand the Zune up with its left side on the floor and the right side on the ceiling, then the vector gets close to {X:-1, Y:0, Z:0}. If I have the ZuneHD flat on a table and begin to tilt it to the left or right, then then the reading along the Z-axis will begin to decrease in magnitude as the reading on the X-axis increases in magnitude. This may be difficult to visualize. So, I encourage you to run the program “AccelerometerTest” that is included with this article to get a feel for the accelerometer’s response to movement.*)
Zune放在一边,屏幕上显示加速度计读数.(Zune laying on its side with the accelerometer reading on the screen.)### 程序背后的数学(The Math Behind the Program)
因此,既然有了加速度计的读数,我们就需要能够将其更改为一个角度.如果您记得三角函数,那么您可能还记得,反正切函数可用于从X和Y坐标获取角度.但是在开始沿着这条路走之前,我们需要记住,我们有三个坐标,而不是两个.此外,反正切函数无法区分某些位置的角度.反正切函数有第二种形式,通常标记为(So now that we have the accelerometer’s reading, we need to be able to change it to an angle. If you remember your trigonometry, then you may recall that the arctangent function can be used to get an angle from an X and a Y coordinate. But before we start going down this trail, we need to keep in mind that we have three coordinates, not two. Also, the arctangent function can’t distinguish between the angles of some positions. There is a second form of the arctangent function, usually labeled) arctan2
,具有我们需要的功能.(, that has the functionality that we need.)
Vector3 accelReading = accelState.Acceleration;
tiltDirection = (float)Math.Atan2(accelReading.Y, accelReading.X);
tiltMagnitude = (float)Math.Sqrt(accelReading.X * accelReading.X +
accelReading.Y * accelReading.Y );
现在我有了倾斜方向和幅度,我需要能够将其转换为气泡指示器的X和Y位移.使用正弦和余弦轻松完成.(Now that I have the tilt direction and the magnitude, I need to be able to translate that into X and Y displacements for the bubble indicators. Easily done using sine and cosine.) Math.Sin(tiltAngle)
会将我的角度转换为1到-1之间的水平位移.(will convert my angle to a horizontal displacement between 1 and -1.) -Math.Cos(tiltAngle)
也会将角度转换为介于1和-1之间的位移.我可以获取这些函数的结果并将其按比例放大以适合气泡指示器所要允许的最大位移.(will convert the angle to a displacement between 1 and -1 also. I can take the results of these functions and scale them up to fit into the maximum displacement that I want to allow for the bubble indicators.)
Rectangle horizontalBubbleRectangle =
new Rectangle((int)(118 + 102 * tiltMagnitude * -
Math.Cos(tiltDirection)), 22, 36, 36);
Rectangle verticalBubbleRectangle =
new Rectangle(22, (int)(80 + 140 + 124 * tiltMagnitude *
Math.Sin(tiltDirection )), 36, 36);
Rectangle smallBubbleArea = new Rectangle(156 +
(int)(48*tiltMagnitude * -Math.Cos(tiltDirection )), 156 +
(int)(48 *tiltMagnitude* Math.Sin(tiltDirection )), 8, 8);
这就是所有需要的计算.一旦完成,剩下的就是将对象放在屏幕上.(That is all the computation that is needed. Once that is done, all that is left is placing the objects on the screen.)
spriteBatch.Begin();
spriteBatch.Draw(ProgramBackground, backgroundTextureArea, Color.White);
spriteBatch.Draw(HorizontalLevelTexture, horizontalLevelTextureArea, Color.White);
spriteBatch.Draw(VerticalLevelTexture, verticalLevelTextureArea, Color.White);
spriteBatch.Draw(RoundLevelTexture, roundLevelTextureArea, Color.White);
spriteBatch.Draw(BubbleTexture, horizontalBubbleRectangle, Color.White);
spriteBatch.Draw(BubbleTexture, verticalBubbleRectangle, Color.White);
spriteBatch.Draw(SmallBubbleTexture, smallBubbleArea, Color.White);
spriteBatch.Draw(BackArrowTexture, BackArrowPosition, Color.White);
spriteBatch.DrawString(MainFont, "J2i.net", siteAddressPosition, Color.Blue);
spriteBatch.End();
定义游戏图标(Defining the Game Icon)
我跳过的一件事是如何为游戏定义图标.创建项目时,它会添加一个名为(The one thing I skipped over is how to define an icon for the game. When you create the project, it adds a file named)**GameThumbnail.png(GameThumbnail.png)**到项目.编辑此文件以更改图标.(to the project. Edit this file to change the icon.)
从这里到哪里(Where to From Here)
如果您想进一步研究XNA程序,那么可以在线获取大量资源.但我强烈建议的两个是(If you’d like to look into the XNA program further, then there are plenty of resources available online. But the two that I would highly suggest are the) Zune编程参考(Zune Programming Reference) 和(and the) XNA Creator俱乐部论坛(XNA Creator’s Club Forums) .(.)
历史(History)
- 2009年9月25日(25 September 2009)-初始发布.(- Initial publishing.)
许可
本文以及所有相关的源代码和文件均已获得The Code Project Open License (CPOL)的许可。
C# C#3.0 .NETCF .NET Mobile .NET3.5 Dev 新闻 翻译