Banana Drop - C# 游戏
Banana Drop - C# Game
我正在开发一款 2d 游戏。其中香蕉 (picturBox
) 从屏幕顶部掉落,您必须接住它们,否则它会掉到地上,您会失去分数。为了给香蕉制作动画,我使用 timer
更改它的 Y-Location,间隔为 5ms(平滑动画)。
Y-Drop Speed 根据屏幕分辨率改变。由于香蕉在 720 的基本分辨率下每 5ms 移动 1px,它需要改变速度在不同的分辨率上花费相同的时间。
代码:
private void timer_Tick(object sender, EventArgs e)
{
double xNanas = nanas.Location.X;
double yNanas = nanas.Location.Y;
yNanas += 1 * this.Height / 720;
nanas.Location = new Point((int)xNanas, (int)yNanas);
nanas.Refresh();
}
问题:
1.当分辨率改成小数字时,例如。 800x600。 double 转换为 int,即使 (1 * 600 / 720) 四舍五入为 1,香蕉也不会移动。
2. 由于速度总是四舍五入,所以香蕉落地的时间差别很大! 1920x1080 为 16.7,1280x720 为 10.6。我怎样才能让它一样?
尝试过:
改变间隔而不是速度。它仍然没有完全同时落地。我无法将间隔更改为较大的数字,因为这会使动画断断续续。
你的做法是不对的,正如你所看到的,它会改变速度,因为int没有小数,因此速度会改变。
一个简单的解决方案是将位置存储在 class 中作为双精度并在双精度中执行所有逻辑,然后在完成所有计算后将 class 中的双精度转换为 int并将其设置为图片框位置,这样双精度将以相同的速度递增,与屏幕尺寸无关。
这里有一个浮动逻辑的例子(足以满足你的需要):
PointF realPosition = PointF.Empty; //Initialize it to the real position of the pb.
private void timer_Tick(object sender, EventArgs e)
{
realPosition.Y += 1.0f * this.Height / 720.0f; //note the .0f to instruct the compiler these must be float operations
nanas.Location = Point.Round(realPosition);
nanas.Refresh();
}
还有另一个错误来源,表单计时器不准确,如果 UI 很忙,它的速度会有所不同,对于真正的游戏来说,正常情况下不使用计时器,但是一个循环并检查经过的时间并将其乘以以秒为单位的速度。
我正在开发一款 2d 游戏。其中香蕉 (picturBox
) 从屏幕顶部掉落,您必须接住它们,否则它会掉到地上,您会失去分数。为了给香蕉制作动画,我使用 timer
更改它的 Y-Location,间隔为 5ms(平滑动画)。
Y-Drop Speed 根据屏幕分辨率改变。由于香蕉在 720 的基本分辨率下每 5ms 移动 1px,它需要改变速度在不同的分辨率上花费相同的时间。
代码:
private void timer_Tick(object sender, EventArgs e)
{
double xNanas = nanas.Location.X;
double yNanas = nanas.Location.Y;
yNanas += 1 * this.Height / 720;
nanas.Location = new Point((int)xNanas, (int)yNanas);
nanas.Refresh();
}
问题:
1.当分辨率改成小数字时,例如。 800x600。 double 转换为 int,即使 (1 * 600 / 720) 四舍五入为 1,香蕉也不会移动。
2. 由于速度总是四舍五入,所以香蕉落地的时间差别很大! 1920x1080 为 16.7,1280x720 为 10.6。我怎样才能让它一样?
尝试过:
改变间隔而不是速度。它仍然没有完全同时落地。我无法将间隔更改为较大的数字,因为这会使动画断断续续。
你的做法是不对的,正如你所看到的,它会改变速度,因为int没有小数,因此速度会改变。
一个简单的解决方案是将位置存储在 class 中作为双精度并在双精度中执行所有逻辑,然后在完成所有计算后将 class 中的双精度转换为 int并将其设置为图片框位置,这样双精度将以相同的速度递增,与屏幕尺寸无关。
这里有一个浮动逻辑的例子(足以满足你的需要):
PointF realPosition = PointF.Empty; //Initialize it to the real position of the pb.
private void timer_Tick(object sender, EventArgs e)
{
realPosition.Y += 1.0f * this.Height / 720.0f; //note the .0f to instruct the compiler these must be float operations
nanas.Location = Point.Round(realPosition);
nanas.Refresh();
}
还有另一个错误来源,表单计时器不准确,如果 UI 很忙,它的速度会有所不同,对于真正的游戏来说,正常情况下不使用计时器,但是一个循环并检查经过的时间并将其乘以以秒为单位的速度。