Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- #include <iostream>
- sf::RenderWindow window;
- constexpr int WIDTH = 1280,
- HEIGHT = 720;
- void checkForClose();
- class Draggable_Sprite
- {
- public:
- void setSprite ( sf::RectangleShape& sprite )
- {
- m_sprite = &sprite;
- offset = getOffsetToMouse();
- }
- void update()
- {
- if ( !m_sprite ) return;
- if ( !sf::Mouse::isButtonPressed( sf::Mouse::Left ) )
- {
- m_sprite = nullptr;
- return;
- }
- if ( m_sprite )
- {
- float yPos = sf::Mouse::getPosition( window ).y - offset.y;
- float xPos = sf::Mouse::getPosition( window ).x - offset.x;
- m_sprite->setPosition( { xPos, yPos } );
- }
- }
- bool hasSprite()
- {
- return m_sprite;
- }
- private:
- sf::Vector2i getOffsetToMouse ( )
- {
- float mouseX = sf::Mouse::getPosition( window ).x;
- float mouseY = sf::Mouse::getPosition( window ).y;
- float spriteX = m_sprite->getPosition().x;
- float spriteY = m_sprite->getPosition().y;
- return { (int)mouseX - spriteX,
- (int)mouseY - spriteY };
- }
- sf::RectangleShape* m_sprite = nullptr;
- sf::Vector2i offset = { 0, 0 };
- };
- bool touchingMouse ( const sf::RectangleShape& shape )
- {
- float height = shape.getLocalBounds().height;
- float width = shape.getLocalBounds().width;
- float mouseX = sf::Mouse::getPosition( window ).x;
- float mouseY = sf::Mouse::getPosition( window ).y;
- float spriteX = shape.getPosition().x;
- float spriteY = shape.getPosition().y;
- return ( mouseX > spriteX &&
- mouseX < spriteX + width &&
- mouseY > spriteY &&
- mouseY < spriteY + height );
- }
- int main()
- {
- window.create( sf::VideoMode ( WIDTH, HEIGHT ), "Drag the square!", sf::Style::Close );
- window.setFramerateLimit( 60 );
- sf::RectangleShape shape;
- shape.setSize( { 50, 50 } );
- shape.setPosition( { 242, 124 } );
- Draggable_Sprite sprite;
- std::cout << sizeof ( window ) << std::endl;
- while ( window.isOpen() )
- {
- window.clear();
- if ( touchingMouse( shape ) && sf::Mouse::isButtonPressed( sf::Mouse::Left ) && !sprite.hasSprite() )
- {
- sprite.setSprite( shape );
- continue;
- }
- sprite.update();
- window.draw( shape );
- window.display();
- checkForClose();
- }
- }
- void checkForClose()
- {
- sf::Event e;
- while ( window.pollEvent( e ) )
- {
- if ( e.type == sf::Event::Closed )
- {
- window.close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement