'The texture of the player does not changing
In the code I wrote, the collision is detected correctly, but only 1 enemy changes players texture. What is the reason and how can I change players texture for every enemy? The problem is between lines 56 and 64 of the code.
Screenshots :
Collision but texture isn't change
Collision and players texture is changed
My code :
#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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
