You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现输入速度与角度后让海龟绘图的黑线呈抛物线击中五边形?

抛物线抛射游戏代码修改方案

我正在制作一款游戏,目标是让用户输入速度(m/s)和抛射角度(度),使黑线呈抛物线轨迹击中红色五边形。当前输入参数后黑线为直线运动,需要修改代码实现弧线运动,且认为代码最后几行需调整。我是Python新手,希望得到友好的技术帮助。

原代码

import turtle as t

t.color('blue')

t.begin_fill()
for _ in range(4):
    t.forward(20)
    t.left(90)
t.end_fill()

t.color('green')
t.forward(65)

t.color('red')

t.begin_fill()
for _ in range(5):
    t.forward(10)
    t.left(74)
t.end_fill()

t.setheading(0)
t.color('green')
t.forward(67)

print("The target is 181.1m away")
v=int(input("What velocity to use (m/s)?:"))
a=int(input("What angle to set (degrees)?:"))

import math
x_speed=v * math.cos(a)

y_speed=v * math.sin(a)

time_step=0.1
gravity=9.806

import turtle
pen=turtle.Turtle()
pen.reset
pen.forward(v*a)

修改后的完整代码

import turtle as t
import math

# 绘制场景:蓝色正方形起点、绿色路径、红色五边形目标
t.color('blue')
t.begin_fill()
for _ in range(4):
    t.forward(20)
    t.left(90)
t.end_fill()

t.color('green')
t.forward(65)

t.color('red')
t.begin_fill()
for _ in range(5):
    t.forward(10)
    t.left(74)
t.end_fill()

t.setheading(0)
t.color('green')
t.forward(67)

print("The target is 181.1m away")
v = int(input("What velocity to use (m/s)?:"))
a = int(input("What angle to set (degrees)?:"))

# 将角度转为弧度,math库三角函数默认用弧度计算
angle_rad = math.radians(a)
x_speed = v * math.cos(angle_rad)
y_speed = v * math.sin(angle_rad)

time_step = 0.1
gravity = 9.806

# 初始化抛射画笔:黑色,回到起点位置
pen = t.Turtle()
pen.color('black')
pen.penup()
pen.goto(0, 0)  # 回到蓝色正方形的初始位置
pen.pendown()
pen.setheading(a)  # 对齐输入的抛射角度

# 循环模拟抛物线运动,直到物体落地
current_x = 0
current_y = 0
while current_y >= 0:
    # y方向速度受重力持续减速
    y_speed -= gravity * time_step
    # 更新当前位置
    current_x += x_speed * time_step
    current_y += y_speed * time_step
    # 移动画笔到新位置,画出轨迹
    pen.goto(current_x, current_y)

关键修改说明

  • 弧度转换:Python的math.cos()和math.sin()默认接收弧度值,必须用math.radians()把输入的角度转换成弧度,否则计算出的速度方向会完全错误。
  • 抛物线模拟逻辑:用循环逐帧更新位置:
    • y方向速度会被重力持续减速(每次减去gravity * time_step)
    • 每次循环计算新的x、y坐标,用goto()移动画笔,自然形成平滑的抛物线轨迹
  • 画笔初始化调整:把抛射的画笔移到蓝色正方形的起点位置,设置为黑色,确保从正确位置开始运动。
  • 代码规范优化:移除了重复导入的turtle库,让代码更整洁。

内容的提问来源于stack exchange,提问作者Polly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:10:31