[英]C++ and SDL problem
I want to blit surfaces that I've created in two classes. 我想对我在两个类中创建的曲面进行blit。 One is called
Map
, that holds the relevant map vector as well as some other stuff. 一种叫做
Map
,它保存相关的地图矢量以及其他一些东西。 The other is a Tile
class. 另一个是
Tile
类。 There is a problem when I run the program. 运行程序时出现问题。
I get no errors, and the program runs as it should. 我没有收到任何错误,程序正常运行。 Any ideas?
有任何想法吗? It's probably a stupid mistake somewhere.
这可能是一个愚蠢的错误。
Map populate
void map::Populate(map M)
for(int x=0;x<=19;x++)
{
for(int y=0;y<=15;y++)
{
int y2 = (y*32);
int x2 = (y*32);
Tile T(x2,y2);
M.AddToMap(&T);
printf("Added Tile");
Render
void map::Render(SDL_Surface* screen)
{
for(int x=0;x<grid.size();x++)
{
printf("test");
Tile* T = grid[x];
SDL_Surface* k = T->GetIcon();
SDL_Rect dstrect;
dstrect.x = (screen->w - k->w) / 2;
dstrect.y = (screen->h - k->h) / 2;
SDL_BlitSurface(k, 0, screen, &dstrect);
You're not stating what the problem actually is, just that the program "runs as it should". 您并没有说明问题的实质,只是程序“按预期运行”。
Problems in your code: 您的代码中的问题:
int x2 = (y*32);
should likely be x*32. 应该是x * 32。
void map::Populate(map M)
takes a map by value - this copies the map you pass, and any changes will not be visible in the passed map. void map::Populate(map M)
按值获取地图-这将复制您传递的地图,并且任何更改都不会在传递的地图中显示。 map & M
passes a reference, so changes will be seen in the map you pass. map & M
通过了参考,因此更改将在您通过的地图中显示。
M.AddToMap(&T)
adds a pointer to the local Tile variable, which gets invalidated each iteration of the inner loop. M.AddToMap(&T)
向本地 Tile变量添加一个指针,该变量在每次内部循环迭代时均无效。 More likely you want new Tile(T)
there, or better yet a smart pointer such as boost's shared_ptr
. 您更有可能在那里需要
new Tile(T)
,或者更好的是智能指针,例如boost的shared_ptr
。 Remember that you also need to delete
those Tiles if you don't use a smart pointer. 请记住,如果您不使用智能指针,则还需要
delete
这些图块。
New code: 新代码:
void map::Populate(map & M)
for(int x=0; x<20; x++)
{
for(int y=0; y<16; y++)
{
int y2 = (y*32);
int x2 = (x*32);
M.AddToMap(new Tile(x2,y2));
printf("Added Tile");
You are adding a reference to a local variable to your map in Populate. 您正在向Populate中的地图添加对局部变量的引用。 If the method doesn't make a copy of the input, this is most likely wrong.
如果该方法未复制输入,则很可能是错误的。 Make a copy (pass by value) or store a smart pointer to your Tile.
进行复制(按值传递)或存储指向Tile的智能指针。 Of course you can store a plain old pointer, but make sure to delete those Tiles in the end!
当然,您可以存储一个普通的旧指针,但是请确保最后删除这些Tiles!
假设您的问题是图像没有显示,您可能需要发布屏幕和表面的设置代码,以便我们查看是否是问题所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.