如何使用公共Character类及函数绘制Boulder Dash角色Rockford?
我在学校项目中需要用C#复刻C64平台的Boulder Dash游戏,但卡在了绘制角色Rockford的环节。我的英文表达能力有限,但看代码会更容易理解。所有与角色相关的内容都在Character类中,我需要使用公共Character类创建精灵并通过函数绘制,但不知道如何将Character中的精灵传递到绘制函数中。我尝试过多种方法,比如在函数内重新创建Character实例,甚至尝试在Draw函数中调用公共Character类,均未成功。相关代码如下:
public Character(string Image, int x, int y, Direction dir) { Image = "images/heros24.bmp"; x = 4; y = 3; dir = Direction.Left; Texture tRockford = new Texture(Image); Sprite sRockford = new Sprite(tRockford); } public void Afficher(RenderWindow fenetre, float PixelByCase) { string Image = "images/heros24.bmp"; int x = 4; int y = 3; Direction dir = Direction.Left; Character p = new Character(Image, x, y, dir); Vector2f position = new Vector2f(X * PixelsParCell, Y * PixelsParCell); p.Position = position; fenetre.Draw(p); }
你的代码存在三个核心问题,导致角色无法正常绘制:
构造函数未保留精灵资源
构造函数内创建的Texture和Sprite是局部变量,方法执行完毕后就会被销毁,Character类没有持有这些资源的引用,后续绘制时自然没有内容可画。绘制方法重复创建实例
每次调用Afficher都新建Character实例,不仅浪费内存,而且你设置的位置参数无法关联到持久的角色对象,新实例的资源也没被正确保存。Character不支持直接绘制
fenetre.Draw(p)要求传入的对象是Sprite类型(或继承自Drawable接口),你的Character类既没有继承Sprite,也没有暴露内部的Sprite实例,所以绘制方法无法识别。
修复后的代码示例
方案1:让Character继承Sprite(推荐)
这种方式最直接,Character本身就是Sprite的子类,可以直接被RenderWindow绘制:
public class Character : Sprite { public Character(string imagePath, int x, int y, Direction dir) { // 加载纹理并绑定到Sprite Texture texture = new Texture(imagePath); this.Texture = texture; // 设置初始位置(替换硬编码,使用传入的参数) this.Position = new Vector2f(x * 24, y * 24); // 根据方向处理精灵翻转 if (dir == Direction.Left) { this.Scale = new Vector2f(-1, 1); } } public void Afficher(RenderWindow fenetre) { // 直接绘制当前Character实例 fenetre.Draw(this); } }
方案2:Character内部持有Sprite实例
如果不想继承Sprite,可以让Character封装Sprite对象,对外暴露必要的属性和绘制方法:
public class Character { private readonly Sprite _sprite; public Vector2f Position { get => _sprite.Position; set => _sprite.Position = value; } public Character(string imagePath, int x, int y, Direction dir) { Texture texture = new Texture(imagePath); _sprite = new Sprite(texture); _sprite.Position = new Vector2f(x * 24, y * 24); if (dir == Direction.Left) { _sprite.Scale = new Vector2f(-1, 1); } } public void Afficher(RenderWindow fenetre) { // 绘制内部持有的Sprite fenetre.Draw(_sprite); } }
正确使用方式
在游戏的初始化逻辑中创建一次Character实例,然后在每一帧的绘制循环中调用它的Afficher方法:
// 在类级别声明角色对象 private Character _rockford; // 初始化时创建角色 _rockford = new Character("images/heros24.bmp", 4, 3, Direction.Left); // 绘制循环中调用(比如在RenderWindow的Draw事件里) _rockford.Afficher(fenetre);
内容的提问来源于stack exchange,提问作者Samuel Kabraelian

