测试XNA游戏中键盘输入,触控输入,按钮输入

Game1.cs

usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingMicrosoft.Xna.Framework; usingMicrosoft.Xna.Framework.Audio; usingMicrosoft.Xna.Framework.Content; usingMicrosoft.Xna.Framework.GamerServices; usingMicrosoft.Xna.Framework.Graphics; usingMicrosoft.Xna.Framework.Input; usingMicrosoft.Xna.Framework.Input.Touch; usingMicrosoft.Xna.Framework.Media; usingInputHandlerDemo.Inputs; namespaceInputHandlerDemo { publicclassGame1:Microsoft.Xna.Framework.Game { GraphicsDeviceManagergraphics; SpriteBatchspriteBatch; SpriteFontfont; Texture2Dsquare; stringaction=""; GameInputgameInput;//游戏输入管理类 TouchIndicatorCollectiontouchIndicators; RectangleJumpRectangle=newRectangle(0,0,480,100); RectangleUpRectangle=newRectangle(0,150,480,100); RectanglePauseRectangle=newRectangle(0,500,200,100); //退出矩形 RectangleExitRectangle=newRectangle(220,500,200,100); publicGame1() { graphics=newGraphicsDeviceManager(this); Content.RootDirectory="Content"; TargetElapsedTime=TimeSpan.FromTicks(333333); //设置高度和宽度 graphics.PreferredBackBufferWidth=480; graphics.PreferredBackBufferHeight=800; } protectedoverridevoidInitialize() { //初始化游戏输入对象 gameInput=newGameInput(); touchIndicators=newTouchIndicatorCollection(); AddInputs(); base.Initialize(); } ///<summary>///添加各种输入方式 ///</summary>privatevoidAddInputs() { //游戏按钮 //Addkeyboard,gamepadandtouchinputsforJump gameInput.AddKeyboardInput(Actions.Jump,Keys.A,true);//A键为跳 gameInput.AddKeyboardInput(Actions.Jump,Keys.Space,false);//Space键为跳 gameInput.AddTouchTapInput(Actions.Jump,JumpRectangle,false);//跳矩形区域为跳 gameInput.AddTouchSlideInput(Actions.Jump,Input.Direction.Right,5.0f);//右滑动为跳 //Addkeyboard,gamepadandtouchinputsforPause gameInput.AddGamePadInput(Actions.Pause,Buttons.Start,true); gameInput.AddKeyboardInput(Actions.Pause,Keys.P,true); gameInput.AddTouchTapInput(Actions.Pause,PauseRectangle,true); gameInput.AddAccelerometerInput(Actions.Pause, Input.Direction.Down, 0.10f); //Addkeyboard,gamepadandtouchinputsforUp gameInput.AddGamePadInput(Actions.Up,Buttons.RightThumbstickUp,false); gameInput.AddGamePadInput(Actions.Up,Buttons.LeftThumbstickUp,false); gameInput.AddGamePadInput(Actions.Up,Buttons.DPadUp,false); gameInput.AddKeyboardInput(Actions.Up,Keys.Up,false); gameInput.AddKeyboardInput(Actions.Up,Keys.W,true); gameInput.AddTouchTapInput(Actions.Up,UpRectangle,true); gameInput.AddTouchSlideInput(Actions.Up,Input.Direction.Up,5.0f); gameInput.AddAccelerometerInput(Actions.Up, Input.Direction.Up, 0.10f); //Addkeyboard,gamepadandtouchinputsforExit gameInput.AddGamePadInput(Actions.Exit,Buttons.Back,false); gameInput.AddKeyboardInput(Actions.Exit,Keys.Escape,false); gameInput.AddTouchTapInput(Actions.Exit,ExitRectangle,true); //AddsomeGesturestoo,justtoshowthemoff? gameInput.AddTouchGestureInput(Actions.Jump, GestureType.VerticalDrag, JumpRectangle); gameInput.AddTouchGestureInput(Actions.Pause, GestureType.Hold, PauseRectangle); } protectedoverridevoidLoadContent() { //CreateanewSpriteBatch,whichcanbeusedtodrawtextures. spriteBatch=newSpriteBatch(GraphicsDevice); //加载内容 font=Content.Load<SpriteFont>("Display"); square=Content.Load<Texture2D>("Pixel"); } protectedoverridevoidUnloadContent() { } protectedoverridevoidUpdate(GameTimegameTime) { if(GamePad.GetState(PlayerIndex.One).Buttons.Back==ButtonState.Pressed) this.Exit(); //根据输入类型更新游戏界面 gameInput.BeginUpdate(); //点击退出矩形,退出程序 if(gameInput.IsPressed(Actions.Exit,PlayerIndex.One)) this.Exit(); if(gameInput.IsPressed(Actions.Jump,PlayerIndex.One)) action=Actions.Jump; if(gameInput.IsPressed(Actions.Pause,PlayerIndex.One)) action=Actions.Pause; if(gameInput.IsPressed(Actions.Up,PlayerIndex.One)) action=Actions.Up; touchIndicators.Update(gameTime,Content); gameInput.EndUpdate(); base.Update(gameTime); } protectedoverridevoidDraw(GameTimegameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); //绘制游戏界面 spriteBatch.Begin(); spriteBatch.Draw(square,UpRectangle,Color.Blue); spriteBatch.DrawString(font, "Up", newVector2(UpRectangle.Left+20,UpRectangle.Top+20), Color.Black); spriteBatch.Draw(square,JumpRectangle,Color.Yellow); spriteBatch.DrawString(font, "Jump", newVector2(JumpRectangle.Left+20,JumpRectangle.Top+20), Color.Black); spriteBatch.Draw(square,PauseRectangle,Color.Green); spriteBatch.DrawString(font, "Pause", newVector2(PauseRectangle.Left+20,PauseRectangle.Top+20), Color.Black); spriteBatch.Draw(square,ExitRectangle,Color.Red); spriteBatch.DrawString(font, "Exit", newVector2(ExitRectangle.Left+20,ExitRectangle.Top+20), Color.Black); spriteBatch.DrawString(font,action,newVector2(100,350),Color.White); touchIndicators.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } }

Action.cs 游戏操作的类型

namespaceInputHandlerDemo { staticclassActions { //自定义的操作类型 publicconststringJump="Jump"; publicconststringExit="Exit"; publicconststringUp="Up"; publicconststringPause="Pause"; } }

下面是输入的操作的封装类

GameInput.cs

usingSystem; usingSystem.Collections.Generic; usingMicrosoft.Xna.Framework; usingMicrosoft.Xna.Framework.Input; usingMicrosoft.Xna.Framework.Input.Touch; namespaceInputHandlerDemo.Inputs { ///<summary>///游戏输入管理类 ///</summary>classGameInput { //输入类型字典 Dictionary<string,Input>Inputs=newDictionary<string,Input>(); //获取输入类型 publicInputGetInput(stringtheAction) { //如果没有改类型的输入操作则添加一个 if(Inputs.ContainsKey(theAction)==false) { Inputs.Add(theAction,newInput()); } returnInputs[theAction]; } publicvoidBeginUpdate() { Input.BeginUpdate(); } publicvoidEndUpdate() { Input.EndUpdate(); } publicboolIsConnected(PlayerIndexthePlayer) { //IfthereneverWASagamepadconnected,justsaythegamepadisSTILLconnected if(Input.GamepadConnectionState[thePlayer]==false) returntrue; returnInput.IsConnected(thePlayer); } publicboolIsPressed(stringtheAction) { if(!Inputs.ContainsKey(theAction)) { returnfalse; } returnInputs[theAction].IsPressed(PlayerIndex.One); } ///<summary>///判断单击的状态 ///</summary>///<paramname="theAction">动作</param>///<paramname="thePlayer">玩家</param>///<returns></returns>publicboolIsPressed(stringtheAction,PlayerIndexthePlayer) { if(Inputs.ContainsKey(theAction)==false) { returnfalse; } returnInputs[theAction].IsPressed(thePlayer); } publicboolIsPressed(stringtheAction,PlayerIndex?thePlayer) { if(thePlayer==null) { PlayerIndextheReturnedControllingPlayer; returnIsPressed(theAction,thePlayer,outtheReturnedControllingPlayer); } returnIsPressed(theAction,(PlayerIndex)thePlayer); } publicboolIsPressed(stringtheAction,PlayerIndex?thePlayer,outPlayerIndextheControllingPlayer) { if(!Inputs.ContainsKey(theAction)) { theControllingPlayer=PlayerIndex.One; returnfalse; } if(thePlayer==null) { if(IsPressed(theAction,PlayerIndex.One)) { theControllingPlayer=PlayerIndex.One; returntrue; } if(IsPressed(theAction,PlayerIndex.Two)) { theControllingPlayer=PlayerIndex.Two; returntrue; } if(IsPressed(theAction,PlayerIndex.Three)) { theControllingPlayer=PlayerIndex.Three; returntrue; } if(IsPressed(theAction,PlayerIndex.Four)) { theControllingPlayer=PlayerIndex.Four; returntrue; } theControllingPlayer=PlayerIndex.One; returnfalse; } theControllingPlayer=(PlayerIndex)thePlayer; returnIsPressed(theAction,(PlayerIndex)thePlayer); } publicvoidAddGamePadInput(stringtheAction,ButtonstheButton, boolisReleasedPreviously) { GetInput(theAction).AddGamepadInput(theButton,isReleasedPreviously); } publicvoidAddTouchTapInput(stringtheAction,RectangletheTouchArea, boolisReleasedPreviously) { GetInput(theAction).AddTouchTapInput(theTouchArea,isReleasedPreviously); } publicvoidAddTouchSlideInput(stringtheAction,Input.DirectiontheDirection, floatslideDistance) { GetInput(theAction).AddTouchSlideInput(theDirection,slideDistance); } publicvoidAddKeyboardInput(stringtheAction,KeystheKey, boolisReleasedPreviously) { GetInput(theAction).AddKeyboardInput(theKey,isReleasedPreviously); } publicvoidAddTouchGestureInput(stringtheAction,GestureTypetheGesture, RectangletheRectangle) { GetInput(theAction).AddTouchGesture(theGesture,theRectangle); } publicvoidAddAccelerometerInput(stringtheAction,Input.DirectiontheDirection, floattiltThreshold) { GetInput(theAction).AddAccelerometerInput(theDirection,tiltThreshold); } publicVector2CurrentGesturePosition(stringtheAction) { returnGetInput(theAction).CurrentGesturePosition(); } publicVector2CurrentGestureDelta(stringtheAction) { returnGetInput(theAction).CurrentGestureDelta(); } publicVector2CurrentGesturePosition2(stringtheAction) { returnGetInput(theAction).CurrentGesturePosition2(); } publicVector2CurrentGestureDelta2(stringtheAction) { returnGetInput(theAction).CurrentGestureDelta2(); } publicPointCurrentTouchPoint(stringtheAction) { Vector2?currentPosition=GetInput(theAction).CurrentTouchPosition(); if(currentPosition==null) { returnnewPoint(-1,-1); } returnnewPoint((int)currentPosition.Value.X,(int)currentPosition.Value.Y); } publicVector2CurrentTouchPosition(stringtheAction) { Vector2?currentTouchPosition=GetInput(theAction).CurrentTouchPosition(); if(currentTouchPosition==null) { returnnewVector2(-1,-1); } return(Vector2)currentTouchPosition; } publicfloatCurrentGestureScaleChange(stringtheAction) { //ScalingisdependentonthePinchgesture.Ifnoinputhasbeensetupfor //Pinchthenjustreturn0indicatingnoscalechangehasoccurred. if(!GetInput(theAction).PinchGestureAvailable)return0; //Getthecurrentandpreviouslocationsofthetwofingers Vector2currentPositionFingerOne=CurrentGesturePosition(theAction); Vector2previousPositionFingerOne=CurrentGesturePosition(theAction)-CurrentGestureDelta(theAction); Vector2currentPositionFingerTwo=CurrentGesturePosition2(theAction); Vector2previousPositionFingerTwo=CurrentGesturePosition2(theAction)-CurrentGestureDelta2(theAction); //Figureoutthedistancebetweenthecurrentandpreviouslocations floatcurrentDistance=Vector2.Distance(currentPositionFingerOne,currentPositionFingerTwo); floatpreviousDistance=Vector2.Distance(previousPositionFingerOne,previousPositionFingerTwo); //Calculatethedifferencebetweenthetwoandusethattoalterthescale floatscaleChange=(currentDistance-previousDistance)*.01f; returnscaleChange; } publicVector3CurrentAccelerometerReading(stringtheAction) { returnGetInput(theAction).CurrentAccelerometerReading; } } }

GestureDefinition.cs

usingSystem; usingMicrosoft.Xna.Framework; usingMicrosoft.Xna.Framework.Input.Touch; namespaceInputHandlerDemo.Inputs { ///<summary>///手势定义 ///</summary>classGestureDefinition { publicGestureTypeType; publicRectangleCollisionArea; publicGestureSampleGesture; publicVector2Delta; publicVector2Delta2; publicVector2Position; publicVector2Position2; publicGestureDefinition(GestureTypetheGestureType,RectangletheGestureArea) { Gesture=newGestureSample(theGestureType,newTimeSpan(0), Vector2.Zero,Vector2.Zero, Vector2.Zero,Vector2.Zero); Type=theGestureType; CollisionArea=theGestureArea; } publicGestureDefinition(GestureSampletheGestureSample) { Gesture=theGestureSample; Type=theGestureSample.GestureType; CollisionArea=newRectangle((int)theGestureSample.Position.X, (int)theGestureSample.Position.Y,5,5); Delta=theGestureSample.Delta; Delta2=theGestureSample.Delta2; Position=theGestureSample.Position; Position2=theGestureSample.Position2; } } }