2016-03-02 67 views
0

我写了一个突破风格的游戏,它除了球蝙蝠的碰撞和反射之外都起作用。它应该使工作如果球从左向右移动,因为它击中了蝙蝠:python - 我的球/蝙蝠碰撞和反射有什么问题?

如果它击中左端它反弹回它 来的方向,如果它击中它反弹的右端在相同的方向

,反之亦然从右到左的方向。并且:

如果它碰到中间区域,它会以相同的角度反弹回来,如果它碰到中心左/右区域,它会在角度发生轻微变化时反弹回去。

它有时也会通过蝙蝠,即使它结束了,应该是反弹,这是令人困惑的,但我认为可能是由于`BH == Bat.y线,因为球正在移动角度等都可能略微超过,并继续进行。

代码:(BAW/H =蝙蝠宽/高,BW/H =球宽/高)

# check with bat 

if theball.y+BH == thebat.y and (theball.x >= thebat.x-5 and theball.x <= thebat.x+BATW): 

# collision in centre - rebounds with angle reflection == angle incidence 

    if theball.cx>= thebat.x+40 and theball.cx<=thebat.x+60: 
     theball.dy = -theball.dy 
     return 

    # else find ball direction, do all areas for each direction 

    if theball.oldx < theball.x: # ball moving left to right, find which area: ends, mid lef, mid right, centre 

     # collision with left end 

     if theball.cx<= thebat.x+10: 

     # ball rebounds back in direction it came from 

      theball.dx = - theball.dx 
      theball.dy = - theball.dy 
      return 

     # collision with right end 

     if theball.cx >= thebat.x+90: 

      angle -= 10 
      if angle < MIN_ANGLE: 
       angle = MIN_ANGLE 

      theball.dx, theball.dy = calc_dxdy(angle) 
      return 

     # middle left and right 

     # mid left 

     if (theball.cx > thebat.x+10 and theball.cx < thebat.x+40): 

      angle -=5 
      if angle <= MIN_ANGLE: 
       angle = MIN_ANGLE 
       theball.dx, theball.dy = calc_dxdy(angle) 
       return 

     # mid right 

     if (theball.cx > thebat.x+60 and theball.cx < thebat.x+90): 

      angle +=5 
      if angle >= MAX_ANGLE: 
       angle = MAX_ANGLE 
       theball.dx, theball.dy = calc_dxdy(angle) 
       return 

    # ball moving right to left 

    if theball.oldx > theball.x: # ball moving right to left, find which area: ends, mid lef, mid right, centre 

     # collision with right end 

     if theball.cx>= thebat.x+90: 

     # ball rebounds back in direction it came from 

      theball.dx = - theball.dx 
      theball.dy = - theball.dy 
      return 

     # collision with right end 

     if theball.cx <= thebat.x+10: 

      angle += 10 
      if angle > MAX_ANGLE: 
       angle = MAX_ANGLE 

      theball.dx, theball.dy = calc_dxdy(angle) 
      return 

     # middle left and right 

     # mid left 

     if (theball.cx > thebat.x+10 and theball.cx < thebat.x+40): 

      angle +=5 
      if angle <= MAX_ANGLE: 
       angle = MAX_ANGLE 
       theball.dx, theball.dy = calc_dxdy(angle) 
       return 

     # mid right 

     if (theball.cx > thebat.x+60 and theball.cx < thebat.x+90): 

      angle -=5 
      if angle >= MIN_ANGLE: 
       angle = MIN_ANGLE 
       theball.dx, theball.dy = calc_dxdy(angle) 
       return 

回答

0

你说得对,这是因为

theball.y+BH == thebat.y 

在角度,球不太可能在正确的高度。 尝试改为添加一些不确定性。例如:

UNCERTAINTY = 10 
if theball.y+BH - UNCERTAINTY <= thebat.y <= theball.y+BH + UNCERTAINTY and ...