Racey – Direction Vectors

Now we want to add a vector for movement.

STEP ONE: MODIFYING THE INIT FUNCTION

Inside our class initialisation function ( __init__) we can create a vector for movement

add the following to the __init__ function

# Create a random speed vector.
movespeed = random.randint(1, 10)
directionx = random.random()*movespeed * random.choice((-1, 1))
directiony = random.random()*movespeed * random.choice((-1, 1))
self.vector = pygame.math.Vector2(directionx , directiony )

def __init__(self, position):
    self.position = position
 
    # Create a random speed vector.
    movespeed = random.randint(1, 10)
    directionx  = random.random()*movespeed * random.choice((-1, 1))
    directiony = random.random()*movespeed * random.choice((-1, 1))
    self.vector = pygame.math.Vector2(directionx, directiony )

STEP TWO: MODIFYING THE MOVE FUNCTION TO USE THE VECTOR

change

self.position = (self.position[0], self.position[1] + 1)

to

self.position = self.position + self.vector

STEP THREE: MODIFYING THE MOVE FUNCTION TO CHECK FOR INSTANCES LEAVING ANY EDGE OF THE SCREEN

Currently we are checking if an instance moves of the bottom of the screen, now we need to check if it moves of any edge.

left x = 0
right x = display_width
top y = 0
bottom y = display_width

change

if self.position[1] > display_height – 50:

to

if self.position[0] < 0 or self.position[0] > display_width or  self.position[1] > display_height – 50 or self.position[1] < 0:

STEP FOUR: MODIFYING THE MOVE FUNCTION SO THAT NEW INSTANCES HAVE A RANDOM Y VALUE

change

dogArray.append(dog((random.randrange(10, display_width-50),10)))

to

dogArray.append(dog((random.randrange(10, display_width-50),random.randrange(10, display_height-100))))