好了,我已经开发了一个2d侧滚动(platformer),它非常高效,使用了1个计时器,而我正在尝试使移动平台成为可能。下面是我尝试并正在调试的内容
Private Sub Timer1_Timer()
'moving platforms
For f = 0 To Platform.Count - 1
If Platform(f).Tag = "moving" Then
For j = 0 To Platform.Count - 1
If Collision(Platform(f), Platform(j)) And j <> f Then
Speed(f) = Speed(f) * -1
End If
Next j
Platform(f).Left = Platform(f).Left + Speed(f)
End If
Next f基本上,代码是这样做的:对于所有的平台,它检查哪个平台有" moving“标签,如果它有这个标签,就移动它,但是在移动它之前,看看它是否需要改变方向,所以它再次循环所有的平台,看看它是否需要再次改变,如果需要的话,它应该这样做,但在这个代码中它不起作用:(
可能的问题是什么?所有速度的初始值都是1,并且我有缩放模式到像素,这就是为什么它这么小的原因。任何帮助我们都将不胜感激
碰撞函数:
Public Function Collision(Shape1 As Control, Shape2 As Control) As Boolean
If (Shape1.Left + Shape1.Width) > Shape2.Left _
And Shape1.Left < (Shape2.Left + Shape2.Width) _
And (Shape1.Top + Shape1.Height) > Shape2.Top _
And (Shape1.Top + Shape1.Height) < Shape2.Top + Shape2.Height Then
Collision = True
Else
Collision = False
End If
End Function发布于 2011-11-08 08:03:58
好了,问题已经解决了。观察这个碰撞函数:
Public Function Collision(Shape1 As Control, Shape2 As Control) As Boolean
If (Shape1.Left + Shape1.Width) > Shape2.Left _
And Shape1.Left < (Shape2.Left + Shape2.Width) _
And (Shape1.Top + Shape1.Height) > Shape2.Top _
And (Shape1.Top + Shape1.Height) < Shape2.Top + Shape2.Height Then
Collision = True
Else
Collision = False
End If
End Function注意到问题了吗?在本例中,我正在测试碰撞的两个平台位于相同的height。想想看,如果你在碰撞函数中看到,最后一个条件:
(Shape1.Top + Shape1.Height) < Shape2.Top + Shape2.Height由于Shape1与Shape2具有相同的Top,因此此条件为假,因为我使用的是小于号,而不是小于或等于号。为了确保没有问题,我用等于或等于1的符号替换了所有符号。
Public Function Collision(Shape1 As Control, Shape2 As Control) As Boolean
If (Shape1.Left + Shape1.Width) >= Shape2.Left _
And Shape1.Left <= (Shape2.Left + Shape2.Width) _
And (Shape1.Top + Shape1.Height) >= Shape2.Top _
And (Shape1.Top + Shape1.Height) <= Shape2.Top + Shape2.Height Then
Collision = True
Else
Collision = False
End IfEnd函数
你看看这个!在其旁边的平台之间弹跳的移动平台。漂亮的。
发布于 2011-11-13 18:31:58
下面是几个需要考虑的优化:
1)与其他语言不同,vb计算语句中的所有表达式。换句话说:
如果FunctionA = true且FunctionB = true,则DoSomething
将始终运行FunctionB,即使FunctionA为false。在您的计时器中,您可以在冲突检查之前检查if语句中的j不等于f,以避免在您已经知道要忽略该冲突时浪费时间检查该冲突。
2)如果我在外部循环和内部循环中从1循环到3,我最终会比较:
1 - 1
1 - 2
1 - 3
2 - 1
2 - 2
2 - 3
3 - 1
3 - 2
3 - 3如果我聪明的话,我会让我的内循环比外循环的起点高一个。然后,我只会以以下几点作为结束:
1 - 2
1 - 3
2 - 3这就大大减少了循环次数,而且只有3个数字。
尝试将for循环行替换为: For j=f+1 To Platform.Count -1
如果你这样做了,你还有一个额外的好处,那就是不需要检查j,<>,f。
发布于 2011-11-08 07:54:50
这段代码看起来没问题。我认为这个错误发生在你的碰撞代码中,因为这个代码决定了你的速度。
试一试
速度(F)= -Speed(f);
还有,你真的按到变速了吗?碰撞后速度的值是多少?
https://stackoverflow.com/questions/8044295
复制相似问题