Welcome, guest | Sign In | My Account | Store | Cart

A class used for creating any object moving in 2D or a Vector Object it takes the initial position, speed, and direction, and lets you addspeed to the the object, steer the object and update it by time.

Python, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#a class used for creating any object moving in 2D or a Vector Object (VObject)
#for direction use degrees, think of a 2d environment like:
#
#                  90
#                   |
#                   |
#           180 ----+----- 0
#                   |
#                   |
#                  270
#

from math import cos as _cos, sin as _sin, radians as _rad

class VObject():
    def __init__(self,x,y,speed,direction):
        self.x = x
        self.y = y
        self.s = speed
        self.d = _rad(direction)    

    def update(self,time=1):
        distance = self.s*time
        y = (_sin(self.d))*distance
        x = (_cos(self.d))*distance
        self.x += x
        self.y += y

    def addspeed(self,speed):
        self.s += speed

    def steer(self,angle):
        self.d += _rad(angle)

    def getx(self): return self.x
    def gety(self): return self.y

I've used this to create an asteroids game, a car driving sim, and a snake game I'm sure there are plenty of other uses... basically anything physics based which involves straight line motion, or 2d motion and uses vectors.

i wanted to include the function; accelerate(self,force,time,direction=self.d): in order to add the physics of currents, thrust, gravity, or wind on an object but I'm new, and couldn't figure out how i could do that and still keep update functional. i wanted to be able to use update to see where the object would be while it accelerated in the direction. It would blow the functionality of this script wide open. any ideas?

Created by Symon Polley on Fri, 18 May 2007 (PSF)
Python recipes (4591)
Symon Polley's recipes (3)

Required Modules

Other Information and Tasks