Недавно я решил написать дискретное симуляцию столкновений с нуля, чтобы помочь изучить Python и для личного удовольствия. Я написал эту программу, чтобы создать видео, сохранив каждый график после дискретного обновления времени в качестве изображения в папке, а затем скомпилируйте все эти изображения вместе (с помощью FFMPEG), что приведет к видео. Сначала я хотел посмотреть, что произойдет, если я смою смоделировать мяч в коробке под влиянием гравитации. Я знаю, как должен был появиться ответ, я играл с бодрыми мячами в детстве. Однако всякий раз, когда мяч приближается к концу своего подпрыгивания, он начнет простираться через пол с застрявшей скоростью, а не поднимаясь на пол, и я не могу для жизни, почему. Они держатся вместе, а не отскакивают, очень похоже на то, как один шарик будет прилипать к полу. < /P>
Это код, который я использовал. Я пытался прокомментировать это как можно лучше. Я не очень опытный кодировщик, поэтому я прошу прощения, если есть обычные ошибки. Я предполагаю, что в небольших количествах скорость после столкновения недостаточно, чтобы вытащить частицу на следующем кадре, поэтому она остается застрявшей в стене, когда скорость переворачивается снова и снова и снова, и никогда не может выйти. Я пытался изменить расчет скорости до абсолютного значения (поскольку, когда мяч попадает на землю, он имеет отрицательную скорость, а затем переключается на положительный), но мяч все равно будет продолжать проходить через пол, когда он должен быть в состоянии покоя. Код, который я использовал, включен ниже, а также ссылка на разброс, которая идет на видео. Где у кого -то есть какое -либо понимание?import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import math
import os
#Class defining a particle used in the simulation
class Particle:
def __init__(self, mass, position, velocity, acceleration):
self.mass = mass
self.radius = math.sqrt(self.mass/(math.pi*1.5))
self.position = position
self.velocity = velocity
self.acceleration = acceleration
self.KE = (1/2)*self.mass*np.dot(self.velocity,self.velocity)
self.left = position[0]-self.radius
self.right = position[0]+self.radius
self.top = position[1]+self.radius
self.bottom = position[1]-self.radius
#just defining the box that the simulation takes place in
class Box:
def __init__(self):
self.left = -10
self.right = 10
self.bottom = -10
self.top = 10
#Function that detects if there is a colision between the particle and the box
#This is where i think theres a problem but cant for the life of me figure out what it is
def handleBoxCollision():
#cor is the coefficient of restitution
cor = 0.8
if p.left = box.right:
p.velocity[0]=-cor*p.velocity[0]
if p.bottom = box.top:
p.velocity[1]=-cor*p.velocity[1]
#Since this is a discreet collision simulation this function is for updating the state of the simulation
def update(dt):
p.velocity = p.velocity+(p.acceleration*dt)
p.position = p.position+(p.velocity*dt)
p.left = p.position[0]-p.radius
p.right = p.position[0]+p.radius
p.top = p.position[1]+p.radius
p.bottom = p.position[1]-p.radius
handleBoxCollision()
#Because I run this simulation many times I first delete all the contents in my directory
#Then as simulation runs it saves each updated graph as a frame. Compile all frames into a video
#I took out the actual directory on my computer for privacy
dir = 'C:/PathToImageFile'
for f in os.listdir(dir):
os.remove(os.path.join(dir, f))
#Initial mass, position, velocity and acceleration
mass = 10
position = np.array([0,0])
velocity = np.array([5,0])
acceleration = np.array([0,-9.8])
#time step = 1/framerate
dt = 1/60
p = Particle(mass, position, velocity, acceleration)
box = Box()
#Run this loop for however many frames I want. In this case 600
for i in range(600):
figure, axes = plt.subplots()
update(dt)
#left of box
plt.plot([-10,-10],[-10,10],color='black')
#right of box
plt.plot([10,10],[-10,10],color='black')
#top of box
plt.plot([-10,10],[10,10],color='black')
#bottom of box
plt.plot([-10,10],[-10,-10],color='black')
cc = plt.Circle((p.position[0] ,p.position[1]), p.radius)
plt.scatter(p.position[0],p.position[1])
plt.xlim(-11,11)
plt.ylim(-11,11)
plt.text(-10,-10.7,"time="+str(i*dt))
plt.text(-10,10.3,"velocity="+str(p.velocity[1]))
axes=plt.gca()
axes.add_artist(cc)
axes.set_aspect(1)
figure.savefig('/PathToImageFile'+str(i)+'.png')
plt.close('all')
Подробнее здесь: https://stackoverflow.com/questions/761 ... ticle-simu
Как мне учитывать частицу в состоянии покоя на земле при моделировании гравитационных частиц? ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Получить подробную информацию по идентификатору транзакции после отправки гравитационных форм
Anonymous » » в форуме Php - 0 Ответы
- 63 Просмотры
-
Последнее сообщение Anonymous
-