2017-03-03 32 views
0

值的功能,我有問我使用一些給定的代碼編寫,它計算到擊中目標10米以外所需角度的功能分配。使用代碼編寫計算彈丸運動

這裏是給定的代碼:

from visual import * 
from visual.graph import * # For the graphing functions 
#Create a graph display window (gdisplay) 

win = gdisplay(xtitle="Distance [m]", ytitle="Height [m]") 
#And a curve on this display 

poscurve = gcurve(gdisplay=win, color=color.cyan) 
#Target position (10 meters away) 

target_pos = vector(10,0,0) 
#Set the starting angle (in degrees) 

angle = 45 
#Set the magnitude of the starting velocity (in m/s) 

v0 = 12.0 
#Gravity vector (m/s**2) 

g = vector(0, -9.8, 0) 
#Create a vector for the projectile's velocity 

velocity = v0 * vector(cos(anglepi/180), sin(anglepi/180), 0) 
#and the position 

position = vector(0,0,0) 
dt = 0.01 # Time step 
#Start loop. Each time taking a small step in time 

while (position.y > 0) or (velocity.y > 0): # Change in position # dx =   (dx/dt) * dt dx = velocity * dt 
# Change in velocity 
# dv = (dv/dt) * dt 
dv = g * dt 

# Update the position and velocity 
position = position + dx 
velocity = velocity + dv 

# Plot the current position 
poscurve.plot(pos=position) 
#When loop finishes, velocity.y must be < 0, and position.y < 0 

print "Landed at X position: ", position.x print "X distance to target: ",  position.x - target_pos.x 

會怎樣我現在寫一個函數來計算所需要的價值?我不知道從哪裏開始,任何幫助將不勝感激!

感謝

+3

,因此用戶可能不會寫你的代碼,但回答您制定明確的問題。如果你的問題沒有顯示出足夠的知識,那麼它將在這裏被視爲脫離主題。 – Alfe

+0

看起來你正在嘗試一些數值積分/運動模擬。至少在2D中需要一個循環來進行這個和向量計算。在代碼中執行此操作,然後可以在此處詢問出現的明確問題。請確保向我們展示您的代碼。 – Alfe

回答

0

你可以用數學來制定出一個方程的結果。

這工作了如:

range = 2v^2/g *cos(a)sin(a) 

where v=initial velocity 
a=angle 
g=gravitational acceleration 

您可以使用此python腳本中找到了答案:

from math import cos 
from math import sin 
from math import radians 
from math import fabs 

a=0 # angle in degrees 
target=10 # How far you want it to go in m 
v=12 # initial velocity in m/s 
g=9.81 #gravitational acceleration m/s/s 

best_angle=None 
nearest_answer=None 

while a<45: # we only need to check up to 45 degrees 
    r = 2*v*v/g*cos(radians(a))*sin(radians(a)) 
    if not nearest_answer or fabs(r-target)<fabs(nearest_answer-target): 
     nearest_answer = r 
     best_angle = a 
    print("{0} -> {1}".format(a,r)) 
    a+=.1 # try increasing the angle a bit. The lower this is the more accurate the answer will be 

print("Best angle={}".format(best_angle))