I made collision detection... but... it always teleports my rectangle to left side of rectangle that is colliding with my rectangle...
Whole code:
// Building Blocks.cpp : main project file.
#include "stdafx.h"
#include "SFML/Window.hpp"
#include "SFML/Graphics.hpp"
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <algorithm>
using namespace System;
using namespace MySql::Data::MySqlClient;
class Player
{
public:
sf::RectangleShape rect;
float left, top, right, bottom;
Player(sf::Vector2f position, sf::Vector2f size, sf::Color color)
{
rect.setPosition(position);
rect.setSize(size);
rect.setFillColor(color);
}
void update()
{
left = rect.getPosition().x;
top = rect.getPosition().y;
bottom = rect.getPosition().y + rect.getSize().y;
right = rect.getPosition().x + rect.getSize().x;
}
bool collision(Player p)
{
if (right < p.left || left > p.right || top > p.bottom || bottom < p.top)
{
return false;
}
if (collisionLeft(p))
{
Console::WriteLine("COLLISION: LEFT");
}
else if (collisionTop(p))
{
Console::WriteLine("COLLISION: TOP");
}
else if (collisionBottom(p))
{
Console::WriteLine("COLLISION: BOTTOM");
}
else if (collisionRight(p))
{
Console::WriteLine("COLLISION: RIGHT");
}
return true;
}
bool collisionRight(Player p)
{
if (right < p.left)
{
return false;
}
rect.setPosition(p.right, top);
return true;
}
bool collisionLeft(Player p)
{
if (left > p.right)
{
return false;
}
rect.setPosition(p.left - 16, top);
return true;
}
bool collisionTop(Player p)
{
if (top > p.bottom)
{
return false;
}
rect.setPosition(left, p.top - 16);
return true;
}
bool collisionBottom(Player p)
{
if (bottom < p.top)
{
return false;
}
rect.setPosition(left, p.bottom);
return true;
}
};
int main(array<System::String ^> ^args)
{
#pragma region Other Settings
Console::WriteLine(L"- Collision");
sf::RenderWindow window;
window.create(sf::VideoMode(600, 400), L"Test Collision", sf::Style::Titlebar | sf::Style::Close);
#pragma endregion
Player p(sf::Vector2f(10, 10), sf::Vector2f(16, 16), sf::Color(0, 255, 0));
Player block(sf::Vector2f(100, 100), sf::Vector2f(48, 48), sf::Color(255, 0, 0));
while (window.isOpen())
{
#pragma region EVENTS
sf::Event event;
if (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
#pragma endregion
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
p.rect.move(0, 1.f);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
p.rect.move(0, -1.f);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
p.rect.move(1.f, 0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
p.rect.move(-1.f, 0);
p.update();
block.update();
if (p.collision(block))
{
//p.rect.setPosition(p.left, block.top - 16);
}
window.clear();
window.draw(p.rect);
window.draw(block.rect);
window.display();
}
return 0;
}