怎样让小球在窗体内来回移动?(10分)

X

xli

Unregistered / Unconfirmed
GUEST, unregistred user!
我是初学者,我编的代码让小球从左移到右后,不能再从右移到左,我发现在从右往左的
过程中小球实际上还在从左往右,所以过不来。代码如下:
procedure TForm1.Timer1Timer(Sender: TObject);
begin
shape1.Left:=shape1.Left+10;
if shape1.Left>form1.ClientWidth-shape1.Width then
shape1.Left:=shape1.Left-10;
end;
请问该如何解决?初学者,请勿见笑。
 
因为你的
if shape1.Left>form1.ClientWidth-shape1.Width then
shape1.Left:=shape1.Left-10;
只能执行一次,你想想为什么
你可以设一个开关(就是一boolean变量)当开关为TRUE就执行
shape1.Left:=shape1.Left+10;
否则就执行
shape1.Left:=shape1.Left-10;
 
要学会使用调试功能,就能发现错在哪里了。
要左右移动的话,需要定义一个方向变量,如下:
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if dir=1 then
begin
Shape1.Left := Shape1.Left + 10;
if Shape1.Left > ClientWidth - Shape1.Width then
dir := 2;
end else
begin
Shape1.Left := Shape1.Left - 10;
if Shape1.Left < Shape1.Width then
dir := 1;
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
dir := 1;
end;
 
非常感谢二位,给你们一人加五分。以后还请多指教。
 

Similar threads

D
回复
0
查看
2K
DelphiTeacher的专栏
D
D
回复
0
查看
2K
DelphiTeacher的专栏
D
D
回复
0
查看
1K
DelphiTeacher的专栏
D
D
回复
0
查看
892
DelphiTeacher的专栏
D
D
回复
0
查看
902
DelphiTeacher的专栏
D
顶部