How To Move A Sprite

This article will show you how to move a sprite in SwinGame.

Level

Advanced

Details

In a game it is important to move almost all the characters and objects. Once a sprite is created SwinGame lets you move that sprite anyway you want. The code below shows how you can move a sprite and to do that SwinGame performs a few steps.

  1. Get the velocity of the sprite
  2. Introduce a game loop where it clears the screen with the color you want
  3. Place the sprite back to the screen if it goes off the screen
  4. Draw and update the sprite
  5. Have an end condition of the game loop

Source Code Widget

  • program HowToMoveASprite;
    uses SwinGame,sgTypes;
    
    procedure Main();
    var
        ball : Sprite;
    begin
        OpenGraphicsWindow('Move a Sprite' ,150 ,150 );
        LoadBitmapNamed('ball' ,'ball_small.png' );
        ball := CreateSprite(BitmapNamed('ball' )  );
        SpriteSetX(ball ,60 );
        SpriteSetY(ball ,0 );
        SpriteSetDx(ball ,0 );
        SpriteSetDy(ball ,0.05 );
        repeat
            ClearScreen(ColorWhite );
            if  SpriteOffscreen(ball )    then
            begin
                SpriteSetX(ball ,60 );
                SpriteSetY(ball ,-30 );
            end;
            DrawSprite(ball );
            UpdateSprite(ball );
            RefreshScreen();
            ProcessEvents();
        
        until WindowCloseRequested();
        FreeSprite(ball );
        ReleaseAllResources();
    end;
    begin
        Main();
    end.
    Download Now"
  • #include 
    #include "SwinGame.h"
    int main() 
    {
        sprite  ball;
        open_graphics_window("Move a Sprite" ,150 ,150 );
        load_bitmap_named("ball" ,"ball_small.png" );
        ball = create_sprite(bitmap_named("ball" ) ) ;
        sprite_set_x(ball ,60 );
        sprite_set_y(ball ,0 );
        sprite_set_dx(ball ,0 );
        sprite_set_dy(ball ,0.05 );
        do 
        {
            clear_screen(color_white );
            if ( sprite_offscreen(ball )  )
            {
                sprite_set_x(ball ,60 );
                sprite_set_y(ball ,-30 );
            }
            draw_sprite(ball );
            update_sprite(ball );
            refresh_screen();
            process_events();
        }
        while ( ! (window_close_requested() ) );
        free_sprite(ball );
        release_all_resources();
        return 0;
    }
    
    Download Now"
  • Source Code Coming Soon

  • Source Code Coming Soon

  • Source Code Coming Soon

If the object is moving, there is a possibility of it being disappear from the screen. SwinGame has a function to detect if the sprite is off the screen. Use it wisely!

Possibilities

You can make lots of games using this principal. You can have all the people running around the screen and when you click on them they stop.