-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vehicle.py
65 lines (54 loc) · 1.87 KB
/
Vehicle.py
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# The Nature of Code
# Daniel Shiffman
# http://natureofcode.com
# The "Vehicle" class
class Vehicle():
def __init__(self, x, y):
self.acceleration = PVector(0, 0)
self.velocity = PVector(0, -2)
self.position = PVector(x, y)
self.r = 6
self.maxspeed = 4
self.maxforce = 0.2
# Method to update location
def update(self):
# Update velocity
self.velocity.add(self.acceleration)
# Limit speed
self.velocity.limit(self.maxspeed)
self.position.add(self.velocity)
# Reset accelerationelertion to 0 each cycle
self.acceleration.mult(0)
def applyForce(self, force):
# We could add mass here if we want A = F / M
self.acceleration.add(force)
# A method that calculates a steering force towards a target
# STEER = DESIRED MINUS VELOCITY
def arrive(self, target):
# A vector pointing from the location to the target
desired = target - self.position
d = desired.mag()
# Scale with arbitrary damping within 100 pixels
if (d < 100):
m = map(d, 0, 100, 0, self.maxspeed)
desired.setMag(m)
else:
desired.setMag(self.maxspeed)
# Steering = Desired minus velocity
steer = desired - self.velocity
steer.limit(self.maxforce) # Limit to maximum steering force
self.applyForce(steer)
def display(self):
# Draw a triangle rotated in the direction of velocity
theta = self.velocity.heading() + PI / 2
fill(127)
stroke(200)
strokeWeight(1)
with pushMatrix():
translate(self.position.x, self.position.y)
rotate(theta)
beginShape()
vertex(0, -self.r * 2)
vertex(-self.r, self.r * 2)
vertex(self.r, self.r * 2)
endShape(CLOSE)