播放器的纹理不会改变



在我写的代码中,碰撞被正确检测到,但只有一个敌人改变了玩家的纹理原因是什么?我如何更改每个敌人的玩家纹理问题出现在代码的第56行和第64行之间。

屏幕截图:

无碰撞

碰撞但纹理没有改变

碰撞和玩家纹理改变

我的代码:

#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个敌人。

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

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

最新更新