简体   繁体   English

如果两只海龟相互接触,如何反弹2只海龟

[英]How to bounce 2 turtles if both are touching each other

I am trying to make a bouncing ball simulator. 我正在尝试制作一个弹跳球模拟器。 I would like some help trying to get the balls bounce off each other if they touch like if they touch the ball, they bounce in the other direction. 我想要一些帮助试图让球互相反弹,如果他们触摸就像他们触摸球,他们反弹另一个方向。

I have tried doing this: 我试过这样做:

def is_collided_with(a):
    for ball in balls:
        if abs(a.xcor() - ball.xcor()) < 3 and abs(a.ycor() - ball.ycor()) < 3:
            a.dx *= -1
            ball.dx *= -1
            a.dy *= -1
            ball.dy *= -1

while True:
    ... other code
    [is_collided_with(ball) for ball in balls]

But the balls don't seem to bounce off each other. 但球似乎没有相互反弹。 Can you please help me? 你能帮我么?

Code: 码:

import turtle
import random
import time

wn = turtle.Screen()
wn.bgcolor("black")
wn.tracer(0)

balls = []
numOfBalls = len(balls)

for _ in range(10):
    balls.append(turtle.Turtle())

colors = ["yellow", "gold", "orange", "red", "maroon", "violet", "magenta", "purple", "navy", "blue", "skyblue", "cyan", "turquoise", "lightgreen", "green", "darkgreen", "chocolate", "brown", "black", "gray", "white"]

for ball in balls:
    ball.shape("circle")
    ball.color(random.choice(colors))
    ball.penup()
    ball.speed(0)
    x = random.randint(-290, 290)
    y = random.randint(200, 400)
    ball.goto(x, y)
    ball.dy = 0
    ball.dx = random.randint(-3, 3)

gravity = 0.1

def addBall():
    balls.append(turtle.Turtle())
    balls[-1].shape("circle")
    balls[-1].color(random.choice(colors))
    balls[-1].penup()
    balls[-1].speed(0)
    x = random.randint(-290, 290)
    y = random.randint(200, 400)
    balls[-1].goto(x, y)
    balls[-1].dy = 0
    balls[-1].dx = random.randint(-3, 3)

def removeBall():
    balls[-1].reset()
    balls.pop()

def reload():
    for ball in balls:
        ball.shape("circle")
        ball.color(random.choice(colors))
        ball.penup()
        ball.speed(0)
        x = random.randint(-290, 290)
        y = random.randint(200, 400)
        ball.goto(x, y)
        ball.dy = 0
        ball.dx = random.randint(-3, 3)

_tick2_frame = 0
_tick2_fps = 20000000
_tick2_t0 = time.time()

def tick(fps=60):
    global _tick2_frame,_tick2_fps,_tick2_t0
    n = _tick2_fps/fps
    _tick2_frame += n
    while n>0: n-=1
    if time.time()-_tick2_t0>1:
        _tick2_t0 = time.time()
        _tick2_fps = _tick2_frame
        _tick2_frame=0

def is_collided_with(a):
    for ball in balls:
        if abs(a.xcor() - ball.xcor()) < 3 and abs(a.ycor() - ball.ycor()) < 3:
            a.dx *= -1
            ball.dx *= -1
            a.dy *= -1
            ball.dy *= -1


turtle.onkey(addBall, "a")
turtle.onkey(removeBall, "p")
turtle.onkey(reload, "r")
turtle.onkey(turtle.bye, "q")
turtle.listen()

while True:
    wn.update()
    numOfBalls = len(balls)
    if numOfBalls > 1:
        wn.title(str(numOfBalls) + ' Bouncing Balls')
    elif numOfBalls == 1:
        wn.title(str(numOfBalls) + ' Bouncing Ball')        
    elif numOfBalls == 0:
        wn.title(str(numOfBalls) + ' Bouncing Balls')
    else:
        wn.title('NaN Bouncing Balls')        

    for ball in balls:
        ball.dy -= gravity
        ball.sety(ball.ycor() + ball.dy)

        ball.setx(ball.xcor() + ball.dx)

        if ball.xcor() > 450 or ball.xcor() < -450:
            ball.dx *= -1

        if ball.ycor() < -300:
            ball.sety(-300)
            ball.dy *= -1

    [is_collided_with(ball) for ball in balls]

    tick(60)

turtle.listen()
turtle.mainloop()

I believe this is the problem: 我相信这是问题所在:

