Tutorial 1: Vectors, Velocity, and Acceleration

Unit 2 · 2D math and movement

Objectives

A 2D vector has an x and y component. Position describes where an object is; velocity describes how its position changes. Acceleration changes velocity.

velocityX += accelerationX * deltaSeconds;
velocityY += accelerationY * deltaSeconds;
positionX += velocityX * deltaSeconds;
positionY += velocityY * deltaSeconds;

Keyboard input such as right plus up produces a vector of (1, 1), whose length is greater than 1. Normalize it before multiplying by speed, or diagonal movement will be faster.

Exercises

  1. Calculate the length of vector (3, 4).
  2. Move an object at 200 units per second for 0.25 seconds.
  3. Clamp a player's position inside a 640 by 360 play area.

Self-check

  1. What is the difference between position and velocity?
  2. Why normalize diagonal input?
  3. What does acceleration change?

Self-Check Quiz

1. What is the length of (3, 4)?

Answer5, using the Pythagorean theorem.

2. What should position use to remain frame-rate independent?

AnswerUpdate position using velocity multiplied by elapsed time.

Homework

  1. Design a vector type or helper functions for addition, scaling, and length.
  2. Implement eight-direction movement with equal speed in every direction.
  3. Explain your boundary-clamping rule.
Sample answerNormalize the input vector when its length is nonzero, multiply it by speed, then update position by velocity times delta time. Clamp x to 0..640 and y to 0..360 after updating.
👤