hello i am making a pong game and i need to compare the x position of the panel to the x position of the ball. but if i use GetPosition() the x value for the panels is always 0 so i can't really compare them that way. i believe i need some kind of conversion. but i don't know which. i have tried to use TransformToGlobal but that didn't work.
below is the code (minimalisezed)
sf::Vector2f pos = ball.TransformToGlobal(ball.GetPosition());
sf::Vector2f pos1 = panel1.TransformToGlobal(panel1.GetPosition());
sf::Vector2f pos2 = panel2.TransformToGlobal(panel2.GetPosition());
std::cout<<pos1.x<<","<<pos1.y<<std::endl;
std::cout<<pos2.x<<","<<pos2.y<<std::endl;
it outputs always something like this
0,122
0,-101
full code under this if someone wants to test:
#include "stdafx.h"
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
// Create main window
sf::RenderWindow App(sf::VideoMode(800, 600), "SFML Shapes"/*, sf::Style::Fullscreen*/);
//define shapes
sf::Shape panel1=sf::Shape::Rectangle(20, 300, 30, 360, sf::Color::White);
sf::Shape panel2=sf::Shape::Rectangle(770, 300, 780, 360, sf::Color::White);
sf::Shape ball=sf::Shape::Circle(395, 330, 10, sf::Color(200,200,200));
ball.SetCenter(0,0);
bool game=false;
int direction=0;
// Start game loop
while (App.IsOpened())
{
// Process events
sf::Event Event;
while (App.GetEvent(Event))
{
// Close window : exit
if (Event.Type == sf::Event::Closed)
App.Close();
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
App.Close();
if (Event.Type == sf::Event::KeyPressed && Event.Key.Code==sf::Key::Space)
game=true;
}
// Clear screen
App.Clear();
// Draw shapes
App.Draw(panel1);
App.Draw(panel2);
App.Draw(ball);
//elapsed time
float ElapsedTime = App.GetFrameTime();
//move panels
if (App.GetInput().IsKeyDown(sf::Key::Up)) {
panel2.Move(0, -110 * ElapsedTime);
sf::Vector2f pos1 = panel1.TransformToGlobal(panel1.GetPosition());
sf::Vector2f pos2 = panel2.TransformToGlobal(panel2.GetPosition());
std::cout<<pos1.x<<","<<pos1.y<<std::endl;
std::cout<<pos2.x<<","<<pos2.y<<std::endl;
}
if (App.GetInput().IsKeyDown(sf::Key::Down)) panel2.Move(0, 110 * ElapsedTime);
if (App.GetInput().IsKeyDown(sf::Key::U)) panel1.Move(0, -110 * ElapsedTime);
if (App.GetInput().IsKeyDown(sf::Key::J)) panel1.Move(0, 110 * ElapsedTime);
if (game) {
if (direction==0) {
sf::Vector2f pos = ball.TransformToGlobal(ball.GetPosition());
if (pos.x+(-49.1934955f * ElapsedTime)<-320) {
direction=1;
} /*else if (pos.x) {
}*/ else {
ball.Move(-49.1934955f * ElapsedTime, -98.386991f * ElapsedTime);
}
}
if (direction==1) {
sf::Vector2f pos = ball.TransformToGlobal(ball.GetPosition());
if (pos.x+(49.1934955f * ElapsedTime)>320) {
direction=1;
} else {
ball.Move(-98.386991f * ElapsedTime, 49.1934955f * ElapsedTime);
}
}
}
// Finally, display the rendered frame on screen
App.Display();
}
return EXIT_SUCCESS;
}