c++ - 未在指定位置绘制 Sprite

标签 c++ multithreading 2d sprite sfml

我有一个简单的多线程 2D 程序,它试图绘制一个 16 x 16 的 Sprite /图 block View ,其中每个图 block 的大小为 32x32 像素。

首先,在主线程中,我为每个图 block 创建一个类的实例,每个图 block 都有一个 Sprite :

Tile.h

class Tile
{
    Point2D pos;
    public:
    Point2D getPos() { return pos; }
    sf::Sprite getSprite() { return sprite; }
    sf::Sprite sprite;
    Tile(int _x, int _y, int _type);
    ~Tile();
};

World.cpp 构造函数

    for (size_t y = 0; y < WORLD_HEIGHT; y++) {
    for (size_t x = 0; x < WORLD_WIDTH; x++) {
         tiles.push_back(Tile(x, y, 0));
    }
}

瓷砖.cpp

Tile::Tile(int _x, int _y, int _type) {
pos = Point2D(_x, _y);

sprite.setTexture(world->rm->dirt); 
sprite.setPosition(world->TILE_WIDTH * _x, world->TILE_HEIGHT * _y);

到目前为止一切似乎都很好,事实上,当我在这里打印出所有值时,这些值都符合我的预期,其中 _x_y 是 1 的增量因为它们来自循环,sprite.setPosition() 获得 32 的增量,例如 0、32、64 等作为参数传递。

初始化此 View 后, Sprite 将在不同的线程中绘制:

main.cpp

void renderingThread(sf::RenderWindow* window) {

// the rendering loop
while (window->isOpen()) {
    window->clear();
    for (size_t y = 0; y < world->WORLD_HEIGHT; y++) {
        for (size_t x = 0; x < world->WORLD_WIDTH; x++) {
            window->draw(world->tiles[y * x + x].sprite);
        }
    }
    window->display();
}
}

在这里,值变得很奇怪,导致这样的 View : https://drive.google.com/file/d/0BxYb1RtxJEu8bGRRaEFORHY2enM/view?usp=sharing

在绘制之前重置 Sprite 在渲染循环中的位置没有效果:

world->tiles[y * x + x].sprite.setPosition(world->tiles[y * x + x].getPos().x * 32, world->tiles[y * x + x].getPos().y * 32);

我是不是漏掉了一些简单的东西或者发生了什么?我自己找不到任何东西。

最佳答案

使用 y * x + x 作为图 block 索引肯定是错误的。它可能应该是 y * width + x

关于c++ - 未在指定位置绘制 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28286246/

相关文章:

java - 在java中执行后台任务

java - Line2D厚度(太厚)

c++ - 在由形成凸四边形的 4 个点定义的一组 6 个线段中查找对角线的算法

javascript - HTML Canvas : Replace the Shapes with Numbers (ctx)

c++ - 找不到boost库

c++ - 访问冲突读取位置0xfeeeefef2 多线程编程c++ windows

objective-c - 在不同的 NSThread/NSRunLoop 中运行和管理 NSTimer

java - Java中的多线程

c++ - 我想删除 txt 文件中以 %% ( C++) 开头的一些行

c++ - C++代码跳过获取行语句的问题