![](/img/trans.png)
[英]Making a Magic 8 Ball program in python, what's wrong with this?
[英]python - what's wrong with my ball/bat collision and reflection?
我寫了一個突破風格的游戲,除了球棒的碰撞和反射之外,其他所有功能都適用。 它應該起作用,以便如果球在擊中球時從左到右移動:
如果撞到左端,則沿原方向反彈;如果撞到右端,則沿原方向反彈
從右到左的方向反之亦然。 和:
如果擊中中間區域,則以相同的角度彈回;如果擊中中央/左/右區域,則以較小的角度彈回。
它有時甚至會越過球棒並應反彈,這令人困惑,但是我認為這可能是由於`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
您說對了,是因為
theball.y+BH == thebat.y
在一個角度,球不太可能恰好位於正確的高度。 嘗試改為增加一些不確定性。 例如:
UNCERTAINTY = 10
if theball.y+BH - UNCERTAINTY <= thebat.y <= theball.y+BH + UNCERTAINTY and ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.