class Moving_object : public Object
{
public:
- Moving_object() = default;
+ Moving_object() : direction{} {};
~Moving_object() = default;
protected:
+ sf::Vector2f direction; // Treat like unit-vector for movement
+
private:
};
#endif
\ No newline at end of file
#define OBJECT_H
#include <SFML/Graphics.hpp>
-#include <vector>
class Object
{
public:
- Object() : x_pos{0}, y_pos{0}, sprite{}, texture{} {};
+ Object() : position{}, sprite{}, texture{} {};
virtual ~Object() = default;
virtual bool collides(Object& other) = 0;
virtual void collision(Object& other) = 0;
virtual void update() = 0;
- virtual void render(sf::RenderWindow& window) = 0;
+ virtual void render(sf::RenderWindow& window) const = 0;
protected:
- double x_pos;
- double y_pos;
+ sf::Vector2f position;
sf::Sprite sprite;
sf::Texture texture;
private:
#include "Player.h"
-Player::Player() : collected{0}
+Player::Player() : collected{0}, max_speed{10}
{
texture.loadFromFile("assets/4V_figur.png");
sprite.setTexture(texture);
sprite.setScale(S_SCALE_KOEFF, S_SCALE_KOEFF);
- sprite.setPosition(S_WIDTH / 2, S_HEIGHT / 2);
+ sf::FloatRect gb {sprite.getGlobalBounds()};
+ sprite.setOrigin(gb.width / 2, gb.height / 2);
+ sprite.setPosition(position);
}
bool Player::collides(Object& other)
void Player::update()
{
- x_pos += 0.1;
- sprite.setPosition((S_WIDTH / 2) + x_pos, S_HEIGHT / 2);
+ position += max_speed * direction;
+
+ sprite.setPosition(position);
return;
}
-void Player::render(sf::RenderWindow& window)
+void Player::render(sf::RenderWindow& window) const
{
window.draw(sprite);
+}
+
+void Player::handle_input(sf::Event& event)
+{
+ direction = {0,0};
+
+ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W))
+ {
+ direction.y -= 1;
+ }
+ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S))
+ {
+ direction.y += 1;
+ }
+ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D))
+ {
+ direction.x += 1;
+ }
+ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A))
+ {
+ direction.x -= 1;
+ }
+
+ // If the vector is diagonal, normalize its length
+ if (abs(direction.x) + abs(direction.y) == 2)
+ {
+ direction.x *= M_SQRT1_2;
+ direction.y *= M_SQRT1_2;
+ }
}
\ No newline at end of file
+#ifndef PLAYER_H
+#define PLAYER_H
+
+#define _USE_MATH_DEFINES
#include <SFML/Graphics.hpp>
+#include <cmath>
#include "Moving_object.h"
#include "constants.h"
-
class Player : public Moving_object
{
public:
Player();
~Player() = default;
- bool collides(Object& other);
- void collision(Object& other);
- void update();
- void render(sf::RenderWindow& window);
-
+ bool collides(Object& other) override;
+ void collision(Object& other) override;
+ void update() override;
+ void render(sf::RenderWindow& window) const override;
+ void handle_input(sf::Event& event);
protected:
private:
int collected;
-};
\ No newline at end of file
+ float max_speed;
+};
+
+#endif
\ No newline at end of file