Search code examples
python-3.xgraphjupyter-notebookphysicsprojectile

Python projectile motion graph gives me a straight line


Here is the code that should calulate the motion but it is producing a line instead of a parabola, any help is appreciate.

import math as m
import matplotlib.pyplot as plt
import numpy as np

class Projectile_motion:
    def __init__(self, V_x, V_y, g, delta_time):
        self.gravity = g
        self.V_x = V_x
        self.V_y = V_y
        self.delta_time = delta_time

    def velocity(self, angle):
        self.angle = angle
        self.V_x= m.ceil(self.V_x *m.cos(self.angle))
        self.V_y = m.ceil((self.V_y * m.sin(self.angle))) - (self.gravity * self.delta_time)

    def distance(self, x, y):
        self.x = x
        self.y = y
        self.x = self.x + (self.V_x * self.delta_time)
        self.y = self.y + (self.V_y * m.sin(self.angle)) + (0.5 * self.gravity * ((self.delta_time)**2))
        return self.x, self.y


ww = np.linspace(0, 50, num=5)
for i in ww:
    attempt1 = Projectile_motion(30, 30, 9.8, i)
    attempt1.velocity(1.042)
    ss=attempt1.distance(0, 0)
plt.plot(ss)
plt.show()

Output:


Solution

  • You are off to a good start here, but you need to clean up some of the physics in your model.

    If you have a V_x and V_y, it isn’t clear what you are doing with an angle, because that is already defined by the relationship of V_x and V_y.

    I would suggest you get rid of the angle for a starter. Then, you just need to do a couple things with V_y:

    1. Update V_y repeatedly when you are running. Gravity should be increasing V_y, right? Right now your V_y does not update. It should increase by 9.8m/s^2, so that is your update every time step
    2. Use this updated V_y to calculate the distance. So After you update V_y, just use that to change y position. You should not be doing any more math there, just y += V_y*dt

    If you get that working, you can transition back to using an angle (which I assume is your initial direction) and calculate V_x and V_y by standard application of cosine and sine on the angle. Also, remember, the math module wants angular inputs in radians.