您的位置:首页 > 其它

XNA游戏开发学习笔记系列(四)

2012-05-11 00:50 267 查看
面向对象设计

在本节中将会创建三个类,第一个是Sprite类,Sprite类是一个抽象类;第二个UserControlledSprite类,继承于Sprite,对象是一个用户可以控制的精灵;第三个是AutomatedSprite,同样是继承于Sprite类,这个类是创建自动精灵的。

Sprite类的成员:

textureImage              Texture2D        要绘制的精灵表

position                       Vector2            精灵的绘制位置

frameSize                    Point                精灵中每一帧的大小

collisionOffset              int                    碰撞检测偏移量

currentFrame              Point                 当前帧在精灵表中的索引

sheetSize                   Point                  精灵表的列数/行数

timeSinceLastFrame   int                      上一帧绘制后经过的毫秒数

millisecondsPerFrame int                      帧与帧之间要等待的毫秒数

speed                         vector2              精灵在X方向和Y方向的移动速度

 

Sprite类的定义了两个构造器,差别在于第二个构造器用millisecondsPerFrame变了计算动画的速度

public Sprite(Texture2D textureImage, Vector2 position, Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed)
: this(textureImage, position, frameSize, collisionOffset, currentFrame, sheetSize, speed, defaultMillisecondsPerFrame)
{
}

//第一个和第二个构造函数的区别在于第二个要求用millisecondsPerFrame变量计算动画速度
public Sprite(Texture2D textureImage, Vector2 position, Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed, int millisecondsPerFrame)
{
this.textureImage = textureImage;
this.position = position;
this.frameSize = frameSize;
this.collisionOffset = collisionOffset;
this.currentFrame = currentFrame;
this.sheetSize = sheetSize;
this.speed = speed;
this.millisecondsPerFrame = millisecondsPerFrame;
}


UserControlledSprite和AutomatedSprite继承Sprite类,重写Update和Draw方法,实现动画,移动,碰撞检测等逻辑,具体请参考上一节或本节源代码。

 

游戏组件GameComponent

GameComponent类允许以模块方式将任何代码插入到应用程序中,并即那个那个组件自动集成到游戏循环的Update调用之中,游戏每一次执行Update调用后都会执行组件中的Update方法,这样既可以方便地为游戏添加模块,同时也可以将不同逻辑的代码实现分离。要使用游戏组件,我们就要新建一个GameComponent,该类默认从GameComponent派生,如果我们想在组件中绘制,既调用Draw方法,我们可以将该类改为继承于DrawableGameComponent。创建了这个游戏组件后,怎么将游戏与组件关联呢?也很简单,就三行代码,先声明一个变量,SpriteBatch spriteBatch; 然后在Initialize方法中添加

spriteManager = new SpriteManager(this);

Components.Add(spriteManager);

最后添加一些逻辑代码,面向对象的精灵管理器就完成了。

 

源代码下载:http://www.ctdisk.com/file/6709470
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