Represent position and velocity as two-dimensional vectors.
Update movement using delta time.
Normalize direction input before applying speed.
A 2D vector has an x and y component. Position describes where an object is; velocity describes how its position changes. Acceleration changes velocity.
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
Calculate the length of vector (3, 4).
Move an object at 200 units per second for 0.25 seconds.
Clamp a player's position inside a 640 by 360 play area.
Self-check
What is the difference between position and velocity?
Why normalize diagonal input?
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
Design a vector type or helper functions for addition, scaling, and length.
Implement eight-direction movement with equal speed in every direction.
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.