播放器的纹理没有改变

The texture of the player does not changing

在我写的代码中,正确检测到碰撞,但只有 1 个敌人改变了玩家纹理。 这是什么原因,我怎样才能为每个敌人改变玩家的纹理?问题出在行56和64[=之间代码的 31=]。

截图:

No collision

Collision but texture isn't change

Collision and players texture is changed

我的代码:

#include <iostream>
#include <stdlib.h>
#include <SFML/Graphics.hpp>

using namespace sf;

int main(){

    RenderWindow window(VideoMode(500,500), "Game");
    window.setFramerateLimit(100);

    Texture playerTexture;
    playerTexture.loadFromFile("./images/player.png");
    Texture collisionPlayerTexture;
    collisionPlayerTexture.loadFromFile("./images/collision_player.png");
    Texture enemyTexture;
    enemyTexture.loadFromFile("./images/enemy.png");

    Sprite player;
    player.setTexture(playerTexture);
    player.setTextureRect(IntRect(50,50,50,50));
    player.setPosition(225,225);

    Sprite enemies[5] = {Sprite(),Sprite(),Sprite(),Sprite(),Sprite()};
    for(int i=0;i<5;i++){
        enemies[i].setTexture(enemyTexture);
        enemies[i].setTextureRect(IntRect(25,25,25,25));
        enemies[i].setPosition(rand() % 475,rand() % 475);
    }

    while(window.isOpen()){

        Event event;
        while(window.pollEvent(event)){
            switch(event.type){
                case Event::Closed:
                    window.close();
            }
        }

        if(Keyboard::isKeyPressed(Keyboard::W) || Keyboard::isKeyPressed(Keyboard::Up)){
            player.move(0.0f,-1.5f);
        }
        if(Keyboard::isKeyPressed(Keyboard::S) || Keyboard::isKeyPressed(Keyboard::Down)){
            player.move(0.0f,1.5f);
        }
        if(Keyboard::isKeyPressed(Keyboard::A) || Keyboard::isKeyPressed(Keyboard::Left)){
            player.move(-1.5f,0.0f);
        }
        if(Keyboard::isKeyPressed(Keyboard::D) || Keyboard::isKeyPressed(Keyboard::Right)){
            player.move(1.5f,0.0f);
        }

        window.clear(Color(255,255,255));

        //////////////////////////////////////////////This is where I'm talking about//////////////////////////////////////////////

        for(int i=0;i<5;i++){
            if(player.getGlobalBounds().intersects(enemies[i].getGlobalBounds())){
                std::cout << "Collision"; // This is working
                player.setTexture(collisionPlayerTexture); // But this line only works for an enemy
            } else {
                player.setTexture(playerTexture);
            }
            window.draw(enemies[i]);
        }

        //////////////////////////////////////////////This is where I'm talking about//////////////////////////////////////////////

        window.draw(player);
        window.display();
    }
    return 0;
}

在你的循环中

    for(int i=0;i<5;i++){

您正在遍历所有 5 个敌人。

如果您检测到与最后一个碰撞,则更改纹理并退出循环。但是如果碰撞是与任何其他敌人发生的,下一个循环迭代将恢复纹理。

解决方案:如果检测到碰撞,您可能希望break;退出循环。