I created 4 images, in which the character (game character, a car) looks at different directions, every time you press the arrow keys (up looks at up, down looks at down, left looks at left, right looks at right), here is the code:
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var path,dleft,dright,dtop,dbot:string;
begin
path:=paramstr(0);
dleft:=extractfilepath(path)+'Images\Pacman_Left.bmp';
dright:=extractfilepath(path)+'Images\Pacman_Right.bmp';
dtop:=extractfilepath(path)+'Images\Pacman_Top.bmp';
dbot:=extractfilepath(path)+'Images\Pacman_Bot.bmp';
case Key of
VK_UP:
begin
image6.Picture.LoadFromFile(dtop);
image6.Top := image6.Top - 10;
end;
VK_DOWN:
begin
image6.Picture.LoadFromFile(dbot);
image6.Top := image6.Top + 10;
end;
VK_LEFT:
begin
image6.Picture.LoadFromFile(dleft);
image6.Left := image6.Left - 10;
end;
VK_RIGHT:
begin
image6.Picture.LoadFromFile(dright);
image6.Left := image6.Left + 10;
end;
end;
end;
I think the code I am using is terrible, because if I press a key over than a time, it will reload the image and it will keep doing it as long as I keep pressing the same key, such a waste of RAM. What can I do about it?
Some improvment: Load all images first (on application startup, say):
var
bmCarLeft, bmCarRight, bmCarUp, bmCarDown: TBitmap;
...
bmCarLeft := TBitmap.Create;
bmCarLeft.LoadFromFile(dleft);
...
and then you can do
Image6.Picture.Assign(bmCarSomething)
every time you need to change it.