program HowToMoveSpriteWithKeyboardInput;
uses SwinGame,sgTypes;
procedure Main();
var
ball : Sprite;
begin
OpenGraphicsWindow('Move a Sprite with Keyboard Input' ,800 ,600 );
LoadBitmapNamed('ball' ,'ball_small.png' );
ball := CreateSprite(BitmapNamed('ball' ) );
SpriteSetX(ball ,385 );
SpriteSetY(ball ,285 );
repeat
ProcessEvents();
ClearScreen(ColorWhite );
if KeyDown(vk_RIGHT ) then
begin
SpriteSetDx(ball ,1 );
SpriteSetDy(ball ,0 );
end
else
if KeyDown(vk_LEFT ) then
begin
SpriteSetDx(ball ,-1 );
SpriteSetDy(ball ,0 );
end
else
if KeyDown(vk_UP ) then
begin
SpriteSetDx(ball ,0 );
SpriteSetDy(ball ,-1 );
end
else
if KeyDown(vk_DOWN ) then
begin
SpriteSetDx(ball ,0 );
SpriteSetDy(ball ,1 );
end
else
begin
SpriteSetDx(ball ,0 );
SpriteSetDy(ball ,0 );
end;
DrawSprite(ball );
UpdateSprite(ball );
RefreshScreen();
until WindowCloseRequested();
FreeSprite(ball );
ReleaseAllResources();
end;
begin
Main();
end.
How To Move Sprite With Keyboard Input
This article will show you how to move a sprite with the help of keyboard inputs.
Level
AdvancedDetails
You can set any direction for any key and the sprite will move according to the command it gets. In this program a sprite can only go left, right, up or down.
To be able to do that, you need to do follow these steps:
- Load an image and create a sprite from it
- Set an initial position (Sprite Set X, Sprite Set Y) for that sprite
- Then clear the screen (Clear Screen) with Color White
- Now depending on the user's command-
- Set x velocity (Sprite Set X) of the sprite any positive value but keep the y velocity (Sprite Set Y) as 0 if it gets the command to go right (Key Down(VK_RIGHT))
- Else set x velocity (Sprite Set X) of the sprite any negative value but keep the y velocity (Sprite Set Y) as 0 if it gets the command to go left (Key Down(VK_LEFT))
- Else set y velocity (Sprite Set Y) of the sprite any negative value but keep the x velocity (Sprite Set X) as 0 if it gets the command to go up (Key Down(VK_UP))
- Else set y velocity (Sprite Set Y) of the sprite any positive value but keep the x velocity (Sprite Set X) as 0 if it gets the command to go down (Key Down(VK_DOWN))
- Else in all other cases set the X and Y value for the sprite's velocity (Sprite Set Dx and Sprite Set Dy) as 0
5. Then draw (Draw Sprite) and update (Update Sprite) the sprite to show it on the screen.
The code below shows all the concepts implemented as a program.
If there is a useful hint you will find it in a box like this
Possibilities
Suggested projects will appear here.
