【发布时间】:2016-03-02 08:22:12
【问题描述】:
我写了一个突围风格的游戏,除了球棒碰撞和反射之外,它都可以正常工作。它应该可以工作,如果球在击球时从左向右移动:
如果它击中左端,它会弹回原来的方向 如果它击中右端,它会朝同一个方向反弹
从右到左的方向反之亦然。并且:
如果它击中中间区域,它会以相同的角度反弹回来 如果它击中中心的左/右区域,它会弹回并略微改变角度。
它有时也会穿过球棒,即使它在球棒上方并且应该反弹,这令人困惑,但我认为可能是由于 `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
【问题讨论】:
标签: python collision-detection collision