Vector of unique pointers error, cannot be referenced after initialization - c++

I'm trying to create a matrix of rectangles in SFML and have them look like a floor. To do that, I want to use a vector of unique pointers. However, there seems to be an error I don't quite understand.
After successfully initializing the vector, it is declared deleted in the very same function. When I do a similar implementation but using new or shared pointers, there are no problems.
What is causing this error, and how can I fix it? The place of occurance is visible below:
Code:
sf::Texture texture;
texture.loadFromFile("./resources/wood.jpg");
std::vector<std::unique_ptr<sf::Sprite>> floor;
unsigned counter = 0;
float posX = 0.f, posY = 0.f;
for (int i = 0; i < 50; i++) {
floor.push_back(std::make_unique<sf::Sprite>());
floor[i]->setTexture(texture);
floor[i]->setTextureRect(sf::IntRect(1, 1, 100, 100));
floor[i]->setPosition(sf::Vector2f(posX, posY));
counter++;
posX += 100.f;
if (counter == 10) {
posY += 100.f;
posX = 0.f;
counter = 0;
}
}
while (window.isOpen()) {
sf::Event eH;
for (auto &sprite : floor)
window.draw(*sprite.get());
while (window.pollEvent(eH)) {
if (eH.type == sf::Event::Closed)
window.close();
if (eH.type == sf::Event::KeyReleased && eH.key.code == sf::Keyboard::Escape)
window.close();
if (eH.type == sf::Event::Resized)
glViewport(0, 0, eH.size.width, eH.size.height);
}
window.display();
window.clear(sf::Color::Black);
Error description:
'std::unique_ptr<sf::Sprite,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function

This line
for (auto sprite : floor)
attempts to copy each unique_ptr into sprite one by one, and unique_ptrs aren't copyable.
Use
for (auto &sprite : floor)
instead.

sf::Sprite is lightweight, you don't need to use std::unique_ptr<sf::Sprite>, just use sf::Sprite directly: std::vector<sf::Sprite> floor;
std::vector<sf::Sprite> floor;
...
floor.push_back(sf::Sprite());
floor[i].set...
...
for (auto const& sprite : floor)
window.draw(sprite);

Related

C++ SFML. How to create a diminishing(shrinking) circle

I have a class of circles that appear and disappear in the window for a while, there may be several, or maybe one. Currently drawn circles are stored in the vector_of_current_circles vector. I need to make them shrink to a certain size over time. How to do it?
window while loop:
while (window.isOpen()) {
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event)) {
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
for (int i = 0; i < vector_of_circles.size(); i++) {
if (std::fabs(vector_of_circles[i].getBeginOfLife() - clock.getElapsedTime().asSeconds()) < 1e-2) {
if (!vector_of_circles[i].get_is_drawn()) {
window.clear();
window.draw(sprite);
vector_of_current_circles.push_back(vector_of_circles[i]);
for (const auto &item : vector_of_current_circles) {
item.print_circle(window);
}
window.display();
vector_of_circles[i].set_is_drawn();
}
}
if (std::fabs(vector_of_circles[i].getEndOfLife() - clock.getElapsedTime().asSeconds()) < 1e-2) {
if (vector_of_circles[i].get_is_drawn()) {
vector_of_current_circles.erase(vector_of_current_circles.begin());
vector_of_circles[i].set_is_drawn();
}
window.clear();
window.draw(sprite);
for (const auto &item : vector_of_current_circles) {
item.print_circle(window);
}
window.display();
}
}
}
Here is Circle code:
private:
sf::CircleShape circle_;
//sf::Clock clock;
float begin_of_life_;
bool is_drawn_ = false;
float end_of_life_;
//sf::RenderWindow& window_;
public:
Circle();
void print_circle(sf::RenderWindow&) const;
float get_radius() const;
void set_position(float, float);
void set_texture(sf::Texture&);
void setBeginOfLife(float);
void setEndOfLife(float);
double getBeginOfLife() const;
double getEndOfLife() const;
bool get_is_drawn() const;
void set_is_drawn();
To reduce equaly a circl in a certain time with a certain speed, you need:
speed (speed_) value: the speed of the reduice of radius by second,
radius (radius_) value: the initial value of the radius.
Your circle need to have setOrigin to the center.
// your function to reduce a certain circle (class member)
void reduce()
{
float elapsed_time = ; // your time elapsed from the last call
// Getting the position of your center
// if you haven't set the origin to the center of the circle this code doesn't work
sf::Vector2f pos = circle_.getPosition();
radius_ -= (speed_ * elapsed_time); // calculating the new radius
circle_.setRadius(radius_); // set the new radius
circle_.setOrigin(sf::Vector2f(radius_ / 2, radius_ / 2)); // update the origine to the center
circle_.setPosition(pos); // not 100% sure that this line is used
}
Now you have a circle that reduce at a certain speed and staying in the same place.