[is_collided_with(ball) for ball in balls]

def is_collided_with(a):
    for ball in balls:
        if abs(a.xcor() - ball.xcor()) < 3 and abs(a.ycor() - ball.ycor()) < 3:
            a.dx *= -1
            ball.dx *= -1
            a.dy *= -1
            ball.dy *= -1

You're checking every ball against every other ball. 你正在检查每一个球对阵其他球。 And then only multiplying dx and dy by -1 if they collided. 如果它们相撞,则只将dxdy乘以-1。 But if A collided with B, then B collided with A so your logic kicks in twice , effectively undoing itself! 但是如果A与B相撞,那么B与A相撞,所以你的逻辑开始两次 ,有效地解除了它自己! And you don't check if A and B are the same ball, which is always a collision! 而且你不会检查A和B是否是同一个球,这总是一个碰撞!

Below is my rework and simplification of your code. 下面是我的返工和简化代码。 It isn't perfect but I believe you'll get more of the ball collision and bounce effects you're looking for: 它并不完美,但我相信你会得到更多你正在寻找的球碰撞和弹跳效果:

from turtle import Screen, Turtle
from random import choice, randint

BALL_DIAMETER = 40
WIDTH, HEIGHT = 600, 600

COLORS = ['yellow', 'gold', 'orange', 'red', 'maroon', 'violet', 'magenta', 'purple', 'navy', 'blue', 'skyblue', 'cyan', 'turquoise', 'lightgreen', 'green', 'darkgreen', 'chocolate', 'brown', 'gray', 'white']

INITIAL_BALLS = 8

GRAVITY = 0.1

CURSOR_SIZE = 20

def addBall():
    ball = Turtle('circle')
    ball.shapesize(BALL_DIAMETER / CURSOR_SIZE)
    ball.color(choice(COLORS))
    ball.penup()
    ball.speed('fastest')
    x, y = randint(BALL_DIAMETER - WIDTH/2, WIDTH/2 - BALL_DIAMETER), randint(BALL_DIAMETER - HEIGHT/2, HEIGHT/2 - BALL_DIAMETER)
    ball.goto(x, y)
    ball.dy = 0
    ball.dx = randint(-3, 3)

    balls.append(ball)

    numOfBalls = len(balls)

    if numOfBalls == 1:
        screen.title(str(numOfBalls) + " Bouncing Ball")
    else:
        screen.title(str(numOfBalls) + " Bouncing Balls")

def removeBall():
    balls.pop().hideturtle()

    numOfBalls = len(balls)

    if numOfBalls == 0 or numOfBalls > 1:
        screen.title(str(numOfBalls) + " Bouncing Balls")
    else:
        screen.title(str(numOfBalls) + " Bouncing Ball")

def reload():
    for ball in balls:
        ball.color(choice(COLORS))
        ball.penup()
        x, y = randint(BALL_DIAMETER - WIDTH/2, WIDTH/2 - BALL_DIAMETER), randint(BALL_DIAMETER - HEIGHT/2, HEIGHT/2 - BALL_DIAMETER)
        ball.goto(x, y)
        ball.dy = 0
        ball.dx = randint(-3, 3)

def is_collided_with(other):
    for ball in balls:
        if ball != other and ball.distance(other) < BALL_DIAMETER:
            other.dx *= -1
            ball.dx *= -1
            other.dy *= -1
            ball.dy *= -1

screen = Screen()
screen.setup(WIDTH, HEIGHT)
screen.bgcolor('black')
screen.tracer(False)

balls = []

for _ in range(INITIAL_BALLS):
    addBall()

screen.onkey(addBall, 'a')
screen.onkey(removeBall, 'p')
screen.onkey(reload, 'r')
screen.onkey(screen.bye, 'q')

screen.listen()

def tick():
    for ball in balls:
        ball.dy -= GRAVITY

        ball.sety(ball.ycor() + ball.dy)

        ball.setx(ball.xcor() + ball.dx)

        if ball.ycor() < -HEIGHT/2:
            ball.sety(-HEIGHT/2)
            ball.dy *= -1

        if ball.xcor() > WIDTH/2 or ball.xcor() < -WIDTH/2:
            ball.dx *= -1

        is_collided_with(ball)

    screen.update()
    screen.ontimer(tick, 60)

tick()
screen.mainloop()

Hopefully, this will give you enough of a working environment to perfect the details of balls bounding off of each other. 希望这会给你足够的工作环境来完善彼此之间的球的细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM