1 # This file defines a World object for keeping track of everything, as well
2 # as the collision logic.
7 # Return a displacement relative to `a` that will push it out of `b`
8 func solve_overlap(a_pos:Vector2, a_size:Vector2, b_pos:Vector2, b_size:Vector2 -> Vector2)
10 a_right := a_pos.x + a_size.x
12 a_bottom := a_pos.y + a_size.y
15 b_right := b_pos.x + b_size.x
17 b_bottom := b_pos.y + b_size.y
19 # Calculate the overlap in each dimension
20 overlap_x := (a_right _min_ b_right) - (a_left _max_ b_left)
21 overlap_y := (a_bottom _min_ b_bottom) - (a_top _max_ b_top)
23 # If either axis is not overlapping, then there is no collision:
24 if overlap_x <= 0 or overlap_y <= 0
27 if overlap_x < overlap_y
28 if a_right > b_left and a_right < b_right
29 return Vector2(-(overlap_x), 0)
30 else if a_left < b_right and a_left > b_left
31 return Vector2(overlap_x, 0)
33 if a_top < b_bottom and a_top > b_top
34 return Vector2(0, overlap_y)
35 else if a_bottom > b_top and a_bottom < b_bottom
36 return Vector2(0, -overlap_y)
40 struct World(player:@Player, goal:@Box, boxes:@[@Box], dt_accum=Num32(0.0), won=no)
41 DT := (Num32(1.)/Num32(60.))
42 STIFFNESS := Num32(0.3)
44 func update(w:@World, dt:Num32)
48 w.dt_accum -= World.DT
50 func update_once(w:@World)
53 if solve_overlap(w.player.pos, Player.SIZE, w.goal.pos, w.goal.size) != Vector2(0,0)
56 # Resolve player overlapping with any boxes:
59 w.player.pos += World.STIFFNESS * solve_overlap(w.player.pos, Player.SIZE, b.pos, b.size)
68 DrawText(CString("WINNER"), GetScreenWidth()/Int32(2)-Int32(48*3), GetScreenHeight()/Int32(2)-Int32(24), 48, Color(0,0,0))
70 func load_map(w:@World, map:Text)
72 map = map.translate({"[]":"#", "@ ":"@", " ":" "})
74 box_size := Vector2(50., 50.)
75 for y,line in map.lines()
76 for x,cell in line.split()
78 pos := Vector2((Num32(x)-1) * box_size.x, (Num32(y)-1) * box_size.y)
79 box := @Box(pos, size=box_size, color=Color(0x80,0x80,0x80))
82 pos := Vector2((Num32(x)-1) * box_size.x, (Num32(y)-1) * box_size.y)
83 pos += box_size/Num32(2) - Player.SIZE/Num32(2)
84 w.player = @Player(pos,pos)
86 pos := Vector2((Num32(x)-1) * box_size.x, (Num32(y)-1) * box_size.y)