[英]How can I detect the collision of multiple turtle objects?
我在屏幕上有一堆烏龜對象。 他們還沒有做任何事情,但我正在嘗試以最簡單的方式檢測海龜對象的碰撞。 我知道我應該將所有海龜元素turtle.pos
與所有其他元素的turtle.pos
進行比較,但我不確定該怎么做。
此外,我擔心不將任何一項與其自身的 position 進行比較。
from turtle import *
import random
screen = Screen()
screen.bgcolor("grey")
screen.setup(width=800, height=600)
my_turtles = []
for i in range(10):
turtle = Turtle()
turtle.penup()
turtle.setx(random.randrange(-50, 50))
turtle.sety(random.randrange(-50, 50))
my_turtles.append(turtle)
#for t in turtles:
# if t.pos == anyother t.pos_except_itself
# do something
screen.listen()
screen.exitonclick()
你最不想做的就是直接比較一個turtle.position()
和另一個turtle.position()
。 原因是海龜在一個浮點平面上游盪,直接比較坐標值很少能按你想要的方式工作。 相反,您需要決定將被視為碰撞的兩只海龜(的中心)之間的最小距離。 一旦你知道那個距離,然后是一個循環:
for a in turtles:
if any(a != b and a.distance(b) < SAFE_MARGIN for b in turtles):
# collision, do something here
這是您的代碼的返工,它會導致任何過度侵入彼此個人空間的海龜眨眼:
from turtle import Screen, Turtle
from random import randrange
RADIUS = 10
def blink_turtles():
for a in turtles:
if any(a != b and a.distance(b) < RADIUS for b in turtles):
a.color(*reversed(a.color()))
screen.ontimer(blink_turtles, 1000)
screen = Screen()
screen.setup(width=800, height=600)
turtles = []
for _ in range(15):
turtle = Turtle()
turtle.hideturtle()
turtle.shape('turtle')
turtle.color('red', 'green')
turtle.penup()
turtle.goto(randrange(-50, 50), randrange(-50, 50))
turtle.showturtle()
turtles.append(turtle)
blink_turtles()
screen.exitonclick()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.