问题是什么
我必须在1比1的盒子里模拟球。 我必须给球一个随机的速度和一个随机的角度。 然而,当我绘制球时,它们会直线并且在0.25时具有渐近线。 我翻了几倍我的数学但我找不到问题?
我的代码
import numpy
import matplotlib.pyplot as plt
import math
import random
def rand_tuples(aantalballen): # here i make a function that randomly makes a list with lists in #
list_balls = [] # the list, every index is a ball with x_pos , y_pos , speed , rotation #
for i in range(aantalballen):
list_balls.append([0.25, 0.75,0.1* random.random(), 2* math.pi*random.random()])
return list_balls
def ball_step(list_balls, dt): # this function calculates the steps the balls takes #
x = list_balls[0]
y = list_balls[1]
vx = math.cos(list_balls[3]) * list_balls[2] # speed in the x direction #
vy = math.sin(list_balls[3]) * list_balls[2] # speed in the y direction #
dt = dt
x_pos = x + (vx * dt) # calculates the actual positions #
y_pos = y + (vy * dt)
if x_pos <= 0 or x_pos >= 1: # collision detection #
vx = -vx
if y_pos <= 0 or y_pos >= 1:
vy = -vy
return x_pos, y_pos, vx , vy # returns the new positions but the same speed so that they can be used again#
def move_ball(ballen, tijd, dt): # takes a list of balls, time they move and the time steps they take#
positions_balls = { } # hold my position in {0:{'x':[positions}, 'y':{...}}}
time_1 = 0
for i in range(len(ballen)) :
positions_balls[i] = None # make a key with empty value #
time_1 = 0
cordinates = {'x':[], 'y':[]} # make the dictionary where my values go into #
while time_1 < tijd:
bal = ball_step(ballen[i] , dt) # call bal step to calculate my x and y position #
ballen[i] = bal
cordinates['x'].append(bal[0])
cordinates['y'].append(bal[1])
time_1 += dt
if int(time_1) == tijd:
positions_balls[i] = cordinates # finally add the dictionary to my main dictionary #
print positions_balls
return positions_balls
dic = move_ball(rand_tuples(30), 3, 0.01)
plt.plot(dic[0]['x'], dic[0]['y'])
plt.show()
我没有足够的声誉来发布情节图片:(
答案 0 :(得分:0)
ball_step()接受(我认为;评论是你的朋友)x,y,速度,旋转。它输出x,y,速度x,速度y。这已被分配回原始列表。