rafamont
@rafamont
Junior BackEnd

Колизия спрайта к окну?

Как сделать коллизию персонажа к окну(чтобы отталкивало от окна)?
Можете на коде показать?
Картинки
Есть код:
#include<SFML\Main.hpp>
#include<SFML\Graphics.hpp> // SFML графика
#include<SFML\System.hpp>
#include<Windows.h>// Виндовс библиотека
#include<cstdlib>// rand(), srand()
#include<ctime>// Time

// НЕЙМСПЕЙСЫ
using namespace sf;

// ПЕРЕМЕННЫЕ И КОНСТАНТЫ
int speed = 7;
int width = 800;
int height = 600;
int currentFrame = 0;
int HeroDemensionX = 50;
int HeroDirection;
int HeroDementionY = height - 150;
int CW = 43;
int CH = 43;
int ScaleX;
int ScaleY;
float Scale;
int RandW;
int RandH;
int Scope;





int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { // WINAPI Скрытие консоли

	

	// ---------------------------- ЯЗЫК ---------------------------- //

	setlocale(LC_ALL, "Russian");

	// ---------------------------- Создание окна,настройка FPS,другие объекты ---------------------------- //

	sf::RenderWindow window(sf::VideoMode(width, height), "Game, get the monet"); // Создание окна
	window.setFramerateLimit(60); // К-ство FPS
	sf::Clock clock; // clock


	// ---------------------------- НАСТРОЙКИ ПЕРСОНАЖА ---------------------------- //

	sf::Image image; // Personaj
	sf::Texture texture; // Personaj
	sf::Sprite sprite; // Personaj
	image.loadFromFile("images/image.png");//Загружаем картинку
	texture.loadFromImage(image);
	sprite.setTexture(texture);
	sprite.setPosition(HeroDemensionX, HeroDementionY);
	sprite.setTextureRect(IntRect(0, 0, 64, 96));

	// ---------------------------- НАСТРОЙКИ МОНЕТКИ ---------------------------- //

	srand(time(NULL));
	int RandW = rand() % 700;
	int RandH = rand() % 500;
	sf::Image coinI; // Moneta
	sf::Texture coinT; // Moneta
	sf::Sprite coinS; // Moneta
	coinI.loadFromFile("images/coin.png");
	coinT.loadFromImage(coinI);
	coinS.setTexture(coinT);
	coinS.setPosition(RandW, RandH);
	coinS.setTextureRect(IntRect(0, 0, CW, CH));


	// Оставить окно открытым
	while (window.isOpen())
	{
		int time = clock.getElapsedTime().asMicroseconds();
		clock.restart();
		time /= 800;

		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}

		sf::FloatRect spriteBounds = sprite.getGlobalBounds();
		sf::FloatRect circleBounds = coinS.getGlobalBounds();

		if (spriteBounds.intersects(circleBounds))
		{
			coinS.setPosition(rand() % width, rand() % height);
			Scope++;
		}

		// КЛАВИАТУРА ( КОМБИНАЦИИ КЛАВИШ ДЛЯ УПРАВЛЕНИЯ ) -------------------------------------------
		// КНОПКА "А", СТРЕЛКА ВЛЕВО

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) || sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
			HeroDirection = 0;
			currentFrame += 0.005*time;
			if (currentFrame > 4) currentFrame -= 4;
			sprite.setTextureRect(sf::IntRect(int(currentFrame) * 64, 96, 64, 96));
			sprite.move(-speed, 0);

		}

		// КНОПКА "D", СТРЕЛКА ВПРАВО

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) || sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
			HeroDirection = 1;
			currentFrame += 0.005*time;
			if (currentFrame > 4) currentFrame -= 4;
			sprite.setTextureRect(sf::IntRect(int(currentFrame) * 64, 192, 64, 96));
			sprite.move(speed, 0);

		}

		// КНОПКА "W", СТРЕЛКА ВПЕРЕД

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
		{
			HeroDirection = 2;
			currentFrame += 0.005*time;
			if (currentFrame > 4) currentFrame -= 4;
			sprite.setTextureRect(sf::IntRect(int(currentFrame) * 64, 288, 64, 96));
			sprite.move(0, -speed);
		}

		// КНОПКА "S", СТРЕЛКА НАЗАД

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
		{
			HeroDirection = 3;
			currentFrame += 0.005*time;
			if (currentFrame > 4) currentFrame -= 4;
			sprite.setTextureRect(sf::IntRect(int(currentFrame) * 64, 0, 64, 96));
			sprite.move(0, speed);
		}

		window.clear();
		window.draw(coinS);
		window.draw(sprite);
		window.display();
	}
}
  • Вопрос задан
  • 209 просмотров
Решения вопроса 1
@steelflame
С самим кодом не помогу(c++ не знаю), но объясню как должно происходить на примере pascal -

//проверка на столкновение с правой стороной
if (x >= [координаты границы окна]-[ширина игрока]) then x:=[координаты границы окна];

//проверка на столкновение с левой стороной
if (x <= 0[<-- координата окна]) then x:=0;

//проверка на столкновение с верхней стороной
if (x >= 0[<-- координаты окна]) then x:=0;

//проверка на столкновение с нижней стороной
if (x >= [координаты границы окна]-[ширина игрока]) then x:=[координаты границы окна];
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы