SFML и C++ Уроки \ Разработка игр › Форумы › SFML Graphics › Проблема со следованием камеры за персоонажем.
Помечено: камера
В этой теме 16 ответов, 2 участника, последнее обновление Heisenberg 8 года/лет, 3 мес. назад.
-
АвторСообщения
-
Начну с того что делается гонка, вид сверху. я сначала долбился с обычным OpenGL , увидел эту библиотеку и уроки и тут понеслось…
Суть. автомобиль перемещается по следующему закону sprite.move(cos(PI / 180 * ang) *currentSpeed*time, sin(PI / 180 * ang) *currentSpeed*time);
первую головную боль я словил потому что у меня нет привязки к координатам спрайта, просто задается начальный пункт откуда поедем.
впрочем потом нашел sprite.GetPosition(); начал делать непосредственно перемещение камеры. насколько я понял обьект класса view содержит метод setCenter в котором есть 2 способа задания вектор и указатель на точку или просто х и у. пробовал 2мя способами, для теста задал просто 2 числа, сделал вызов перед очисткой window.setView (view) не работает! просто пустой экран. может быть я где то что то пропустил , подскажите что нужно для минимума запуска отображения данным способом. код будет чуть позже.
После инициализации окна
C++12cam.reset(sf::FloatRect(0.f, 0.f, 800, 600));window.setView(cam);В игровом цикле
C++1cam.setCenter(hero.getPosition());то есть window.setView() задается не в цикле? в уроке было сказано перед очисткой экрана его делать.
Верно, перед очисткой экрана.
C++12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273while (window.isOpen()){float time = clock.getElapsedTime().asMicroseconds();clock.restart();time = time / 800;sf::Event event;while (window.pollEvent(event)){if (event.type == sf::Event::Closed)window.close();}///////////////////////////////////////////Управление персонажем с анимацией////////////////////////////////////////////////////////////////////////if (Keyboard::isKeyPressed(Keyboard::Left)) {p.dir = 1; p.speed = 0.1;CurrentFrame += 0.005*time;if (CurrentFrame > 3) CurrentFrame -= 3;p.sprite.setTextureRect(IntRect(96 * int(CurrentFrame), 96, 96, 96));getplayercoordinateforview(p.getplayercoordinateX(), p.getplayercoordinateY());//передаем координаты игрока в функцию управления камерой}if (Keyboard::isKeyPressed(Keyboard::Right)) {p.dir = 0; p.speed = 0.1;CurrentFrame += 0.005*time;if (CurrentFrame > 3) CurrentFrame -= 3;p.sprite.setTextureRect(IntRect(96 * int(CurrentFrame), 192, 96, 96));getplayercoordinateforview(p.getplayercoordinateX(), p.getplayercoordinateY());//передаем координаты игрока в функцию управления камерой}if (Keyboard::isKeyPressed(Keyboard::Up)) {p.dir = 3; p.speed = 0.1;CurrentFrame += 0.005*time;if (CurrentFrame > 3) CurrentFrame -= 3;p.sprite.setTextureRect(IntRect(96 * int(CurrentFrame), 288, 96, 96));getplayercoordinateforview(p.getplayercoordinateX(), p.getplayercoordinateY());//передаем координаты игрока в функцию управления камерой}if (Keyboard::isKeyPressed(Keyboard::Down)) {p.dir = 2; p.speed = 0.1;CurrentFrame += 0.005*time;if (CurrentFrame > 3) CurrentFrame -= 3;p.sprite.setTextureRect(IntRect(96 * int(CurrentFrame), 0, 96, 96));getplayercoordinateforview(p.getplayercoordinateX(), p.getplayercoordinateY());//передаем координаты игрока в функцию управления камерой}p.update(time);viewmap(time);//функция скроллинга карты, передаем ей время sfmlchangeview();//прикалываемся с камерой вида<strong>setView(view)</strong>;//"оживляем" камеру в окне sfml ЦИКЛ ЕСЛИ Я ПРАВИЛЬНО ПОСЧИТАЛ СКОБКИ{})))window.clear();/////////////////////////////Рисуем карту/////////////////////for (int i = 0; i < HEIGHT_MAP; i++)for (int j = 0; j < WIDTH_MAP; j++){if (TileMap[i][j] == ' ') s_map.setTextureRect(IntRect(0, 0, 32, 32));if (TileMap[i][j] == 's') s_map.setTextureRect(IntRect(32, 0, 32, 32));if ((TileMap[i][j] == '0')) s_map.setTextureRect(IntRect(64, 0, 32, 32));s_map.setPosition(j * 32, i * 32);window.draw(s_map);}window.draw(p.sprite);window.display();}или вы имели ввиду другой цикл какой то. но если я правильно скобки посчитал, то вот он цикл. инициализация окна выше. так куда его пихать то?
WTF?
setView(view);//”оживляем” камеру в окне sfml ЦИКЛ ЕСЛИ Я ПРАВИЛЬНО ПОСЧИТАЛ СКОБКИ{})))
//===_NEED
//========
window.setView(view);
window.clear();
window.draw(spirt);
window.display();
}Где вы инициализировали вид камеры view.reset(sf::FloatRect&);?
C++12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849void main(){LoadTrack();Clock clock;RenderWindow window(sf::VideoMode(640, 480), "2D Racing");view.reset(sf::FloatRect(0, 0, 640, 480));Player p("car.png", 25, 50, 206, 142, 1, 0, 0, 0, 0, 0, 0);p.sprite.setPosition(p.x, p.y);p.sprite.setOrigin(p.w / 3, p.h / 2);Image map_image;map_image.loadFromFile("images/map.png");Texture map;map.loadFromImage(map_image);Sprite s_map;s_map.setTexture(map);while (window.isOpen()){float time = clock.getElapsedTime().asMicroseconds();clock.restart();time = time / 800;sf::Event event;while (window.pollEvent(event)){if (event.type == sf::Event::Closed)window.close();}if (Keyboard::isKeyPressed(Keyboard::Up)) { p.sprite.move(cos(PI / 180 * p.ang)*0.3*time, sin(PI / 180 * p.ang)*0.3*time); }if (Keyboard::isKeyPressed(Keyboard::Down)) { p.sprite.move(cos(PI / 180 * p.ang)*-0.1*time, sin(PI / 180 * p.ang)*-0.1*time); }if (Keyboard::isKeyPressed(Keyboard::Left)) { p.ang = p.ang - 0.2; p.sprite.setRotation(p.ang); }if (Keyboard::isKeyPressed(Keyboard::Right)) { p.ang = p.ang + 0.2; p.sprite.setRotation(p.ang); }view.setCenter(p.sprite.getPosition());window.setView(view);window.clear(Color(100,20,250));for (int i = 0; i < WIDTH_MAP; i++)for (int j = 0; j < HEIGHT_MAP; j++){if (trackMaxrix[i][j] == 0) s_map.setTextureRect(IntRect(0, 0, 32, 32));if (trackMaxrix[i][j] == 1) s_map.setTextureRect(IntRect(32, 0, 32, 32));if ((trackMaxrix[i][j] == 2)) s_map.setTextureRect(IntRect(64, 0, 32, 32));if ((trackMaxrix[i][j] == 3)) s_map.setTextureRect(IntRect(96, 0, 96, 96));if ((trackMaxrix[i][j] == 4)) s_map.setTextureRect(IntRect(128, 0, 128, 128));s_map.setPosition(j * 32, i * 32);window.draw(s_map);}window.draw(p.sprite);window.display();}}Вложения:
You must be logged in to view attached files.результаты работы. без коммента и что должно быть
Вложения:
You must be logged in to view attached files.Скинь проект, у себя гляну.
не помню доделал процедурное программирование или нет
Залей на облако, к примеру ЯД.
Перенесите
View view;
в main и всё заработает.Из глобальной области не хочет работать.
Вот рабочий вариант
C++123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134#include <SFML/Graphics.hpp>#include "map.h"#include <iostream>#include <fstream>#include <math.h>#define PI 3.14159265using namespace sf;sf::Time t1 = sf::microseconds(10000);float resistance = 0.1 ;class Player{public:float w, h, x, y,currentSpeed, maxSpeed, weight, power, braking, controllability, clutch, acceleraation;float ang;String file;Image image;Texture texture;Sprite sprite;Player(String File, int X, int Y, int W, int H, float Weight, float Power, float Braking, float Controllability, float Clutch, float Acceleraation, float Ang);~Player();int getPlayerCoortdsX(){return x;}int getPlayerCoortdsY(){return y;}void CarMove(float time){sprite.move(cos(PI / 180 * ang)*currentSpeed*time, sin(PI / 180 * ang)*currentSpeed*time);if (Keyboard::isKeyPressed(Keyboard::Left)) { sprite.setRotation(ang); }if (Keyboard::isKeyPressed(Keyboard::Right)) { sprite.setRotation(ang); }}void CarCalculations(){maxSpeed = power / weight * 2;if (Keyboard::isKeyPressed(Keyboard::Up)){acceleraation = power * controllability * clutch / weight / 100;currentSpeed = currentSpeed + acceleraation;}else{if (currentSpeed > 0)currentSpeed = currentSpeed - resistance * controllability / weight * 10;elsecurrentSpeed = 0;}if (Keyboard::isKeyPressed(Keyboard::Down)){if (currentSpeed > 0){acceleraation = 0;currentSpeed = currentSpeed - braking * controllability * resistance / weight;}elsecurrentSpeed = -0.05;}if (currentSpeed > 0.001 || currentSpeed < -0.001){if (Keyboard::isKeyPressed(Keyboard::Left)) { ang = ang - 0.2; }if (Keyboard::isKeyPressed(Keyboard::Right)) { ang = ang + 0.2; }}if (currentSpeed > maxSpeed) currentSpeed = maxSpeed;}};Player::Player(String File, int X, int Y, int W, int H, float Weight, float Power, float Braking, float Controllability, float Clutch, float Acceleraation, float Ang){currentSpeed = 0;file = File;x = X; y = Y; w = W; h = H; weight = Weight; power = Power; braking = Braking;controllability = Controllability; clutch = Clutch; acceleraation = Acceleraation; ang = Ang;image.loadFromFile("images/" + file);texture.loadFromImage(image);sprite.setTexture(texture);sprite.setTextureRect(IntRect(0, 0, w, h));}Player::~Player(){}void main(){View view;LoadTrack();Clock clock;RenderWindow window(sf::VideoMode(800, 600), "2D Racing");view.reset(sf::FloatRect(0, 0, 640, 480));Player p("car.png", 250, 200, 206, 142, 650, 150, 1.5, 0.65, 0.5, 0, 0);p.sprite.setPosition(p.x, p.y);p.sprite.setOrigin(p.w / 3, p.h / 2);Image map_image;map_image.loadFromFile("images/map.png");Texture map;map.loadFromImage(map_image);Sprite s_map;s_map.setTexture(map);while (window.isOpen()){float time = clock.getElapsedTime().asMicroseconds();clock.restart();time = time / 800;sf::Event event;while (window.pollEvent(event)){if (event.type == sf::Event::Closed)window.close();}p.CarCalculations();p.CarMove(time);view.setCenter(p.sprite.getPosition());window.setView(view);window.clear(Color(100,20,250));for (int i = 0; i < WIDTH_MAP; i++)for (int j = 0; j < HEIGHT_MAP; j++){if (trackMaxrix[i][j] == 0) s_map.setTextureRect(IntRect(0, 0, 32, 32));if (trackMaxrix[i][j] == 1) s_map.setTextureRect(IntRect(32, 0, 32, 32));if ((trackMaxrix[i][j] == 2)) s_map.setTextureRect(IntRect(64, 0, 32, 32));if ((trackMaxrix[i][j] == 3)) s_map.setTextureRect(IntRect(96, 0, 96, 96));if ((trackMaxrix[i][j] == 4)) s_map.setTextureRect(IntRect(128, 0, 128, 128));s_map.setPosition(j * 32, i * 32);window.draw(s_map);}window.draw(p.sprite);window.display();}}о чет не подумал, спасибо, все воркс)))
-
АвторСообщения
Для ответа в этой теме необходимо авторизоваться.