SFML Collisions never register in my system

Trying to make a collision system in sfml for the first time in SFML without using a tutorial, using a array-based thing like so:
bool moright, moleft, moup, xcollision, ycollision;
float xvel, yvel;
int position, predictx, predicty, cm, arraynum;
class playerClass{
public:
playerClass(){
}
void update()
{
if (moright == true){
xvel = 2;}
if (moleft == true){
xvel = -2;}
if (!(moright || moleft)){
if (xvel < 0)
xvel = 0;
if (xvel > 0)
xvel = 0;}
}
};
int main()
{
playerClass playerObject;
// Create the main window
RenderWindow window(VideoMode(1080, 720), "SFML window");
// Load a sprite to display
Texture texture;
if (!texture.loadFromFile("gsquare100x100.png"))
return EXIT_FAILURE;
Sprite sprite(texture);
Sprite floor(texture);
Sprite wall(texture);
floor.setPosition(Vector2f(0.f, 498.f));
wall.setPosition(Vector2f(598.f,0.f));
floor.setColor(Color(0, 255, 0));
floor.setScale(12.f, 12.f);
wall.setScale(12.f, 12.f);
wall.setColor(Color(0, 0, 255));
int collisions[2][4]{
{0, 400, 500, 600},
};
// Start the game loop
while (window.isOpen())
{
Vector2f position = sprite.getPosition();
cout << position.y << endl;
predictx = position.x + xvel;
predicty = position.y + yvel;
yvel = 1;
for (arraynum = 0; arraynum < 2; arraynum++){
if ((predictx > collisions[arraynum][0])&&(predictx < collisions[arraynum][1])&&(predicty > collisions[arraynum][2])&&(predicty < collisions[arraynum][3])){
if ((position.y > collisions[arraynum][3])||(position.y < collisions[arraynum][2])){
xcollision = true;}
if ((position.x > collisions[arraynum][1])||(position.x < collisions[arraynum][0])){
ycollision = true;}
}
}
if (xcollision == true)
xvel = 0;
xcollision = false;
if (ycollision == true)
yvel = 0;
ycollision = false;
sprite.move(sf::Vector2f(0.f+xvel, 0.f+yvel));
// Process events
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == Event::KeyPressed)
{if (event.key.code == Keyboard::D)
moright = true;
if (event.key.code == Keyboard::A)
moleft = true;}
if (event.type == Event::KeyReleased)
{if (event.key.code == Keyboard::D)
moright = false;
if (event.key.code == Keyboard::A)
moleft = false;}
playerObject.update();
}
However the collision never registers, removing the bit that checks from which direction the sprite is moving in from doesn't help.
Very new to c++ so apologies if this is a stupid question and for my likely overly elaborate collision system.
I've written simple collisions with SFML before, and here's my advice to you: make your code as readable as possible! Things are going to get more complicated, and you need to have a system is reusable and easy to understand.
I've read your code but I don't understand why you've used an array. I assume you're trying to check if a smaller rectangle sprite is about to exit the collisions array?
For this purpose I suggest using a FloatRect object. It has useful functions like .contains() and .intersects() that you might need in the future. One downside it that is has top and left only, and to make it more and short, we'll define a simple struct to handle that part for us, as well as work for rectangular sprites as well.
I've left comments that explain the code, but haven't tested it personally. You can do that and integrate what you've learned into your project. Good luck
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
using namespace sf;
//using a struct is not necessarily faster. BUT it does give your code more readability and is reusable for future needs
//this struct just stores a floatRect of the given sprite/Floatrecct, defining some useful functions allowing for shorter code and more readability
struct rectangularShape
{
FloatRect containingRectangle;
//constructor with sprite input
rectangularShape(Sprite sprite)
{
this -> containingRectangle = FloatRect(Vector2f(sprite.getGlobalBounds().left, sprite.getGlobalBounds().top),
Vector2f(sprite.getGlobalBounds().left + sprite.getGlobalBounds().width,sprite.getGlobalBounds().top + sprite.getGlobalBounds().height));
}
//constructor with floatrect
rectangularShape(FloatRect rect)
{
this -> containingRectangle = rect;
}
//any useful functions for rectangular shapes-- you could add more if you want
float getTop() {return containingRectangle.top;}
float getbottom() {return containingRectangle.top + containingRectangle.height;}
float getleft() {return containingRectangle.left;}
float getright() {return containingRectangle.left + containingRectangle.width;}
};
//note the use of a FloatRect instead of the arrays you were using, this just makes it easier to understand
FloatRect inclusionArea(TopLeftVector, BottomRightVector);
Sprite sprite(texture);
//declare rectangularShapes, here we check if smallRectangle is exiting it's container
rectangularShape containingRectangle(inclusionArea);
rectangularShape smallRectangle(sprite);
//alternatively you can use the sprite's next position:
/*
spriteCopy = sprite;
spriteCopy.move(deltaTime * Vector2f(xSpeed, ySpeed));
rectangularShape smallRectangle(spriteCopy);
*/
//do the check:
if (smallRectangle.getTop() < containingRectangle.getTop() or smallRectangle.getBottom() > containingRectangle.getBottom())
//exiting in Y axis
//do something;
;
if (smallRectangle.getLeft() < containingRectangle.getLeft() or smallRectangle.getRight() > containingRectangle.getRight())
//exiting in X axis
//do something;
;
I can't comment due to low reputation.
From the code presented, it's seems like you never set xcollision or ycollision to true anywhere.

Write text input on the screen in SFML

So I'm creating a graphing calculator. I have an input string s. From the string, I can graph it using SFML. I start from the a MIN x-coordinate to a MAX x-coordinate, get the corresponding y from a EvaluateString() method, and all the coordinates to a VertexArray v. I wrote my method and the graphing method already and it all worked well.
However, I have a small issue. I want to input my string on the screen, such as "sin(cos(tan(x)))" like this. I'm struggling to find a way to do it. I kinda figured out it has to do with the event TextEntered, but still I can't find anything completely.
Please suggest me a way.
class Calculator{
public:
void main();
private:
WindowSize DefaultWindow;
sf::RenderWindow window;
Cartesian vertexX[2],vertexY[2];
sf::Vertex axis[4];
const double MAX = 10;
const double MIN = -10;
const double INCREMENT = 0.001;
};
int main(){
DefaultWindow.Max = Cartesian(10,10);
DefaultWindow.Min = Cartesian(-10,-10);
DefaultWindow.plane.width=1500;
DefaultWindow.plane.height=1500;
// Set up x and y-axis
vertexX[0] = Cartesian(-100,0);
vertexX[1] = Cartesian(100, 0);
vertexY[0] = Cartesian(0,-100);
vertexY[1] = Cartesian(0,100);
axis[0] = sf::Vertex(convertCartesiantoWindow(vertexX[0],DefaultWindow));
axis[1] = sf::Vertex(convertCartesiantoWindow(vertexX[1],DefaultWindow));
axis[2] = sf::Vertex(convertCartesiantoWindow(vertexY[0],DefaultWindow));
axis[3] = sf::Vertex(convertCartesiantoWindow(vertexY[1],DefaultWindow));
// Set up the window
window.create(sf::VideoMode(1500, 1500), "Graphing calculator");
// Input string
string s = "sin(cos(tan(x)))";
// Stack c contains all the Cartesian coordinate vertices
// Cartesian is a struct which contains x and y coordinates
Stack<Cartesian> c;
sf::VertexArray v;
// For a certain function in string s, I evaluate it
// and return the y_coordinate from the function EvaluateString (s, i)
// Push each (x,y) evaluated in the Stack c
for (double i = MIN; i <= MAX; i+= INCREMENT)
c.Push(Cartesian(i,EvaluateString(s,i)));
// v is VertexArray which contains all the vertices (x,y)
v = plot(DefaultWindow, c);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
}
}
}
// Draw the graph
window.clear(sf::Color::Black);
window.draw(axis,4,sf::Lines);
window.draw(v);
window.display();
}
As #super suggest, use a library would be a nice solution, and surely better than mine, but just in case this satisfies your needs, I implemented a super basic TextField class.
It may be plenty of errors, but it can gives you an idea on how to achieve that functionality.
A TextField is nothing more than a rectangle which contains a text. Since it will have a sf::Text, it must have a sf::Font. Additionally, I limit the number of characters that it will contain. In order for us to write inside the TextField, we have to know if it's selected, i.e. if it has the focus. So, a first approach could be:
class TextField : public sf::Transformable, public sf::Drawable{
private:
unsigned int m_size;
sf::Font m_font;
std::string m_text;
sf::RectangleShape m_rect;
bool m_hasfocus;
};
We need a constructor for this class:
class TextField : public sf::Transformable, public sf::Drawable{
public:
TextField(unsigned int maxChars) :
m_size(maxChars),
m_rect(sf::Vector2f(15 * m_size, 20)), // 15 pixels per char, 20 pixels height, you can tweak
m_hasfocus(false)
{
m_font.loadFromFile("C:/Windows/Fonts/Arial.ttf"); // I'm working on Windows, you can put your own font instead
m_rect.setOutlineThickness(2);
m_rect.setFillColor(sf::Color::White);
m_rect.setOutlineColor(sf::Color(127,127,127));
m_rect.setPosition(this->getPosition());
}
private:
unsigned int m_size;
sf::Font m_font;
std::string m_text;
sf::RectangleShape m_rect;
bool m_hasfocus;
};
We also need some basic methods, we want to get the text inside:
const std::string sf::TextField::getText() const{
return m_text;
}
and move it, placing it somewhere inside our window:
void sf::TextField::setPosition(float x, float y){
sf::Transformable::setPosition(x, y);
m_rect.setPosition(x, y);
}
this is a tricky one. We are overwritting setPosition method of sf::Transformable because we need to update our own m_rect.
Also, we need to know if a point is inside of the box:
bool sf::TextField::contains(sf::Vector2f point) const{
return m_rect.getGlobalBounds().contains(point);
}
pretty simple, we use cointains method of sf::RectangleShape, already in sfml.
Set (or unset) focus on the TextField:
void sf::TextField::setFocus(bool focus){
m_hasfocus = focus;
if (focus){
m_rect.setOutlineColor(sf::Color::Blue);
}
else{
m_rect.setOutlineColor(sf::Color(127, 127, 127)); // Gray color
}
}
easy one. For aesthetics, we also change the outline color of the box when focused.
And last, but not least, our TextField has to behave some way when input (aka an sf::Event) is received:
void sf::TextField::handleInput(sf::Event e){
if (!m_hasfocus || e.type != sf::Event::TextEntered)
return;
if (e.text.unicode == 8){ // Delete key
m_text = m_text.substr(0, m_text.size() - 1);
}
else if (m_text.size() < m_size){
m_text += e.text.unicode;
}
}
That delete key check is little dirty, I know. Maybe you can find better solution.
That's all! Now main looks like:
int main()
{
RenderWindow window({ 500, 500 }, "SFML", Style::Close);
sf::TextField tf(20);
tf.setPosition(30, 30);
while (window.isOpen())
{
for (Event event; window.pollEvent(event);)
if (event.type == Event::Closed)
window.close();
else if (event.type == Event::MouseButtonReleased){
auto pos = sf::Mouse::getPosition(window);
tf.setFocus(false);
if (tf.contains(sf::Vector2f(pos))){
tf.setFocus(true);
}
}
else{
tf.handleInput(event);
}
window.clear();
window.draw(tf);
window.display();
}
return 0;
}
Proof of concept:
std::string str;
sf::String text;
// In event loop...
if (event.Type == sf::Event::TextEntered)
{
// Handle ASCII characters only
if (event.Text.Unicode < 128)
{
str += static_cast<char>(event.Text.Unicode);
text.SetText(str);
}
}
// In main loop...
window.Draw(text);
This should create an sf::Event::TextEntered for input, and sf::String for output

SFML C++11 Trying to call a function in an object which is in a vector

So I am trying to make a simple shooter but so far i had no luck. I want to spawn bullets when the user presses right shift. And the bullets should fire at the top of the screen. The bullets do spawn but they dont move.
I created a vector to hold the created bullets named "bullets". Then I used the update function in my core struct to detect RShift presses and push an instance of the Bullet object to the vector.
Later on in my main class I iterate the vector and draw the bullets. But when I try calling the function it doesnt work.
My Code so far:
#include <SFML/Graphics.hpp>
#include <stdio.h>
const unsigned int ResX{480}, ResY{640};
struct Bullet {
sf::CircleShape shape;
Bullet(float sX, float sY, sf::Color color, float bullet_radius) {
shape.setRadius(bullet_radius);
shape.setOrigin(bullet_radius, bullet_radius);
shape.setFillColor(color);
shape.setPosition(sX, sY);
}
void update(float vel) {
sf::Vector2f velocity;
velocity.y = -abs(vel);
shape.move(velocity);
}
};
std::vector<Bullet> bullets;
struct Core {
const float core_width{64}, core_height{48}, core_velocity{0.2};
sf::RectangleShape shape;
sf::Vector2f velocity;
Core(float sX, float sY) {
shape.setSize({core_width, core_height});
shape.setPosition(sX, sY);
shape.setFillColor(sf::Color::White);
shape.setOrigin(core_width/2, core_height/2);
}
void update() {
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
velocity.x = -core_velocity;
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
velocity.x = core_velocity;
else
velocity.x = 0;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
velocity.y = -core_velocity;
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
velocity.y = core_velocity;
else
velocity.y = 0;
shape.move(velocity);
if(sf::Keyboard::isKeyPressed(sf::Keyboard::RShift)) {
Bullet b(shape.getPosition().x, shape.getPosition().y, sf::Color::Red, 5);
bullets.push_back(b);
}
}
};
int main(int argc, char *argv[])
{
sf::RenderWindow window(sf::VideoMode(ResX, ResY), "Brick Breaker", sf::Style::None);
Core core(ResX / 2, ResY /2 + 200);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
window.close();
}
std::printf("VelocityX=%f, BulletVelocity=\n",core.velocity.x);
window.clear();
core.update();
window.draw(core.shape);
for(const auto& b : bullets)
window.draw(b.shape);
//this function is causing an error : method update could not be resolved!
b.update();
window.display();
}
return 0;
}
btw i feel the need to say i am very very unexperienced with programming in c++ I am a complete beginner so any advice is welcome. srry 4 bad english. thanks!
EDIT: I figured it out thx! (The problem was that i missed the curly brackets:
for(const auto& b : bullets)
{
window.draw(b.shape);
//this function is causing an error : method update could not be resolved!
b.update();
}
But i have another question aswell! It would be awesome if one of you explained how the iterator functions and what purpose the auto& and const keywords serve here. Thanks again!

Implementing collision response, current implementation does too many checks

I don't know how I should handle my collision response when collision between two entities leads to second collision with third entity.
Blue arrow is velocity of the rightmost entity and numbers below are single collision response.
Single Collision
At the beginning leftmost and middle entities are not colliding with each others, but after rightmost entity collides with middle one, the velocity middle entity gains now causes it to collide with leftmost one
How end result should be
Or if the leftmost entity was a wall -> 0, 0, -v
Current implementation: check collisions until all are handled
Velocities before collision handling
0, 0, <-10
Collisions: 2&3
If entity velocity is changed due the collision do new check
After 1. collision check:
0, <-5, <-5
Collisions: 1&2
After 2. collision check:
<-2.5, <-2.5, <-5
Collisions: 2&3
After 3. collision check:
<-2.5, <-3.75, <-3.75
Collisions: 1&2
After 4. collision check:
<-3.125, <-3.125, <-3.75
Collisions: 2&3
After nth collision check:
<-3.33, <-3.33, <-3.33
No collisions
Continue
Question: As we clearly see, it takes way too many collision checks to fix even simple collisions this way. How should I improve this?
Sample code written with sfml:
I have 3 types of entities in my test case:
wall
pushable
passable
Entity, velocity and boundingRect:
Collision response:
wall <-> pushable: can't move inside wall, push pushable entity away
pushable <-> pushable: both are repelled from each others so they won't collide
wall<->wall: skip collision checks between walls and all checks with passable terrain
Controls in sample code
Arrow keys: move green entity
Left mouse button: spawn pushable entities
Right mouse button: spawn wall entities
Middle mouse button: spawn moving pushable entities
.
#include <SFML/Graphics.hpp>
#include <iostream>
const sf::Vector2f entitySize(16.f, 16.f);
bool isMovingUp = false;
bool isMovingDown = false;
bool isMovingRight = false;
bool isMovingLeft = false;
enum Category
{
wall,
pushable,
passable,
};
class Entity
{
public:
Entity(sf::Vector2f position, sf::Color color, Category type) : position(position), type(type)
{
shape.setSize(entitySize);
shape.setFillColor(sf::Color::Transparent);
shape.setOutlineColor(color);
shape.setOutlineThickness(1.f);
}
sf::Vector2f position;
sf::Vector2f velocity;
sf::Vector2f adjustedVelocity;
sf::Vector2f defaultVelocity;
sf::RectangleShape shape;
Category type;
};
void DrawEntity(sf::RenderWindow& window, Entity& entity)
{
entity.shape.setPosition(entity.position - entity.shape.getSize() / 2.f);
window.draw(entity.shape);
}
sf::FloatRect GetBoundingRect(const Entity& entity)
{
return sf::FloatRect(entity.position+entity.velocity - entitySize / 2.f, entitySize);
}
void HandleCollision(std::vector<Entity>& entities)
{
bool allCollisionsChecked = false;
while(!allCollisionsChecked)
{
allCollisionsChecked = true;
// Pair all possible combinations, but only once per pair
for (auto first = entities.begin(); first != entities.end(); ++first)
{
for (auto second = std::next(first); second != entities.end(); ++second)
{
if (first->type == Category::passable || second->type == Category::passable || first->type == Category::wall && second->type == Category::wall)
continue;
sf::FloatRect intersection;
if (GetBoundingRect(*first).intersects(GetBoundingRect(*second), intersection))
{
if (second->position == first->position)
second->position.x += entitySize.x;
sf::Vector2f direction = second->position - first->position;
sf::Vector2f offset;
// X collision
if (abs(direction.x) > abs(direction.y))
offset.x = ((direction.x<0)?-1:1)*intersection.width;
// Y collision
if (abs(direction.x) < abs(direction.y))
offset.y = ((direction.y<0)?-1:1)*intersection.height;
if(first->type == Category::pushable && second->type == Category::pushable)
{
first->velocity -= offset / 2.f;
second->velocity += offset / 2.f;
allCollisionsChecked = false;
}
else if(first->type == Category::pushable)
{
first->velocity -= offset;
allCollisionsChecked = false;
}
else if(second->type == Category::pushable)
{
second->velocity += offset;
allCollisionsChecked = false;
}
}
}
}
}
}
void handlePlayerInput(sf::Keyboard::Key key, bool isPressed)
{
switch(key)
{
case sf::Keyboard::Up:
isMovingUp = isPressed;
break;
case sf::Keyboard::Down:
isMovingDown = isPressed;
break;
case sf::Keyboard::Left:
isMovingLeft = isPressed;
break;
case sf::Keyboard::Right:
isMovingRight = isPressed;
break;
}
}
int main()
{
sf::RenderWindow window(sf::VideoMode(1280, 720), "SFML Application");
window.setVerticalSyncEnabled(true);
std::vector<Entity> entities;
Entity player(sf::Vector2f(1280/2, 720/2), sf::Color::Green, Category::pushable);
entities.push_back(player);
size_t cols = 1280/int(entitySize.x);
size_t rows = 720/int(entitySize.y);
for (size_t i=0; i < cols*rows; ++i)
if (i%cols == rows/5 && i/cols > rows/6 && i/cols < rows*5/6 || i%cols >= rows/5 && i%cols <= rows*4/5 && (i/cols == rows/6 || i/cols == rows*5/6))
entities.push_back(Entity(sf::Vector2f(entitySize.x*(i%cols)+entitySize.x/2, entitySize.y*(i/cols)+entitySize.y/2), sf::Color::Yellow, Category::wall));
//else
//entities.push_back(Entity(sf::Vector2f(entitySize.x*(i%cols)+entitySize.x/2, entitySize.y*(i/cols)+entitySize.y/2), sf::Color::Transparent, Category::passable));
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::MouseButtonPressed)
{
sf::Vector2i pixel(event.mouseButton.x, event.mouseButton.y);
sf::Vector2f coord = window.mapPixelToCoords(pixel);
if (event.mouseButton.button == sf::Mouse::Left)
{
Entity pushable(coord, sf::Color::Blue, Category::pushable);
entities.push_back(pushable);
}
else if (event.mouseButton.button == sf::Mouse::Right)
{
Entity wall(coord, sf::Color::Yellow, Category::wall);
entities.push_back(wall);
}
else if (event.mouseButton.button == sf::Mouse::Middle)
{
Entity mover(coord, sf::Color::Magenta, Category::pushable);
mover.defaultVelocity.x = -1.f;
entities.push_back(mover);
}
}
switch (event.type)
{
case sf::Event::KeyPressed:
handlePlayerInput(event.key.code, true);
break;
case sf::Event::KeyReleased:
handlePlayerInput(event.key.code, false);
break;
case sf::Event::Closed:
window.close();
break;
}
}
if (isMovingUp)
entities[0].velocity.y -= 5.f;
if (isMovingDown)
entities[0].velocity.y += 5.f;
if (isMovingLeft)
entities[0].velocity.x -= 5.f;
if (isMovingRight)
entities[0].velocity.x += 5.f;
if (entities[0].velocity.x != 0.f && entities[0].velocity.y != 0.f)
{
entities[0].velocity.x /= std::sqrt(2.f);
entities[0].velocity.y /= std::sqrt(2.f);
}
HandleCollision(entities);
// Apply and reset velocities
for (Entity& e : entities)
{
e.position += e.velocity;
e.velocity = e.defaultVelocity;
}
// Draw
window.clear();
for (Entity& e : entities)
DrawEntity(window, e);
window.display();
}
}
Sample results
Magenta entities are moving to the left with constant speed and yellow entities are wall.
without checking collisions due the other collisions
Desired outcome:
Same scenario when checking collisions until all are resolved
How could I achieve this?