Vectors in PyGame

From TRCCompSci - AQA Computer Science
Revision as of 13:50, 17 July 2018 by Admin (talk | contribs) (Created page with "=Intro= Python can use tuples and lists to essentially represent a vector, however these will not allow you to do any real vector calculations. for example: <syntaxhighligh...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Intro

Python can use tuples and lists to essentially represent a vector, however these will not allow you to do any real vector calculations.

for example:

pos = [200,200]

Pygame has a built in maths module for 2D vector calcuations, you can import it:

import pygame.math as math

You can then create a new vector:

test = math.Vector2(200,200)

Simple Calculations

You can add or subtract vectors using standard calculations:

PositionA = math.Vector2(200,200)
PositionB = math.Vector2(500,300)
Distance = PositionB - PositionA
Position= math.Vector2(200,200)
Movement = math.Vector2(1,1)
Position += Movement

Special Calculations

Dot Product

You can calculate the dot product between the vector and any other vector:

test=math.Vector2(200,200)
DOTPRODUCT = test.dot(math.Vector2(10,10))

Magnitude

Although pygame.math should contain a magnitude method, however this doesn't seem to be enabled. However the same calculation is also done by the length method:

test=math.Vector2(200,200)
test.length()


Distance

Pygame.math has a built in method to calculate the distance between any two vectors:

test=math.Vector2(200,200)
DISTANCE = test.distance_to(math.Vector2(10,10))

Other Features

Pygame.math has other features and methods to use, check them out:

https://www.pygame.org/docs/ref/math.html