Skip to content

First lesson SFML with Youtube

Bài viết này ghi lại quá trình học làm game với library C++ SFML nhờ vào xem vài video tutorial trên Youtube để xem cách họ lập trình và set up Visual Studio ra sao.

1 Introduction

2 Tạo Project SFML

2.1 Create project

Chọn File –> New Project –> Windows Desktop Wizard C++
Chọn Empty Project

Trong Windows sẽ tạo thành Folder với các thành phần sau

2.2 Add Directory external

Tạo 1 folder External để add các library khác vào game của mình

Vì mình cài SFML từ vcpkg nên không cần phải add các library thủ công, nhưng các library mà không có trên vcpkg thì phải add thủ công

Nếu không cài SFML mà chỉ tải SFML từ trang chủ thì cần phải add library vào Solution của VS như sau (lấy theo Youtube Tutorial)

2.3 Add Linker, external library

Tương tự, các library cũng phải được add vào Linker

Add Input

2.4 Test project

Sử dụng code có sẵn từ Tutorial của SFML

#include <iostream>
#include <ctime>
#include <cstdlib>

#include "SFML\Graphics.hpp"

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

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

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

    return 0;
}

3 Game class

3.1 Add game class VS 2019

3.2 Khởi tạo Game.h, Class

Tạo Game loop

#ifndef GAME_H
#define GAME_H

// Tạo header Game.h liên kết với Game.cpp

// Khai báo các library stardard
#include <iostream>
#include <ctime>
#include <cstdlib>

// Khai báo SFML library, SFML cần được cài đặt thông qua vcpkg
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>

class Game
{
private:
    // Variables
    // Khai báo các biến sẽ sử dụng trong các functions trong Game.cpp
    sf::RenderWindow *window; // Sử dụng pointer, chú ý phải clean các pointer sau khi sử dụng, nếu không sẽ bị chiếm mất vị trí của bộ nhớ.
    // Bây giờ có khai báo các biến thuộc dạng window trong Game.cpp
    sf::Event sfEvent;

    // Static functions
    // 
    // 
    //trong Private
    void initWindow();

public:
    Game();
    virtual ~Game();

    // Tạo các functions cho game
    // Tạo game loop
    void update();
    void updateSFMLEvents();
    void render();
    void run();
    // Các functions này được định nghĩa chi tiết tại Game.cpp
};

#endif

Sử dụng Class để tạo Class Game. Trong class Game có các functions gồm update(), render, run,…

Các functions này mô tả (định nghĩa) trong Game.cpp, và được sử dụng trong main.cpp

3.3 Định nghĩa Game Class function tại Game.cpp

#include "Game.h"

// Khởi tạo Initizalizer
void Game::initWindow()
{
    //sf::RenderWindow window(sf::VideoMode(200, 200), "Checking SFML"); // Đây là khai báo gốc tại main.cpp để test SFML.
    this-> window = new sf::RenderWindow(sf::VideoMode(800, 600), "Checking SFML");
}

//Constructors and Destructors
Game::Game()
{
    this->initWindow();
}

Game::~Game()
{
    // Cần phải xoá pointer window sau khi sử dụng
    delete this->window;
}

void Game::update()
{
    this->updateSFMLEvents();

}

void Game::updateSFMLEvents()
{

    while (this->window->pollEvent(this->sfEvent))
    {
        if (this->sfEvent.type == sf::Event::Closed)
            this->window->close();
    }

}

void Game::render()
{
    this->window->clear();

    this->window->display();
}

void Game::run()
{
    while (this->window ->isOpen())
    {
        this->update();
        this->render();
    }
}

4 Game loop

  • Game loop là phần rất quan trọng cho mỗi game để nó có thể vận hành được.
  • Game loop được khai báo trong main.cpp và sử dụng while
  • Trong Game.h sẽ kèm theo Player.h và Enemey.h
  • Player.h và Enemey.h đều có Class chứa các functions là:
  • initShape(): Để tạo hình dáng ban đầu cho nhân vật hay enemy
  • render(): draw vào màn hình
  • update(*target): update các animation của nhân vật. Lưu ý cần khai báo biến trong function này thuộc pointer

4.1 Player

4.2 Enemy

  • static_cast<type>(expression) sử dụng để convert expression thành một type cụ thể.
int main() {
  int j = 41;
  int v = 4;
  float m = j/v;
  float d = static_cast<float>(j)/v;
  cout << "m = " << m << endl;
  cout << "d = " << d << endl;
}
  • Vì j và v đều là integers nên m cũng thuộc dạng integer, vì vậy phải dùng static_cast để chuyển j từ int sang float .

push_back: add 1 giá trị vào cuối của list của một vector

4.3 Collision

void Game::updateCollision()
{
    // Check the collision
    // Kiểm tra cho tất cả các swagBalls được hình thành
    for (size_t i = 0; i < swagBalls.size(); i++)
    {
        if (player.getShape().getGlobalBounds().intersects(swagBalls[i].getShape().getGlobalBounds()))
            //Sử dụng intersects để xác định player Shape có va chạm với Balls shape
            // Nếu có thì xoá ball đi
            // Và add 1 point
        {
            switch (swagBalls[i].getType())
            {
            case SwagBallTypes::DEFAULT:
                points++;
                break;
            case SwagBallTypes::DAMAGING:
                player.takeDamange(1);
                break;
            case SwagBallTypes::HEALING:
                player.gainHealth(1);
                break;
            }

            swagBalls.erase(swagBalls.begin() + i);
        }
    }
}

5 Sản phẩm

Tuy nhiên sau khi theo dõi các Tutorial trên Youtube thì gần như các kiến thức không được liên kết chặt chẽ. Ngoài ra C++ của mình còn rất hạn chế nên các phần thuộc về class và pointer * và & nhiều khi không hiểu.

Vì vậy bây giờ mình sẽ học theo 1 quyển sách , hy vọng quyển này sẽ giúp mình hệ thống lại kiến thức rõ ràng hơn.

The following pages link to this page:



Created : Jan 28, 2022