2017-05-27 54 views
0

我想知道为什么我的碰撞只在将我的精灵移动到屏幕原点时才起作用。这是我加载我的地​​图的方式有问题,还是有一些关于精灵如何工作,我不完全明白的问题?下面是我对tilemap的SFML碰撞检测只在原点工作?

Tilemap.cpp

#include "Tilemap.h" 
#include "Player.h" 

#include <SFML/Graphics.hpp> 
#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 
using namespace sf; 

//default constructor 
Tilemap::Tilemap() 
{ 
    if (!texture.loadFromFile("map/purpleBlock.png")) 
    { 
     cout << "Error opening file" << endl; 
    } 

    sprite.setTexture(texture); 
} 

//reads tilemap from a text file into an array 
void Tilemap::loadTile(RenderWindow &window, string filename) 
{ 
    string temp; 
    ifstream mapFile; 
    mapFile.open("map/test.map"); 

    if (!mapFile.is_open()) 
    { 
     cout << "Error opening " << filename << endl; 
    } 

    //getline(mapFile, tileSet); 

    //reading height, width, tile height, tile width and storing them into variables 
    getline(mapFile, temp); 
    tileWidth = stoi(temp, nullptr); 
    getline(mapFile, temp); 
    tileHeight = stoi(temp, nullptr); 

    getline(mapFile, temp); 
    width = stoi(temp, nullptr); 
    getline(mapFile, temp); 
    height = stoi(temp, nullptr); 

    data = new int[width*height]; 

    //reading values into array 
    for (int y = 0; y < height; ++y) 
    { 
     for (int x = 0; x < width; ++x) 
     { 
      char temp; 
      mapFile >> data[x + y * width] >> temp; 
     } 
    } 

    mapFile.close(); 
} 

//drawing the map onto the screen 
void Tilemap::drawMap(RenderWindow &window) 
{ 
    for (int y = 0; y < height; ++y) 
    { 
     for (int x = 0; x < width; ++x) 
     { 
      if (!data[x + y * width] == 0) 
      { 
       sprite.setPosition(x * 32, y * 32); 
       sprite.setTextureRect(IntRect(0, 0, tileWidth, tileHeight)); 
       window.draw(sprite); 
      } 
     } 
    } 

} 

//testing collision 
bool Tilemap::tileCollision(RenderWindow &window, RectangleShape &rect) 
{ 
    if (sprite.getGlobalBounds().intersects(rect.getGlobalBounds())) 
    { 
     cout << "Collision" << endl; 
    } 

    return true; 
} 

enter image description here

回答

0

代码,您只有一个精灵,你改变它的位置绘制它。好的,但是当你测试碰撞是否存在时,你可以用你设置为精灵的最新位置来测试碰撞。所以,你不应该与你的精灵测试碰撞。如果您仍然可以访问您的地图,请改用它。

编辑:

我看到您的帖子Using tiles in SFML and collision detection

顺丰::质地的资源,SF ::雪碧只是画类,这样你就可以创建很少纹理许多精灵。 (std::vector<std::vector<sf::Sprite>> map