简体   繁体   中英

Using code to write a function that calculates values for Projectile motion

I have an assignment that asks me to use some given code to write a function which calculates the angle needed to hit a target 10 metres away.

here is the given code:

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

How would I now write a function to calculate the required value? I have no idea where to start, any help would be greatly appreciated!

Thanks

You could use maths to work out an equation for the result.

This works out as:

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

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

You can use this python script to find the answer:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM