2013-09-22 61 views
0

我一直在使用sfml 2.0庫的oop版本的蛇,我有一個單獨的類來處理碰撞。下面的代碼:SFML 2.0碰撞類

包括「collision.hpp」

bool sfc::Sprite::collision(sfc::Sprite sprite2) { 
    this->setBounds(); 
    sprite2.setBounds(); 

    if (top > sprite2.bottom || bottom < sprite2.top || left > sprite2.right || right < sprite2.left) { 
    return false; 
    } 

    return true; 
} 

void sfc::Sprite::colMove(sf::Vector2f &movement, sfc::Sprite sprite2) { 
    if (!this->collision(sprite2)) { 
    this->move(movement); 
    } 
} 

void sfc::Sprite::colMove(float x, float y, sfc::Sprite sprite2) { 
    if (!this->collision(sprite2)) { 
    this->move(x, y); 
    } 
} 

void sfc::Sprite::setBounds() { 
    top = this->getPosition().y; 
    bottom = this->getPosition().y + this->getTexture()->getSize().y; 
    left = this->getPosition().x; 
    right = this->getPosition().x + this->getTexture()->getSize().y; 
} 

唯一的問題是,一旦碰撞事件發生時,精靈被卡住窗口的餘生。我怎麼能得到它,以便在碰撞時它不會粘在那裏。謝謝! 〜邁克爾

編輯:據我所知,精靈是不允許移動發生碰撞後,但我不知道任何其他方式停止移動後的精靈的衝突。

回答

2

你的問題是,一旦你的精靈進入與你的精靈2碰撞,它不能再移動。如果您檢測到碰撞,您可以嘗試將移動恢復到前一個x和y。或者檢查你將移動到的地方是否爲空。

bool sfc::Sprite::collision(sfc::Sprite sprite2, float x, float y) { 
    this->setBounds(); 
    sprite2.setBounds(); 

    if (top > sprite2.bottom + y || bottom < sprite2.top - y || left > sprite2.right +x|| right < sprite2.left - y) { 
    return false; 
    } 

    return true; 
} 

這是碰撞,然後

void sfc::Sprite::colMove(float x, float y, sfc::Sprite sprite2) { 
    if (!this->collision(sprite2, x, y)) { 
    this->move(x, y); 
    } 
} 

注:我沒記錯的使用SFML因此檢查+和座標系 -

+0

可惜,這是行不通的。我明白我的精靈在碰撞後不允許移動,但你上面發佈的代碼只會在碰撞發生之前改變兩個精靈之間的距離。 – Michaelslec

+0

哦,我明白了。我不記得太多關於smfl的信息,但是我希望它對你有所幫助 – th3sn4k3

+0

謝謝你的回答!我很感激 :) – Michaelslec