【发布时间】:2017-01-25 22:06:22
【问题描述】:
我目前正在尝试进行简单的字符串模拟。目的是看起来像字符串,但我的看起来有点奇怪,我不知道解决方案是什么。有没有人有什么想法,这里是代码
from pygame.locals import *
from math import sqrt
import pygame
pygame.init()
screen = pygame.display.set_mode([500, 500])
clock = pygame.time.Clock()
class Node():
def __init__(self, position, mass, initalVelocity):
self.position = position[:]
self.mass = mass
self.velocity = initalVelocity
def update(self):
self.position[0] += self.velocity[0]
self.position[1] += self.velocity[1]
class String():
def __init__(self, nodes, gravity = .981 , springConstant = 10, iterations = 1):
self.nodes = nodes[:]
self.gravity = gravity
self.springC = springConstant
self.iterations = iterations
self.setDistance = 1
def calculateForces(self):
for x in range(self.iterations):
for i in range(1, len(self.nodes), 1):
distance = sqrt((self.nodes[i].position[0] - self.nodes[i - 1].position[0]) ** 2 + (self.nodes[i].position[1] - self.nodes[i - 1].position[1]) ** 2)
force = -self.springC * (distance - self.setDistance)
force = force / self.nodes[i].mass
nDistanceVector = [(self.nodes[i].position[0] - self.nodes[i - 1].position[0]) / distance, (self.nodes[i].position[1] - self.nodes[i - 1].position[1]) / distance]
nDistanceVector = [nDistanceVector[0] * force, nDistanceVector[1] * force]
self.nodes[i].velocity[0] = 0.71 * self.nodes[i].velocity[0] + nDistanceVector[0]
self.nodes[i].velocity[1] = 0.71 * self.nodes[i].velocity[1] + (nDistanceVector[1] + self.gravity)
self.nodes[i].update()
pygame.draw.aalines(screen, [0, 0, 0], False, a)
a = [Node([250 + i * 10, 100], 100, [0, 1]) for i in range(25)]
s = String(a)
while 1:
screen.fill([255, 255, 255])
s.calculateForces()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
pygame.display.update()
clock.tick(60)`
我使用胡克定律,当每个节点与前一个节点超出一定距离时,每个节点都会充当弹簧,但它看起来笨重且不切实际。我错过了什么?
【问题讨论】:
-
我无法运行代码 -
aalines中的数据有问题 -
好的,我运行它。至于我,它看起来不错,但我不知道该期待什么。如果我设置更大的质量 - 大约 150 - 那么它看起来可能更真实。
-
顺便说一句:对我来说更易读的版本:pastebin.com/4Aq5fzAX
-
顺便说一句:与
pygame.math.Vector2相同:pastebin.com/JkmrND7v
标签: python-3.x pygame physics game-physics