一直使用海龟库来制作台球和主球轨迹。我已经实现了球的轨迹物理,所以当它撞到墙壁(或指定的有限距离)时,它会反射到适当的方向。但我遇到了一个问题,那就是球会朝一个我没有指定的方向移动,然后根据标题给出它稍微向那个方向旋转的方向。我调试了代码,没有发现任何问题,并试图找到主球最初试图到达的坐标,因为我知道,如果球移动的循环发生变化,初始值总是指向该方向,并打破具有方向的点。
import turtle
from math import *
t = turtle.Turtle()
width=200
# White ball - Moving ball
t.color("black")
t.shape("circle")
t.penup()
t.goto(90,-80)
# White ball - Permanent
ball=turtle.Turtle()
ball.speed(0)
ball.penup()
ball.goto(90,-80)
ball.color("black")
ball.shape("circle")
angleString="Enter the hit force's angle (0-360) in degrees: "
angle=int(input(angleString))
# Moving Ball
t.color("yellow")
# Ball movement mechanic
step=20
t.penup()
LIMIT_X=width-8
LIMIT_Y=(width/2)-8
t.setheading(angle)
t.pendown()
x=-LIMIT_X
y=LIMIT_Y
t.dx=step*cos(angle)
t.dy=step*sin(angle)
for x in range(50):
t.speed(1)
print(x,t.pos(), t.heading())
x+=t.dx
y+=t.dy
t.goto(x,y)
# Check vertical borders
if abs(x)>LIMIT_X:
t.dx=-t.dx
# Check horizontal borders
if abs(y)>LIMIT_Y:
t.dy=-t.dy
turtle.done()发布于 2021-11-11 05:40:40
我发现你的代码有两个问题。首先,您同时使用两个不同的x变量:
x=-LIMIT_X
y=LIMIT_Y
t.dx=step*cos(angle)
t.dy=step*sin(angle)
for x in range(50):
t.speed(1)
print(x,t.pos(), t.heading())
x+=t.dx
y+=t.dy
t.goto(x,y)我猜iteration x变量只用于调试print()语句,而不是用来定位球,应该重命名。
其次,angle是以度为单位的,但来自数学模块的三角函数假定为弧度,因此这些计算没有任何意义:
t.dx=step*cos(angle)
t.dy=step*sin(angle)使用math中的radians()函数转换角度。(Turtle可以使用这两种方法,但如果您想使用弧度而不是度数,则需要告诉它。)
此外,此语句不执行任何操作:
t.setheading(angle)当你用goto()移动你的球时。只有当您使用forward()移动球时,标题才有意义。
我对您的代码进行了修改,修复了上述问题以及其他更改:
from turtle import Screen, Turtle
from math import sin, cos, radians
WIDTH = 200
LIMIT_X = WIDTH - 8
LIMIT_Y = WIDTH/2 - 8
STEP = 20
ANGLE_STRING = "Enter the hit force's angle (0-360) in degrees: "
CURSOR_SIZE = 20
angle = int(input(ANGLE_STRING))
screen = Screen()
# Billard table (roughly)
table = Turtle()
table.hideturtle()
table.shape('square')
table.shapesize(WIDTH / CURSOR_SIZE + 1, WIDTH*2 / CURSOR_SIZE + 1)
table.color('green')
table.stamp()
# Black ball - Permanent
permanent = Turtle()
permanent.shape('circle')
permanent.color('black')
permanent.penup()
permanent.goto(90, -80)
# Yellow ball - Moving ball
moving = permanent.clone()
moving.color('yellow')
moving.pendown()
x = -LIMIT_X
y = LIMIT_Y
moving.dx = STEP * cos(radians(angle))
moving.dy = STEP * sin(radians(angle))
for z in range(50):
moving.speed('slowest')
print(z, moving.pos(), moving.heading())
x += moving.dx
y += moving.dy
moving.goto(x, y)
# Check vertical borders
if abs(x) > LIMIT_X:
moving.dx = -moving.dx
# Check horizontal borders
if abs(y) > LIMIT_Y:
moving.dy = -moving.dy
screen.mainloop()我并不是说它做了你想要的,它只是没有那么多buggy。也许你的议案基于setheading()和forward()而不是goto(),可能会得到你想要的结果。当然,你必须重新考虑你的墙反射逻辑。
https://stackoverflow.com/questions/69909968
复制相似问题