1 minute read

스프라이트 텍스쳐를 나누는 법

shot

이런 텍스쳐가 있다고 해보죠.
32x32텍스쳐이므로 전체 크기는 x = 32 * 4, y = 32 * 4 이므로
텍스쳐의 사이즈는 128 x 128입니다. 텍스쳐의 사이즈는 이 함수를 통해 가져올 수 있습니다.

sf::Vector2u textureSize = playerTexture.getSize();

32 x 32로 스프라이트를 잘라서 하나씩 사용하고 싶으므로 텍스쳐들을 잘라주겠습니다.

textureSize.x /= 4; textureSize.y /= 4; 그리고 setTextureRect에대해 알아봅시다 sf::Sprite 클래스의 멤버 함수인 setTextureRect는 텍스처의 특정 영역을 스프라이트의 텍스처 영역으로 설정하는 데 사용됩니다. 일반적으로, 하나의 텍스처에는 여러 개의 이미지 또는 애니메이션 프레임이 포함될 수 있습니다. 이때 setTextureRect 함수를 사용하여 텍스처 내에서 스프라이트가 표시될 영역을 지정할 수 있습니다. 이 함수는 텍스처의 좌측 상단 모퉁이를 원점으로 하는 x, y 좌표와 너비와 높이를 나타내는 sf::IntRect를 매개변수로 받습니다. 예를 들어, 다음과 같은 코드를 사용하여 64x64 크기의 텍스처를 불러온 뒤, 스프라이트에 텍스처 영역을 설정하면 해당 스프라이트는 텍스처의 왼쪽 상단에서 32x32 크기의 영역을 표시합니다.

sf::Texture texture;
texture.loadFromFile("texture.png");

sf::Sprite sprite(texture);
sprite.setTextureRect(sf::IntRect(0, 0, 32, 32));

이런식으로요
그리고 저는 이 부분을 사용하고 싶습니다.

shot1

그러므로 다음과 같이 코드를 짜면 되겠네요

코드

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

int main()
{
    // 윈도우 생성
    sf::RenderWindow window(sf::VideoMode(1280, 720), "SFML TUTORIAL", sf::Style::Close | sf::Style::Resize);

    // 사각형 생성 및 초기화
    sf::RectangleShape player(sf::Vector2f(100.0f, 100.0f));
    player.setOrigin(50.0f, 50.0f);

    // 텍스처 로드 및 적용
    sf::Texture playerTexture;
    playerTexture.loadFromFile("32x32-bat-sprite.png");
    player.setTexture(&playerTexture);

    // 텍스처 크기 가져오기
    sf::Vector2u textureSize = playerTexture.getSize();
    textureSize.x /= 4;
    textureSize.y /= 4;

    // 적용할 텍스처 영역 설정
    player.setTextureRect(sf::IntRect(textureSize.x * 2, textureSize.y * 0, textureSize.x, textureSize.y));

    while (window.isOpen())
    {
        // 이벤트 처리
        sf::Event evnt;
        while (window.pollEvent(evnt))
        {
            switch (evnt.type)
            {
            case sf::Event::Closed:
                window.close();
                break;
            }
        }

        // 마우스 왼쪽 버튼 클릭 시, 플레이어 이동
        if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
        {
            sf::Vector2i mousePos = sf::Mouse::getPosition(window);
            player.setPosition((float)mousePos.x, (float)mousePos.y);
        }

        // 화면 업데이트
        window.clear(sf::Color::White);
        window.draw(player);
        window.display();
    }

    return 0;
}

shot2

원하는 부분이 잘나오네요. 이미지 다운을 원하시면 https://opengameart.org/content/bat-sprite

Leave a comment