Book Image

Cocos2d-x by Example: Beginner's Guide

By : Roger Engelbert
Book Image

Cocos2d-x by Example: Beginner's Guide

By: Roger Engelbert

Overview of this book

Table of Contents (19 chapters)
Cocos2d-x by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

What are vectors?


First, let's do a quick refresh on vectors and the way you can use Cocos2d-x to deal with them.

So what is the difference between a vector and a point? At first, they seem to be the same. Consider the following point and vector:

  • Point (2, 3.5)

  • Vec2 (2, 3.5)

The following figure illustrates a point and a vector:

In this figure, they each have the same value for x and y. So what's the difference?

With a vector, you always have extra information. It is as if, besides those two values for x and y, we also have the x and y of the vector's origin, which in the previous figure we can assume to be point (0, 0). So the vector is moving in the direction described from point (0, 0) to point (2, 3.5). The extra information we can derive then from vectors is direction and length (usually referred to as magnitude).

It's as if a vector is a person's stride. We know how long each step is, and we know the direction in which the person is walking.

In game development, vectors can be used, among other things, to describe movement (speed, direction, acceleration, friction, and so on) or the combining forces acting upon a body.

The vector methods

There is a lot you can do with vectors, and there are many ways to create them and manipulate them. And Cocos2d-x comes bundled with helper methods that will take care of most of the calculations for you. Here are some examples:

  • You have a vector, and you want to get its angle—use getAngle()

  • You want the length of a vector—use getLength()

  • You want to subtract two vectors; for example, to reduce the amount of movement of a sprite by another vector—use vector1 - vector2

  • You want to add two vectors; for example, to increase the amount of movement of a sprite by another vector—use vector1 + vector2

  • You want to multiply a vector; for example, applying a friction value to the amount of movement of a sprite—use vector1 * vector2

  • You want the vector that is perpendicular to another (also known as a vector's normal)—use getPerp() or getRPerp()

  • And, most importantly for our game example, you want the dot product of two vectors—use dot(vector1, vector2)

Now let me show you how to use these methods in our game example.