所以我正在制作一个飞扬的小鸟副本。但是在绘制一个矩形之后我无法改变它的值,当我改变'pipe1.X'时它会被改变但从未在Form中实际改变过。当单击空格按钮时以及当timer1执行代码'rect.Y - = gravity;'时,我想要'rect'作为鸟来改变它的Y位置所以它不断下降。我想让管道向左移动,但由于某些原因,没有任何控件在移动。我尝试使用断点进行调试,并且rec.Y正在改变,就像我想要的那样,但它在形式上没有变化。
int pipeSpeed = 1;
int gravity = 1;
static int y = 150;
static int xP = 640;
static int yP1 = 0;
static int yP2 = 260;
public Form1()
{
InitializeComponent();
}
Random r = new Random();
public int a;
public int b;
private void Form1_Load(object sender, EventArgs e)
{
//640, -27, 16, 150
timer1.Interval = 500;
a = r.Next(25, 150);
b = r.Next(150, 300);
timer1.Start();
}
Rectangle rect = new Rectangle(25, y, 25, 25);
Rectangle pipe1 = new Rectangle(xP, yP1, 25, 0);
Rectangle pipe2 = new Rectangle(xP, yP2, 25, 0);
private void update()
{
}
private void timer1_Tick(object sender, EventArgs e)
{
Application.DoEvents();
pipe1.X -= pipeSpeed;
rect.Y -= gravity;
if (xP == -35)
{
pipe1 = new Rectangle(xP, yP1, 25, 0);
pipe2 = new Rectangle(xP, yP2, 25, 0);
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Space)
{
rect.Y -= 5;
}
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle((Brushes.Red),rect);
pipe1.Height = a;
pipe2.Height = b;
e.Graphics.FillRectangle((Brushes.Black),pipe1);
e.Graphics.FillRectangle((Brushes.Black), pipe2);
}`
答案 0 :(得分:0)
你可以尝试
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Space)
{
rect.Y -= 5;
this.Invalidate();
}
}
和
private void timer1_Tick(object sender, EventArgs e)
{
...
this.Invalidate();
}
使控件的整个表面无效并导致控件 重新绘制。
请注意,有更多的重载和其他技巧可以提高效率,但这至少应该让您重绘表单