I need to create a variable(velocity) with magnitude and direction. How can this be done?

1.8k views Asked by At

Then with this velocity and acceleration and initial position find the next position(2D). The only tricky part is the creation of the vector!

3

There are 3 answers

2
Anand S Kumar On

You can create a class , then each instance (object) of that class would be a velocity object (vector) . A very simple example is -

class Velocity:
    def __init__(self, mag, direction):
        self.mag = mag
        self.direction = direction

Then you can create velocity objects like -

v1 = Velocity(5,5)
v2 = Velocity(10,15)

You can access the magnitude and direction of each velocity as -

print(v1.mag)
>> 5
print(v1.direction)
>> 5

The above is a minimalistic example , you will need to add whatever operations (read functions) you want our velocity object to support.

0
heinst On

You could create a velocity tuple, where magnitude is at index 0 and direction is at index 1. Then define acceleration as a float and a startingPos where x is at index 0 and y is at index 1.

#0: magnitude 1: direction (degrees above x axis)
velocity = (2.3, 55)
acceleration = 3.2
#0: x 1: y
startingPos = (-10, 0)
0
Malik Brahimi On

Just use standard vector math. Distance is the Pythagorean theorem and magnitude is trigonometry:

from math import *

class Vector2D:
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)

    def direction(self):
        return degrees(atan(self.y / self.x))

    def magnitude(self):
        return sqrt(self.x ** 2 + self.y ** 2)