Learning Python by Building Games by Sachin Kafle

Learning Python by Building Games by Sachin Kafle

Author:Sachin Kafle
Language: eng
Format: epub
Tags: COM012040 - COMPUTERS / Programming / Games, COM087020 - COMPUTERS / Desktop Applications / Design and Graphics, COM051360 - COMPUTERS / Programming Languages / Python
Publisher: Packt Publishing
Published: 2019-10-11T13:18:43+00:00


Dealing with two-dimensional vectors

Before actually exploring vectors, let's start with the basic overview of motion and how characters are moved in a straight line. To move any object or image, we have to make a slight change to the frames by a fixed amount. The movement must be fixed for each frame in order to make it symmetrical. To make an object move in a horizontal direction, we carry out an addition of a fixed amount to the x position, and to make it move in a vertical direction, we add the same amount to the y position. Thus, motion in 2D games can be represented as (x, y). Let's consider the following example to illustrate the usage of these coordinates on order to draw any shape into the game environment:

def line(a, b, x, y):

"Draw line from `(a, b)` to `(x, y)`."

import turtle

turtle.up()

turtle.goto(a, b)

turtle.down()

turtle.goto(x, y)

We are using the turtle module, which we used in the previous chapter to draw a line using the (a, b) and (x, y) positions. The goto() method is used to move the pen to the passed positions. These coordinates—(x, y) or (a, b)—clearly show the importance of knowing the positions in order to create game characters (we use line as a metaphor for any game character).

We can deem that the usage of a straight line motion is pretty useful, but looking at it from a different perspective, a game that only supports vertical or horizontal motions may seem dull and unexciting. For example, in the Pacman game, where a player would move either in a vertical or horizontal direction, this may be appropriate, but in the case of a car-racing game, where users can move in any direction, this motion doesn't work properly. We must be able to move in any direction by adjusting the positions of x and y for each frame. We will use the same two positions, x and y, to generate both straight and diagonal motions: a rate that indicates speed for the x and y positions. The form that represents (x, y) is known as a vector, but more importantly, vectors signify direction, unlike scalar. We will explore vectors in more detail in the following subsection.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.