Ok so first of all i'm just messing around in delphi, and still really new to it, but i noticed that whenever i try to make some kind of game , where W,A,S, and D are the buttons which moves an object (TImage) , it starts flashing randomly, i noticed that it happens if the speed is fast, or when it's moving and there is another image (background) behind it...
Most of my "moving" code looks like this:
if key = 's' then begin
for I := 1 to 5 do
sleep(1);
x:=x-2;
Image1.Top := x;
end;
Maybe that causes it, but still it's really annoying. I would be really pleased if you could help with this.
Something like this is better handled using TPaintBox
instead.
Have the keystrokes set variables as needed and then call TPaintBox.Invalidate()
to trigger a repaint when the OS is ready for it.
The TPaintBox.OnPaint
event handler can then draw a TGraphic
at the appropriate coordinates specified by the current variable values as needed.
var
X: Integer = 0;
Y: Integer = 0;
procedure TMyForm.KeyPress(Sender: TObject; var Key: Char);
begin
case Key of
'W': begin
Dec(Y, 2);
PaintBox.Invalidate;
end;
'A': begin
Dec(X, 2);
PaintBox.Invalidate;
end;
'S': begin
Inc(Y, 2);
PaintBox.Invalidate;
end;
'D': begin
Inc(X, 2);
PaintBox.Invalidate;
end;
end;
end;
procedure TMyForm.PaintBoxPaint(Sender: TObject);
begin
PaintBox.Canvas.Draw(X, Y, SomeGraphic);
end;