SFML - Moving a sprite on mouseclick

user7383
  • SFML - Moving a sprite on mouseclick user7383

    I want to be able to move a sprite from a current location to another based upon where the user clicks in the window. This is the code that I have:

    #include <SFML/Graphics.hpp>
    
    int main()
    {
        // Create the main window
        sf::RenderWindow App(sf::VideoMode(800, 600), "SFML window");
    
        // Load a sprite to display
        sf::Texture Image;
        if (!Image.LoadFromFile("cb.bmp"))
            return EXIT_FAILURE;
        sf::Sprite Sprite(Image);
    
        // Define the spead of the sprite
        float spriteSpeed = 200.f;
    
        // Start the game loop
        while (App.IsOpened())
        {
            if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Escape))
                App.Close();
    
            if (sf::Mouse::IsButtonPressed(sf::Mouse::Right)) {
                Sprite.SetPosition(sf::Mouse::GetPosition(App).x, sf::Mouse::GetPosition(App).y);
            }
    
            // Clear screen
            App.Clear();
    
            // Draw the sprite
            App.Draw(Sprite);
    
            // Update the window
            App.Display();
        }
    
        return EXIT_SUCCESS;
    }
    

    But instead of just setting the position I want to use Sprite.Move() and gradually move the sprite from one position to another. The question is how? Later I plan on adding a node system into each map so I can use Dijkstra's algorithm, but I'll still need this for moving between nodes.

  • The easiest way I see is to store velocity, when user clicks on screen. This velocity will define, which direction sprite should move and by what speed (so for example direction * spriteSpeed).

    Direction can be obtained by simple vector math: (TargetPosition - CurrentPosition).normalize()

    And then you will update sprites position each frame. So just add to while loop: CurrentPosition += Velocity * ElapsedTimeSinceLastFrame. ElapsedTimeSinceLastFrame is just for sure - if you don't use time and run this application on faster machine (while loop will be executed faster), your sprite will move of course faster.

    And finally - you should control, if sprite is at the end of its journey. So control, if (Velocity * ElapsedTime).length() is not more than (TargetPos - CurrentPos).length(). If it is, move sprite to target position and set velocity to zero (or set some flag not to update sprite position till next mouse click).

Tags
c++ sprites input mouse sfml
Related questions and answers
  • from it. As an added touch i have made it so after you collide while traveling down the randomly generated map (or rather as the walls move uppward while your character stays put) the X chars you've... //////////// bool move(int X, int Y) { location[0] += X; location[1] += Y; return true;}; };// end of sprite... in the main function * not Finally.. but i believe that te numb_coll problem has something to do with the time and framrate. When running full speed i quickly die upon entering a wall as numb_coll

  • between frame updates or other problems..... Finally I would like to know how my organization, planning, etc is.. Thanks! my UPDATED, WORKING Code: #include<SFML/Graphics.hpp> #include<SFML/System.hpp> #include<cmath> #include<vector> # define M_PI 3.14159265358979323846 sf::RenderWindow Window; template<typename T> void CalculateMove(T Time, T Speed, T... axis. I then implemented this function into my custom mySprite class, more specifically into it's update() function which updates its Position using the above function to calculate its new position

  • I've got a Windows API Window. I've managed to make it windowed, and "fullscreen windowed". But I can't seem to make the window just full-screen- for example, even if I specify WS_POPUP, I can still freely move the cursor to my second screen. However, if I launch full-screen games, they don't permit it, and exist only exclusively or minimized. How can I make a window that behaves this way? Edit: Excuse me. Limiting the mouse movement was just one example of how a full-screen window behaves differently to a non-fullscreen window, I'm not looking for how to limit the mouse movement

  • components. A powerup has the Sprite, Position, BoundingBox. And so on. The main loop manages the game "physics", i.e. how the components interact each other: foreach(entity (let it be entity1...) I was thinking about the following: class Entity; class Component { Entity* entity; ... virtual void serialize(filestream, op) = 0; ...} class Sprite : public Component {...}; class Position... boost::fusion::map< pair<Sprite, Sprite*>, pair<Position, Position*> > components; template <class C> bool has_component() { return components.at<C>() != 0

  • end end return best_move end def alphabeta(alpha, beta, player) best_score = -INFINITY if not self.has_available_moves? return WIN if self.has_this_player_won?(player) == player return LOSS if self.has_this_player_won?(1 - player) == 1 - player else self.remaining_moves.each do |move| break if alpha > beta..._score next_move = move end best_score = alpha end end return best_score end currently, the algorithm is playing terribly. It will initially pick

  • components total. Or is this even feasible? How much I can accomplish with this approach? In essence I want to be able to do something like this with reasonable efficiency: moving_update(DB) :- alive(DB,A),alive(DB,B),wontcollide(DB,A,B), move(DB,A),move(DB,B). wontcollide(DB,A,B) :- get_component(DB,position,A,PA), get_component(DB,position,B,PB),... move(DB,A) :- get_component...,update(DB,position,A,NewP). DB=loadgame(); loop{ moving_update(DB); blow_stuff(DB); collect_loot(DB);...}

  • I am trying to create a ID3D10RasterizerState with direct3D10, and then call ID3D10Device::RSSetState() with the proper information. However, whenever the window get rescaled, or when the app goes fullscreen, the rasterizerstate seems to reset to the default state. I have tried to set the state with WM_SIZE messages, but awkwardly, nothing seems to happen... It works properly when I call...); m_pD3DDevice->RSSetState(m_pRSState); //...more code } WndProc: switch( message ) { case WM_SIZE: { m_pD3DDevice->RSSetState(m_pRSState); break; } }

  • Currently in my project, the way I handle user input events is through the OS Framework, then create a generic object - basically combines all types of input: keyboard, mouse, touch, trackball, etc... that I have generated. I handle the threads by using turn-based concurrency. My problem is I worry about lag of the input events when there are fast moving objects, and I am curious to see if there are better ways of handling the input events then currently? My current idea, of handling the simple hit test of fast moving objects with user input, is that I try and use the timestamp generated

  • Sorry for the ackward title, but i don't know what to call it exactly. I'm looking for code or libraries that allow easy creation of commonly used user input devices, and code/libs that make gaming controls easy to set up (i'm using SFML and Box2D at the moment) I don't want to re-invent things like buttons, arrows being placed wherever the mouse is located, and more game specific items such as "controls settings" or even being able to drag objects around with the mouse. More specifically i want source code for interfaces that.... Makes Buttons and Textboxes easy to create allows mouse

Data information