Hi,
Im quite new to C++ and SFML. I was following some tutorials to draw shapes and get keyboard input to make those shapes move. I got everything working nice, at that point I had everything declared and executed in main() method.
Then I thought to make my code more modular and OOP, as soon as I did that -> placed shapes in Player class and keyboard input as a method in Player class and then called those methods exactly where that code was previously in main() method, shapes wont draw.
It must be something simple, there is no errors, but I cant figure it out. Am hoping someone could point out what is wrong. Drawing shapes in main still works as I tried to draw circle and its fine, just drawing from my Player class seems faulty.
Heres my code:
main() method
#include <iostream>
#include <SFML/Graphics.hpp>
#include <math.h>
#include "Player.h"
using namespace std;
int main() {
sf::RenderWindow window1(sf::VideoMode(1024, 768), "Tutorial", sf::Style::Close | sf::Style::Resize);
Player player;
while (window1.isOpen())
{
sf::Event evnt1;
while (window1.pollEvent(evnt1))
{
switch (evnt1.type) {
case sf::Event::Closed:
window1.close();
break;
}
}
window1.clear(sf::Color(0, 150, 150));
window1.draw(player.player);
window1.draw(player.sigth);
player.movePlayer();
sf::Vector2i mousePos = sf::Mouse::getPosition(window1);
player.sigthRotation(mousePos);
window1.display();
}
return 0;
}
And Player class
Player.h
#pragma once
#include <SFML/Graphics.hpp>
#include <math.h>
#define PI 3.14159265
class Player
{
public:
sf::CircleShape player;
sf::RectangleShape sigth;
Player();
void movePlayer();
void sigthRotation(sf::Vector2i mousePos);
};
and Player.cpp
#include "Player.h"
Player::Player() {
sf::CircleShape player (25);
sf::RectangleShape sigth (sf::Vector2f(150.0f, 2.0f));
player.setPosition(206.0f, 206.0f);
sigth.setPosition(231.0f, 231.0f);
player.setFillColor(sf::Color::Blue);
}
void Player::movePlayer() {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
player.move(-0.1f, 0.0f);
sigth.move(-0.1f, 0.0f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
player.move(0.1f, 0.0f);
sigth.move(0.1f, 0.0f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
player.move(0.0f, -0.1f);
sigth.move(0.0f, -0.1f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
player.move(0.0f, 0.1f);
sigth.move(0.0f, 0.1f);
}
}
void Player::sigthRotation(sf::Vector2i mousePos) {
sf::Vector2f linePos = sigth.getPosition();
float dx = linePos.x - mousePos.x;
float dy = linePos.y - mousePos.y;
double rotation = (atan2(dy, dx)) * 180 / PI;
sigth.setRotation((float)rotation + 180);
}