Game Dev Advanced
21 Vector math
Every engine leans on a small vector type. Here you give a Vec2 the two operations everything else builds on, then use them to advance a body one physics step.
Implement one semi-implicit Euler step: apply gravity to the velocity, then move the position by the new velocity. Return (pos, vel).
Hints
- Update velocity first:
v += gravity * dt, thenpos += v * dt. - Do it component by component; there is no operator overload here.
Reveal solution
#[derive(Clone, Copy, PartialEq, Debug)]
struct Vec2 { x: f32, y: f32 }
fn step(pos: Vec2, vel: Vec2, gravity: Vec2, dt: f32) -> (Vec2, Vec2) {
let nv = Vec2 { x: vel.x + gravity.x * dt, y: vel.y + gravity.y * dt };
let np = Vec2 { x: pos.x + nv.x * dt, y: pos.y + nv.y * dt };
(np, nv)
}