如何在 python 中为海龟添加物理学

How to add physics to a turtle in python

我正在 python 中创建一个游戏,您可以四处移动并尝试通过与硬币碰撞来收集积分。我想给它添加 2D 物理以使其逼真。有什么办法吗?谢谢

模拟的本质是它们不同于现实。当我们进行模拟时,我们创建了对象行为的数学模型。让我们考虑重力的模拟。我们定义一个球,然后随着时间流逝移动球的位置。牛顿用 x=gt^2 模拟了球的下落。因此,我们必须为球定义一个朝向地面的加速度。有关模拟的更多信息可用 in this video

您可以使用此代码来模拟重力:

yvel=5*(time()-start_t)

其中 time() 来自 from time import time

操作方法如下: 解释在代码里面。

#Importing all the modules
import turtle
from turtle import *
import math

#Creating the screen
screen=Screen()

#Creating the turtle
vector1=Turtle("classic")
vector1.speed(-1)
vector1.penup()

#Declaring all the needed variables
Vx=0
Vy=0
V=0
A=0

#Starting the while loop
while True:

    #Updating the screen for better preformence
    screen.update()

    #Carculating the velocity
    V=math.sqrt(Vx**2+Vy**2)

    #Carculating the angle
    if Vx!=0:
        A=math.degrees(math.atan(Vy/Vx))
        if Vy<0 and Vx<0 or Vy>0 and Vx<0:
            A=A-180
    elif Vy <0:
        A=270
    else:
        A=90

#Moving the turtle    
    vector1.seth(A)
    vector1.fd(V)

#Changing the values of the velocities
    Vy-=0.5
    if Vx>0:
        Vx-=0.2
    elif Vx<0:
        Vx+=0.2

有什么问题请追问!