【翻译】Windows Phone开发海盗游戏!带源码
大家好哦!在这篇文章中,我将放出一个 Windows 手机游戏(或至少是一个游戏的开始……),并希望它给大家慢慢带来更多的乐趣。同时给大家介绍所需要的基本技术。然后,我将介绍其中的一些步骤,我希望这能一直引起你的兴趣,直到文章的结尾。
同时我也不得不感谢一直支持我的卤面网版主,是他让我提起兴趣写了这么一篇文章,再次感谢卤面网,一个非常不错的wp7开发论坛,后面我也将再次向大家发布几篇高质量文章,请大家到卤面上找我吧,呵呵
好了,正题开始..
“海盗! 是一个wp7上的用C#和XNA做出来的游戏,使用Farseer物理引擎。游戏的想法,主要是启发于Rovio的“愤怒的小鸟”的游戏,在2011年年底达到500万次的下载。愤怒的小鸟可能已经上瘾了世界各地的许多人,但是从我个人而言,我不沉迷于游戏本身,而是追求创作一个这样的游戏所需要的过程。
而不是鸟,而是大炮炮弹。而不是猪,而是大海盗船的海盗。在这里你的任务是使用大炮瞄准,并销毁所有海盗。
Farseer物理引擎
这是一个很酷的开源物理引擎,一个开放源码项目(顺便说一句,愤怒的小鸟也是使用Box2D的)。所不同的是用的 C + +的Box2D(并已被移植到多国语言),而本游戏用的C#,Silverlight和XNA。
调整游戏每秒60帧
1.为了达到最大帧每秒(约60帧),你必须修改你下载的farseer的源代码:
2.双击“Samples XNA WP7 ”解决方案。选择“Upgrade Windows Phone Projects… “ 他们全部升级到最新的Windows Phone 7.5芒果。
在游戏类的构造函数中,添加此事件处理程序:
_graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs>(_graphics_PreparingDeviceSettings);
3.然后添加此事件:
void _graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e) { e.GraphicsDeviceInformation.PresentationParameters.PresentationInterval = PresentInterval.One; }
4.在游戏类的初始化方法中,确保修改PresentationInterval参数为PresentationInterval.One:
protected override void Initialize() { base.Initialize(); this.GraphicsDevice.PresentationParameters.PresentationInterval = Microsoft.Xna.Framework.Graphics.PresentInterval.One; ...
幸运的是,我已经修改出了Farseer物理引擎兼容的编译版本,它能在 Windows Phone 7.5上运行尽可能最好的帧率。这将给对farseer引擎与游戏开发有兴趣的读者带来非常有用的帮助,
转换成物理对象的图像
对游戏中的所有动态创建对象进行贴图。这是 Farseer一个非常不错的功能,使我们的开发更容易。我们留下的空白与透明色,如图,
Farseer使用BayazitDecomposer.ConvexPartition的方法,创建一个大凹多边形的小凸多边形:
TextureBody textureBody; // 加载的纹理,将代表的物理身体 var physicTexture = ScreenManager.Content.Load<Texture2D>(string.Format("Samples/{0}", physicTextureName)); // 创建一个数组来保存纹理数据 uint[] data = new uint[physicTexture.Width * physicTexture.Height]; // 纹理数据传送到阵列 physicTexture.GetData(data); // 查找纹理的形状轮廓顶点 Vertices textureVertices = PolygonTools.CreatePolygon(data, physicTexture.Width, false); //在纹理中发现的顶点。 // 我们需要找到真正的中心(重心)的顶点,原因有二: // 1。转换多边形的顶点,使周围的重心集中。 Vector2 centroid = -textureVertices.GetCentroid() + bodyOrigin - centerScreen; textureVertices.Translate(ref centroid); // 2。到正确的位置绘制纹理。 var origin = -centroid; // 我们简化纹理的顶点。 textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f); // 因为它是一个凹多边形,我们需要进行分区成几个较小的凸多边形 List<Vertices> list = BayazitDecomposer.ConvexPartition(textureVertices); // 调整对象为WP7的较低分辨率 _scale = 1f; Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * _scale; foreach (Vertices vertices in list) { vertices.Scale(ref vertScale); }
处理输入循环
Farseer 引擎处理输入循环的接口,使我们有机会来检测和处理用户的手势。
此方法是负责:
检测左边摇杆运动,并转化成大炮运动。
检测的右边“A”的按钮,射击大炮。
public override void HandleInput(InputHelper input, GameTime gameTime) { var cannonCenter = new Vector2(0, 0); var cannonLength = 10f; var leftX = input.VirtualState.ThumbSticks.Left.X; var leftY = input.VirtualState.ThumbSticks.Left.Y; var cos = -leftX; var sin = leftY; var newBallPosition = cannonCenter + new Vector2(cos * cannonLength, sin * cannonLength); if (leftX < 0) { lastThumbSticksLeft.X = leftX; lastThumbSticksLeft.Y = leftY; } if (leftX != 0 || leftY != 0) { var newAngle = cannonAngle + leftY / gameTime.ElapsedGameTime.Milliseconds; if (newAngle < GamePredefinitions.MaxCannonAngle && newAngle > GamePredefinitions.MinCannonAngle) { cannonAngle = newAngle; } } if (input.VirtualState.IsButtonDown(Buttons.A)) { cannonBall.ResetHitCount(); smokeTracePositions.Clear(); VibrateController.Default.Start(TimeSpan.FromMilliseconds(20)); cannonBall.Body.AngularVelocity = 0; cannonBall.Body.LinearVelocity = new Vector2(0, 0); cannonBall.Body.SetTransform(new Vector2(0, 0), 0); cannonBall.Body.ApplyLinearImpulse(new Vector2(GamePredefinitions.Impulse * (float)System.Math.Cos(cannonAngle), GamePredefinitions.Impulse * (float)System.Math.Sin(cannonAngle))); PlaySound("Audio/cannon.wav"); } base.HandleInput(input, gameTime); }
Update循环
在XNA框架中,更新循环被调用时,需要处理游戏逻辑。这可能包括游戏状态管理,处理用户输入,或数据的更新。通过重写此方法,我们可以添加逻辑,具体到我们的海盗游戏我下面也会慢慢讲。
在XNA中, Update方法是和draw方法组合起来用的,你必须考虑到每个对象都有自己的特定角色。也就是说,一定不要把draw写入到了update中,也不要在draw中去更新update。
update 类主要有以下用途:
计算新的云的位置。有3层云 ,每一层以自己的速度移动。
海的外观是由4个现有的图片纹理轮流显示。
根据游戏状态转换移动camera (也就是说,游戏一开始是显示你的海盗船,然后camera移动到你的船)。
要沿炮弹描述的路径更新camera位置。这是有用的,以保持游戏动作的轨道。
必要时控制camera变焦。
也许最重要的是:更新大炮球的位置(随着烟雾留痕迹飞)
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (cannonBall.Body.LinearVelocity == Vector2.Zero) { cannonBall.Body.SetTransform(Vector2.Zero, 0f); } switch (seaStep) { case 0: seaTexture = sea1Texture; break; case 1: seaTexture = sea2Texture; break; case 2: seaTexture = sea3Texture; break; case 3: seaTexture = sea4Texture; break; } lastSeaStepTime = lastSeaStepTime.Add(gameTime.ElapsedGameTime); if (lastSeaStepTime.TotalSeconds > 1) { lastSeaStepTime = TimeSpan.Zero; seaStep++; if (seaStep == 4) seaStep = 0; } lastCloudStep1Time = lastCloudStep1Time.Add(gameTime.ElapsedGameTime); lastCloudStep2Time = lastCloudStep2Time.Add(gameTime.ElapsedGameTime); lastCloudStep3Time = lastCloudStep3Time.Add(gameTime.ElapsedGameTime); if (lastCloudStep1Time.TotalMilliseconds > GamePredefinitions.CloudStep1MaxTimeMs) { lastCloudStep1Time = TimeSpan.Zero; cloudStep1++; if (cloudStep1 == GamePredefinitions.MaxCloudStep) cloudStep1 = 0; } if (lastCloudStep2Time.TotalMilliseconds > GamePredefinitions.CloudStep2MaxTimeMs) { lastCloudStep2Time = TimeSpan.Zero; cloudStep2++; if (cloudStep2 == GamePredefinitions.MaxCloudStep) cloudStep2 = 0; } if (lastCloudStep3Time.TotalMilliseconds > GamePredefinitions.CloudStep3MaxTimeMs) { lastCloudStep3Time = TimeSpan.Zero; cloudStep3++; if (cloudStep3 == 800) cloudStep3 = 0; } var ballCenter = ConvertUnits.ToDisplayUnits(cannonBall.Body.WorldCenter); var ballX = ballCenter.X; var ballY = ballCenter.Y; var cameraX = GamePredefinitions.CameraInitialPosition.X; var cameraY = GamePredefinitions.CameraInitialPosition.Y; if (gameStateMachine.CurrentSate == GameState.Playing) { if (ballX < -scrollableViewport.Width / 6) { cameraX = -scrollableViewport.Width / 6; } else if (ballX > scrollableViewport.Width / 6) { cameraX = scrollableViewport.Width / 6; } else { cameraX = ballX; } if (ballY < -scrollableViewport.Height / 6) { cameraY = -scrollableViewport.Height / 6; } else if (ballY > scrollableViewport.Height / 6) { cameraY = scrollableViewport.Height / 6; } else { cameraY = ballY; } Camera.Position = new Vector2(cameraX, cameraY); } else if (gameStateMachine.CurrentSate == GameState.ShowingPirateShip) { if (gameStateMachine.EllapsedTimeSinceLastChange().TotalMilliseconds > GamePredefinitions.TotalTimeShowingPirateShipMs) { gameStateMachine.ChangeState(GameState.ScrollingToStartPlaying); } } else if (gameStateMachine.CurrentSate == GameState.ScrollingToStartPlaying) { var newCameraPosX = Camera.Position.X + (float)-10.0 * (gameTime.ElapsedGameTime.Milliseconds); Camera.Position = new Vector2(newCameraPosX, scrollableViewport.Height / 6); if (Camera.Zoom < 1.0f) { Camera.Zoom += gameTime.ElapsedGameTime.Milliseconds / GamePredefinitions.CameraZoomRate; } if (Camera.Position.X < -scrollableViewport.Width / 6) { Camera.Position = new Vector2(-scrollableViewport.Width / 6, Camera.Position.Y); gameStateMachine.ChangeState(GameState.Playing); } } if (cannonBall.HitCount == 0) { if (smokeTracePositions.Count() == 0) { smokeTracePositions.Add(cannonBall.Body.Position); } else { var lastBallPosition = smokeTracePositions.Last(); var currentBallPosition = cannonBall.Body.Position; var deltaX = Math.Abs((lastBallPosition.X - currentBallPosition.X)); var deltaY = Math.Abs((lastBallPosition.Y - currentBallPosition.Y)); if (deltaX * deltaX + deltaY * deltaY > GamePredefinitions.SmokeTraceSpace * GamePredefinitions.SmokeTraceSpace) { smokeTracePositions.Add(cannonBall.Body.Position); } } } }
在update函数中一个很重要是使用 GameTime参数。此参数告诉我们时间,因为游戏是最后一次更新花了多少时。正如你可以在上面看到,它使我们能够正确地计算cpu的速度波动的干扰。否则,你可能会看到比赛快或慢,取决于你手机在某一时刻的cpu的处理速度。
draw循环
是XNA框架绘制的重要模块。我们重写此方法来绘制我们的海盗游戏所需的所有帧。
这个循环处理了下面所说的一部分内容:
绘制背景纹理
绘制的蓝天,白云,大海和船
绘制了炮弹,大炮和烟雾的痕迹
绘制了现场的海盗和其他对象。
得分和最高分数。
public override void Draw(GameTime gameTime) { ScreenManager.SpriteBatch.Begin(0, null, null, null, null, null, Camera.View); if (gameStateMachine.CurrentSate != GameState.None) { var skyRect = GamePredefinitions.SkyTextureRectangle; var seaRect = GamePredefinitions.SeaTextureRectangle; ScreenManager.SpriteBatch.Draw(skyTexture, skyRect, Color.White); ScreenManager.SpriteBatch.Draw(cloud1Texture, new Rectangle(skyRect.X + cloudStep1, skyRect.Y, skyRect.Width, skyRect.Height), Color.White); ScreenManager.SpriteBatch.Draw(cloud2Texture, new Rectangle(skyRect.X + cloudStep2 * 2, skyRect.Y, skyRect.Width, skyRect.Height), Color.White); ScreenManager.SpriteBatch.Draw(cloud3Texture, new Rectangle(skyRect.X + cloudStep3 * 3, skyRect.Y, skyRect.Width, skyRect.Height), Color.White); ScreenManager.SpriteBatch.Draw(seaTexture, seaRect, Color.White); ScreenManager.SpriteBatch.Draw(pirateShipTexture, GamePredefinitions.PirateShipTextureRectangle, Color.White); ScreenManager.SpriteBatch.Draw(royalShipTexture, GamePredefinitions.RoyalShipTextureRectangle, Color.White); } smokeTracePositions.ForEach(e => ScreenManager.SpriteBatch.Draw(smokeTraceTexture, ConvertUnits.ToDisplayUnits(e) + GamePredefinitions.CannonCenter - new Vector2(10, 10), null, Color.White, 0f, Vector2.Zero, _scale, SpriteEffects.None, 0f)); foreach (var textureBody in textureBodies) { ScreenManager.SpriteBatch.Draw(textureBody.DisplayTexture, ConvertUnits.ToDisplayUnits(textureBody.Body.Position), null, Color.White, textureBody.Body.Rotation, textureBody.Origin, _scale, SpriteEffects.None, 0f); } ScreenManager.SpriteBatch.Draw(cannonTexture, GamePredefinitions.CannonCenter, null, Color.White, cannonAngle, new Vector2(40f, 29f), 1f, SpriteEffects.None, 0f); var hiScoreText = string.Format("hi score: {0}", scoreManager.GetHiScore()); var scoreText = string.Format("score: {0}", scoreManager.GetScore()); DrawScoreText(0, 0, hiScoreText); DrawScoreText(0, 30, scoreText); ScreenManager.SpriteBatch.End(); _border.Draw(); base.Draw(gameTime); }
首先,我们绘制的天空。然后我们绘制以水平不同的速度运动的云 ,然后我们画的大海,然后船。最后,我们得出的动态元素:炮弹,大炮,比分。
最后的思考
我希望你喜欢!如果你有话要说,请到卤面网(codewp7.com)问答区联系我,我会很高兴知道你在想什么。同时wp7交流QQ群172765887中,也能找到我的身影,感谢大家
原文请见
http://www.codeproject.com/Articles/322715/WPPirates