我的 SDL 程序有问题。我的目标是让一个点沿着一条线移动。我将所有坐标保存在数据文件中。所以我只想从文件中读取它们并在正确的位置显示点。 点类(名为 linefollower)如下所示。
class Linefollower
{
private:
int x, y;
char orientation;
public:
//Initializes the variables
Linefollower();
void set(int m_x, int m_y, char m_orietnation);
void show();
char get_orientation();
};
Linefollower::Linefollower()
{
x = 0;
y = 0;
orientation = 'E';
}
void Linefollower::set(int m_x, int m_y, char m_orientation)
{
x = m_x;
y = m_y;
orientation = m_orientation;
}
void Linefollower::show()
{
//Show the linefollower
apply_surface(x, y, linefollower, screen );
}
char Linefollower::get_orientation()
{
return orientation;
}
apply_surface 函数。
void apply_surface( int x, int y, SDL_Surface * source, SDL_Surface* destination)
{
//Temporary rectangle to hold the offsets
SDL_Rect offset;
//Get the offsets
offset.x = x;
offset.y = y;
//Blit the surface
SDL_BlitSurface( source, NULL, destination, &offset);
}
应该显示动画的循环如下所示。
//While the user hasn't quit
while( quit == false )
{
//Apply the surface to the screen
apply_surface( 0, 0, image, screen );
fin.read((char*) &my_linefollower, sizeof my_linefollower);
if(my_linefollower.get_orientation() == 'Q')
break;
my_linefollower.show();
//Upadate the screen
if( SDL_Flip( screen ) == -1 )
{
return 1;
}
SDL_Delay(200);
}
现在我期待的是,我在屏幕上得到一个移动的点,但我唯一得到的是背景(图像)几秒钟,直到 if(my_linefollower.get_orientation() == '问')
break;
是真的。我做错了什么?
PS:我想值得注意的是,我是 SDL 的初学者,我从 tutorial 中获取了大部分代码。 .学习它对我来说完全是浪费时间,因为我不太可能很快再次使用它。
最佳答案
首先,您应该将 apply_surface
中的 offset
更改为如下所示:
SDL_Rect offset = { x, y, 0, 0 };
SDL_Rect
没有构造函数来默认将您的成员设置为 0
,因此您的 width
和 高度
。
此外,您应该检查 linefollower
包含的内容,如果它是有效的 SDL_Surface
。删除文件读取代码并手动控制 Linefollower
将使您能够轻松找到错误的来源。
使用调试器验证您的 x
和 y
坐标。
除此之外,您的代码应该可以工作,尽管您的窗口将没有响应,因为您没有通过 SDL_PollEvent
发送事件。
关于c++ - 在sdl中显示移动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14547844/