Moving the sprite with Vector in Pygame

In this chapter we are going to use our newly created Vector2D class to move the game sprite within a pygame screen. What we are doing here is to add up a vector with another vector which will then create a new vector that will be use as the sprite’s new position. If the user presses any of these keys on the keyboard : left arrow, right arrow, up arrow or the down arrow key then a new unit vector will be created and by multiplying that unit vector with the speed and time we will get a new vector which can then be added up to the old one and becomes the new position of the sprite object.

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit
from vector2d import Vector2D


boat = 'boat.png'

screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Pygame Demo")

player = pygame.image.load(boat).convert_alpha()

clock = pygame.time.Clock()
player_pos = Vector2D(350, 350)
player_speed = 300.
v = Vector2D(0., 0.)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
    pressed_keys = pygame.key.get_pressed()
    if pressed_keys[K_UP]:
        v = Vector2D(0., -1.) 
    elif pressed_keys[K_DOWN]:
        v = Vector2D(0., 1.) 
    elif pressed_keys[K_LEFT]:
        v = Vector2D(-1., 0.) 
    elif pressed_keys[K_RIGHT]:
        v = Vector2D(1., 0.)
    screen.fill((255, 255, 255))
    player_draw_pos = Vector2D(player_pos.x, player_pos.y)
    screen.blit(player, player_draw_pos)
    time_passed = clock.tick()
    time_passed_seconds = time_passed / 1000.0
    player_pos+= v * player_speed * time_passed_seconds   

With that we are almost done with the vector part of the pygame tutorial and ready for the next chapter in pygame so make sure you visit this blog everyday to learn the complete pygame tutorial!