游戲人生Silverlight:星際競(jìng)技場(chǎng)
介紹
使用 Silverlight 2.0(c#, Farseer Physics Engine) 開發(fā)一個(gè)射擊游戲:星際競(jìng)技場(chǎng)
玩法
W 或者 ↑ = 前進(jìn);S 或者 ↓ = 后退:A 或者 ← = 左轉(zhuǎn);D 或者 → = 右轉(zhuǎn);J 或者 Ctrl = 開火
思路
1、使用一個(gè)開源的 Silverlight 物理引擎:Farseer Physics Engine
2、將 Farseer Physics Engine 中的物理運(yùn)算器 PhysicsSimulator 放到一個(gè)全局變量中,對(duì) Body 和 Geom 做即時(shí)運(yùn)算,
3、寫個(gè) IPhysicsControl 接口,用于描述物理對(duì)象的各個(gè)屬性,需要運(yùn)動(dòng)和碰撞的對(duì)象,要實(shí)現(xiàn)該接口抽象出來的各個(gè)屬性
4、寫個(gè)抽象類(Sprite),在其內(nèi)封裝好物理引擎。各種類型的物理對(duì)象的模擬器,都需要重寫該抽象類的兩個(gè)方法GetForce()和GetTorque()即可,其分別要返回對(duì)象在當(dāng)前時(shí)刻所受到的牽引力和力矩
5、寫個(gè) IFire 接口,所有可開火的對(duì)象都要實(shí)現(xiàn)該接口
6、寫個(gè)控件 PhysicsBox,用于包裝 IPhysicsControl,從而將模擬器計(jì)算出的運(yùn)動(dòng)和碰撞結(jié)果呈現(xiàn)到界面上
關(guān)鍵代碼Sprite.cs(Sprite 模擬器的基類)
- using System;
 - using System.Net;
 - using System.Windows;
 - using System.Windows.Controls;
 - using System.Windows.Documents;
 - using System.Windows.Ink;
 - using System.Windows.Input;
 - using System.Windows.Media;
 - using System.Windows.Media.Animation;
 - using System.Windows.Shapes;
 - using FarseerGames.FarseerPhysics;
 - using FarseerGames.FarseerPhysics.Mathematics;
 - using FarseerGames.FarseerPhysics.Dynamics;
 - using FarseerGames.FarseerPhysics.Collisions;
 - namespace YYArena.Core
 - {
 - /**//// <summary>
 - /// Sprite 基類
 - /// </summary>
 - public abstract class Sprite
 - {
 - private PhysicsSimulator _physicsSimulator;
 - protected PhysicsBox playerBox;
 - protected Geom playerGeometry;
 - /**//// <summary>
 - /// 構(gòu)造函數(shù)
 - /// </summary>
 - /// <param name="physicsSimulator">PhysicsSimulator</param>
 - /// <param name="physicsControl">IPhysicsControl</param>
 - /// <param name="position">初始位置</param>
 - /// <param name="angle">初始轉(zhuǎn)角</param>
 - /// <param name="originalVelocity">初始速度</param>
 - public Sprite(PhysicsSimulator physicsSimulator,
 - IPhysicsControl physicsControl, Vector2 position, float angle, float originalVelocity)
 - {
 - _physicsSimulator = physicsSimulator;
 - playerBox = new PhysicsBox(physicsControl);
 - playerBox.Body.Position = position;
 - playerBox.Body.Rotation = (float)Helper.Angle2Radian(angle);
 - playerBox.Body.LinearVelocity = Helper.Convert2Vector(originalVelocity, (float)Helper.Angle2Radian(angle));
 - // Body 和 Geom 的 Tag 保存為 Sprite,方便引用
 - playerBox.Body.Tag = this;
 - playerBox.Geom.Tag = this;
 - playerBox.Update();
 - }
 - /**//// <summary>
 - /// 即時(shí)計(jì)算力和力矩
 - /// </summary>
 - void CompositionTarget_Rendering(object sender, EventArgs e)
 - {
 - if (Enabled)
 - {
 - var force = GetForce();
 - var torque = GetTorque();
 - playerBox.Body.ApplyForce(force);
 - playerBox.Body.ApplyTorque(torque);
 - playerBox.Update();
 - }
 - }
 - /**//// <summary>
 - /// 返回 Sprite 當(dāng)前受的力
 - /// </summary>
 - protected abstract Vector2 GetForce();
 - /**//// <summary>
 - /// 返回 Sprite 當(dāng)前受的力矩
 - /// </summary>
 - protected abstract float GetTorque();
 - public PhysicsBox PhysicsBox
 - {
 - get { return playerBox; }
 - }
 - private bool _enabled = false;
 - /**//// <summary>
 - /// 是否啟用此 Sprite
 - /// </summary>
 - public bool Enabled
 - {
 - get { return _enabled; }
 - set
 - {
 - _enabled = value;
 - if (value)
 - {
 - CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
 - _physicsSimulator.Add(playerBox.Body);
 - _physicsSimulator.Add(playerBox.Geom);
 - }
 - else
 - {
 - CompositionTarget.Rendering -= new EventHandler(CompositionTarget_Rendering);
 - GC.SuppressFinalize(this);
 - _physicsSimulator.Remove(playerBox.Body);
 - _physicsSimulator.Remove(playerBox.Geom);
 - }
 - }
 - }
 - }
 - }
 
#p#
PlayerSprite.cs(玩家 Sprite 模擬器)
- using System;
 - using System.Net;
 - using System.Windows;
 - using System.Windows.Controls;
 - using System.Windows.Documents;
 - using System.Windows.Ink;
 - using System.Windows.Input;
 - using System.Windows.Media;
 - using System.Windows.Media.Animation;
 - using System.Windows.Shapes;
 - using System.Collections.Generic;
 - using FarseerGames.FarseerPhysics.Mathematics;
 - using FarseerGames.FarseerPhysics;
 - using FarseerGames.FarseerPhysics.Collisions;
 - namespace YYArena.Core
 - {
 - /**//// <summary>
 - /// 玩家 Sprite
 - /// </summary>
 - public class PlayerSprite : Sprite, IFire
 - {
 - private List<Key> _upKeys { get; set; }
 - private List<Key> _downKeys { get; set; }
 - private List<Key> _leftKeys { get; set; }
 - private List<Key> _rightKeys { get; set; }
 - private List<Key> _fireKeys { get; set; }
 - private KeyboardHandler _keyHandler;
 - private IPhysicsControl _physicsControl;
 - /**//// <summary>
 - /// 構(gòu)造函數(shù)
 - /// </summary>
 - /// <param name="physicsSimulator">PhysicsSimulator</param>
 - /// <param name="physicsControl">IPhysicsControl</param>
 - /// <param name="position">初始位置</param>
 - /// <param name="angle">初始轉(zhuǎn)角</param>
 - /// <param name="originalVelocity">初始速度</param>
 - /// <param name="keyboardHandler">KeyboardHandler</param>
 - /// <param name="up">操作玩家向前移動(dòng)的按鍵集合</param>
 - /// <param name="down">操作玩家向后移動(dòng)的按鍵集合</param>
 - /// <param name="left">操作玩家向左轉(zhuǎn)動(dòng)的按鍵集合</param>
 - /// <param name="right">操作玩家向右轉(zhuǎn)動(dòng)的按鍵集合</param>
 - /// <param name="fire">操作玩家開火的按鍵集合</param>
 - public PlayerSprite(PhysicsSimulator physicsSimulator,
 - IPhysicsControl physicsControl, Vector2 position, float angle, float originalVelocity,
 - KeyboardHandler keyboardHandler,
 - List<Key> up, List<Key> down, List<Key> left, List<Key> right, List<Key> fire)
 - : base(physicsSimulator, physicsControl, position, angle, originalVelocity)
 - {
 - PrevFireDateTime = DateTime.MinValue;
 - MinFireInterval = 500d;
 - _upKeys = up;
 - _downKeys = down;
 - _leftKeys = left;
 - _rightKeys = right;
 - _fireKeys = fire;
 - _keyHandler = keyboardHandler;
 - _physicsControl = physicsControl;
 - CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
 - }
 - void CompositionTarget_Rendering(object sender, EventArgs e)
 - {
 - if (Enabled)
 - {
 - // 如果按了開火鍵,是否可開火
 - if (_keyHandler.AnyKeyPressed(_fireKeys) && (DateTime.Now - PrevFireDateTime).TotalMilliseconds > MinFireInterval)
 - {
 - PrevFireDateTime = DateTime.Now;
 - if (Fire != null)
 - Fire(this, EventArgs.Empty);
 - }
 - }
 - }
 - public DateTime PrevFireDateTime { get; set; }
 - public double MinFireInterval { get; set; }
 - public event EventHandler<EventArgs> Fire;
 - protected override Vector2 GetForce()
 - {
 - Vector2 force = Vector2.Zero;
 - if (_keyHandler.AnyKeyPressed(_upKeys))
 - force += Helper.Convert2Vector(_physicsControl.ForceAmount, playerBox.Body.Rotation);
 - if (_keyHandler.AnyKeyPressed(_downKeys))
 - force += Helper.Convert2Vector(_physicsControl.ForceAmount, playerBox.Body.Rotation - Helper.Angle2Radian(180));
 - // 最大線性速度限制
 - if (playerBox.Body.LinearVelocity.Length() > _physicsControl.MaxLinearVelocity)
 - force = Vector2.Zero;
 - return force;
 - }
 - protected override float GetTorque()
 - {
 - float torque = 0;
 - if (_keyHandler.AnyKeyPressed(_leftKeys))
 - torque -= _physicsControl.TorqueAmount;
 - if (_keyHandler.AnyKeyPressed(_rightKeys))
 - torque += _physicsControl.TorqueAmount;
 - // 用于修正 RotationalDragCoefficient (在沒有任何 Torque 的情況下,如果轉(zhuǎn)速小于 1.3 則設(shè)其為 0)
 - // 如果不做此修正的話,轉(zhuǎn)速小于 1.3 后還會(huì)轉(zhuǎn)好長(zhǎng)時(shí)間
 - if (!_keyHandler.AnyKeyPressed(_leftKeys) && !_keyHandler.AnyKeyPressed(_rightKeys) && Math.Abs(playerBox.Body.AngularVelocity) < 1.3)
 - playerBox.Body.AngularVelocity = 0;
 - // 最大轉(zhuǎn)速限制
 - if (Math.Abs(playerBox.Body.AngularVelocity) > _physicsControl.MaxAngularVelocity)
 - torque = 0;
 - return torque;
 - }
 - }
 - }
 
#p#
AISprite.cs(敵軍 Sprite 模擬器)
- using System;
 - using System.Net;
 - using System.Windows;
 - using System.Windows.Controls;
 - using System.Windows.Documents;
 - using System.Windows.Ink;
 - using System.Windows.Input;
 - using System.Windows.Media;
 - using System.Windows.Media.Animation;
 - using System.Windows.Shapes;
 - using System.Collections.Generic;
 - using FarseerGames.FarseerPhysics.Mathematics;
 - using FarseerGames.FarseerPhysics;
 - using FarseerGames.FarseerPhysics.Collisions;
 - using FarseerGames.FarseerPhysics.Dynamics;
 - namespace YYArena.Core
 - {
 - /**//// <summary>
 - /// 敵軍 Sprite
 - /// </summary>
 - public class AISprite : Sprite, IFire
 - {
 - private Sprite _attackTarget;
 - private int _aiLevel;
 - private IPhysicsControl _physicsControl;
 - /**//// <summary>
 - /// 構(gòu)造函數(shù)
 - /// </summary>
 - /// <param name="physicsSimulator">PhysicsSimulator</param>
 - /// <param name="physicsControl">IPhysicsControl</param>
 - /// <param name="position">初始位置</param>
 - /// <param name="angle">初始轉(zhuǎn)角</param>
 - /// <param name="originalVelocity">初始速度</param>
 - /// <param name="attackTarget">攻擊目標(biāo)</param>
 - /// <param name="aiLevel">ai等級(jí)</param>
 - public AISprite(PhysicsSimulator physicsSimulator,
 - IPhysicsControl physicsControl, Vector2 position, float angle, float originalVelocity, Sprite attackTarget, int aiLevel)
 - : base(physicsSimulator, physicsControl, position, angle, originalVelocity)
 - {
 - // 上次開火時(shí)間
 - PrevFireDateTime = DateTime.Now.AddSeconds(3);
 - // 最小開火間隔
 - MinFireInterval = 3000d;
 - _attackTarget = attackTarget;
 - _aiLevel = aiLevel;
 - _physicsControl = physicsControl;
 - InitAI();
 - CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
 - }
 - private void InitAI()
 - {
 - // 根據(jù) ai 等級(jí)設(shè)置最小開火間隔
 - double fireCoefficient = 1 + 30 / _aiLevel;
 - MinFireInterval = Helper.GenerateRandom((int)MinFireInterval, (int)(fireCoefficient * MinFireInterval));
 - }
 - void CompositionTarget_Rendering(object sender, EventArgs e)
 - {
 - if (Enabled && AttackTarget.Enabled)
 - {
 - // 是否開火
 - if ((DateTime.Now - PrevFireDateTime).TotalMilliseconds > MinFireInterval)
 - {
 - PrevFireDateTime = DateTime.Now;
 - if (Fire != null)
 - Fire(this, EventArgs.Empty);
 - }
 - }
 - }
 - public DateTime PrevFireDateTime { get; set; }
 - public double MinFireInterval { get; set; }
 - public event EventHandler<EventArgs> Fire;
 - public Sprite AttackTarget
 - {
 - get { return _attackTarget; }
 - set { _attackTarget = value; }
 - }
 - protected override Vector2 GetForce()
 - {
 - Vector2 force = Vector2.Zero;
 - if (!_attackTarget.Enabled)
 - return force;
 - force += Helper.Convert2Vector(_physicsControl.ForceAmount, playerBox.Body.Rotation);
 - // 根據(jù) ai 等級(jí)做最大線性速度限制
 - if (playerBox.Body.LinearVelocity.Length() > _physicsControl.MaxLinearVelocity * Helper.GenerateRandom(50, 200) / 1000)
 - force = Vector2.Zero;
 - return force;
 - }
 - protected override float GetTorque()
 - {
 - float torque = 0f;
 - if (!_attackTarget.Enabled)
 - return torque;
 - // 按某個(gè)方向旋轉(zhuǎn),原則是以最小的旋轉(zhuǎn)角度對(duì)準(zhǔn)目標(biāo)
 - Vector2 relativePosition = _attackTarget.PhysicsBox.Body.Position - playerBox.Body.Position;
 - double targetRotation = Helper.Convert2Rotation(relativePosition);
 - double currentRotation = playerBox.Body.Rotation;
 - double relativeAngle = Helper.Radian2Angle(targetRotation - currentRotation);
 - if (relativeAngle < 0)
 - relativeAngle += 360;
 - if (relativeAngle > 1)
 - {
 - if (relativeAngle < 180 && relativeAngle > 0)
 - torque += _physicsControl.TorqueAmount;
 - else if (relativeAngle > 180 && relativeAngle < 360)
 - torque -= _physicsControl.TorqueAmount;
 - }
 - else
 - {
 - playerBox.Body.AngularVelocity = 0;
 - }
 - // 最大轉(zhuǎn)速限制
 - if (Math.Abs(playerBox.Body.AngularVelocity) > _physicsControl.MaxAngularVelocity)
 - torque = 0;
 - return torque;
 - }
 - }
 - }
 
原文鏈接:http://www.cnblogs.com/webabcd/archive/2009/06/22/1508042.html















 
 
 















 
 
 
 