如何固定弹球的运动方向并使其发生碰撞



我制作了这个弹球游戏程序作为我班的作业,我一直在努力解决弹球的移动和碰撞问题。

第一个问题是,无论用户将哪个方向设置为速度,球都只能以特定的角度移动。

我真的不知道为什么它不起作用,根据我的笔记、演讲幻灯片和讨论讲义,它应该没问题。那么,有人知道为什么它不起作用吗?我环顾四周,找不到确切的答案。任何帮助都将不胜感激。我被难住了:(

不工作意味着无论用户将弹球设置到哪个方向,它都只在一个方向上移动(例如,用户将弹珠设置为向左,弹球设置为向右;用户将弹子设置为向上,弹球向右;等等)此外,弹球不会与墙壁或任何目标碰撞

图形就是图形.py:http://mcsp.wartburg.edu/zelle/python/graphics/graphics/index.html

这是碰撞代码(连同速度反转,只与游戏板的右壁保持碰撞):

def checkHit(ball,target,dispX,dispY,VelX,VelY,hit): ###pulled the definition out of the loop but keeping it here for easier reference
     center = ball.getCenter() ###defines the center of the pinball as a point
     hit = 0 ###used for differentiating between objects collided with
     if center.getX() + 1 <= 45 and center.getX() + 1 + dispX > 45: ####if the pinball collides with the right wall of the board
         VelX = VelX *(-1) ###velocity in the x direction reverses
         hit = 0  ###did not collide with a target
for j in range(1000):####1000 frames (ball isn't expected to last long in the air, only a couple seconds)
     vy = vy - 9.8 ###effect of gravity
     dx = vx / math.sqrt(vx**2 + vy**2) ###speed in x direction over time
     dy = vy / math.sqrt(vx**2 + vy**2) ###speed in y direction over time
     checkHit(pinball,target_front1,dx,dy,vx,vy,0) ####runs function each frame for collision testing
     pinball.move(dx , dy) ###moves pinball

我不能确定,因为您还没有告诉我们graphics模块是从哪里来的。学校很有可能。

尝试将一些if语句更改为elif s。您可能同时评估了太多语句。考虑以下代码,其中您只希望运行以下if语句中的ONE,但实际上,所有语句都在运行:

def foo(x):
 if x < 5:
  print 'x is greater than five'
 if x == 10:
  print 'x is 10'
foo(10)
>>> x is greater than 5
>>> x is 10

如果将第二个if更改为elif,那么如果运行第一个if语句,则会忽略其余的elif

def bar(x):
 if x < 5:
  print 'x is greater than five'
 elif x == 10:  #changed this line to an 'elif' 
  print 'x is 10'
bar(10)
>>> x is greater than 5   #only prints once, because the first if statement is True

您还为每个循环定义了checkHit,浪费了系统资源。最好把它从循环中拉出来,放到模块的最顶部。


编辑:事实上,上面的例子虽然是真的,但不是很好。想象一下,如果x,一个速度,大于5,球就会停止滚动,所以你现在可以把x改为0。然后立即用第二个if语句检查它,看看它是否已停止。如果它停止了,请重新开始移动(x == 5或其他什么)。这意味着球永远不会停止移动,因为无论怎样,在if语句结束时,球总是会再次开始移动。

因此,您需要使用elif语句,而不是第二个if,因为除非前一个if语句不是True,否则不会对elif求值。

最新更新