SFML community forums

Help => General => Topic started by: seb_thoms on July 18, 2019, 11:08:54 pm

Title: Is this good beginner code?
Post by: seb_thoms on July 18, 2019, 11:08:54 pm
I recently started programming withh C++.
What do you thing about my code?
Do you have any ideas to improve it?

surce.cpp

#include <SFML/Graphics.hpp>
#include <iostream>
#include "movePlayer.h"

//global variables
float speed = 5.0f;

int main()
{
        //game objects
        sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
        sf::RectangleShape shape(sf::Vector2f(10.0f, 10.0f));
        shape.setFillColor(sf::Color::Cyan);
        window.setFramerateLimit(50);

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

                //move player
                shape.move(inputMoveVector());

                //draw window
                window.clear();
                window.draw(shape);
                window.display();
        }

        return 0;
}
 
movePlayer.h

#pragma once
#include <SFML/Graphics.hpp>
#include <iostream>

extern float speed;

//give out a Vector2f
sf::Vector2f inputMoveVector() {

        float x = 0.0f;
        float y = 0.0f;

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
                x = speed;

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
                x = -speed;

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
                y = -speed;

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
                y = speed;

        return sf::Vector2f(x, y);

}
 
Title: Re: Is this good beginner code?
Post by: Rosme on July 19, 2019, 03:24:23 pm
This is not the appropriate place to post this. You would be better to post in General.
Title: Re: Is this good beginner code?
Post by: Crembotz on July 20, 2019, 06:19:17 pm
Why did you use extern on speed? Doesn't look like you're using it anywhere else...
Title: Re: Is this good beginner code?
Post by: Nexus on July 20, 2019, 09:41:51 pm
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
                x = speed;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
                x = -speed;
This is problematic if both keys are pressed. In that situation, you usually want the resulting X coordinate to be 0, but in your case it's going left. Use += instead of =.

//global variables
float speed = 5.0f;
Avoid global variables (except maybe for constants). In a good design they are very rarely needed.

//give out a Vector2f
sf::Vector2f inputMoveVector() {
You can define the function in the .cpp file, too -- no need for it to be in the header.