From 7a03b89b993db8598c8407688fdffb1952f74c3a Mon Sep 17 00:00:00 2001 From: Cameron Reikes Date: Wed, 25 Jan 2023 07:37:53 -0800 Subject: [PATCH] Apply force at point --- physics.jai | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/physics.jai b/physics.jai index 10823a4..c0b06b3 100644 --- a/physics.jai +++ b/physics.jai @@ -38,6 +38,12 @@ MASS :: 1.0; moment_of_inertia :: (using r: Rect) -> float { return MASS*(halfsize.y*halfsize.y + halfsize.x*halfsize.x)/12.0; } +apply_force_at_point :: (r: *Rect, force: Vector2, point_world_space: Vector2) { + r.force += force; + offset_from_center_of_mass := point_world_space - r.pos; + r.torque += offset_from_center_of_mass.x * force.y - offset_from_center_of_mass.y * force.x; +} + draw_rect :: (using r: Rect) { facing_to_right := rotate(xy(halfsize.x,0.0), angle); facing_to_up := rotate(xy(0.0,halfsize.y), angle); @@ -93,7 +99,7 @@ main :: () { rects: [..]Rect; array_add(*rects, .{pos = #run xy(0.0, 0.0), halfsize = #run xy(0.3)}); - array_add(*rects, .{pos = #run xy(1.5, 0.0), halfsize = #run xy(0.3)}); + array_add(*rects, .{pos = #run xy(2.5, 0.0), halfsize = #run xy(0.3)}); quit := false; @@ -139,9 +145,19 @@ main :: () { defer unprocessed_time -= TIMESTEP; - - - rects[0].angle += TIMESTEP * 1.0; + if get_time() < 0.5 + { + apply_force_at_point(*rects[0], xy(3, 0), rects[0].pos + xy(-0.1, 0.03)); + } + for * rects + { + defer { it.force = .{}; it.torque = 0.0; }; + it.vel += (it.force/MASS) * TIMESTEP; + it.pos += it.vel * TIMESTEP; + + it.angle_vel += (it.torque / moment_of_inertia(it)) * TIMESTEP; + it.angle += it.angle_vel * TIMESTEP; + } } }