Skip to content

Commit

Permalink
improve polygon example
Browse files Browse the repository at this point in the history
  • Loading branch information
slmjkdbtl committed Oct 26, 2023
1 parent 2ce89e4 commit 42f1060
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 27 deletions.
83 changes: 58 additions & 25 deletions examples/polygon.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,72 @@
kaboom()

// Add a thing that follows the mouse
var CURSOR = "cursor"
setBackground(0, 0, 0)

const cursor = add([
circle(10),
area(),
pos(),
z(100),
CURSOR,
add([
text("Drag corners of the polygon"),
pos(20, 20),
])

cursor.onMouseMove(pos => {
cursor.pos = pos
})

// Make a weird shape
const poly = add([
polygon([
vec2(0, 0),
vec2(200, 0),
vec2(50, 300),
vec2(0, 100),
]),
pos(80, 120),
outline(4),
vec2(0, -160),
vec2(160, 0),
vec2(80, 80),
vec2(-60, 120),
vec2(-120, 0),
], {
colors: [
rgb(128, 255, 128),
rgb(255, 128, 128),
rgb(128, 128, 255),
rgb(255, 128, 128),
rgb(128, 128, 128),
],
}),
pos(300, 300),
area(),
color(rgb(255, 0, 0)),
color(),
])

// Change the color when the cursor object collides with the polygon
poly.onCollide(CURSOR, () => {
poly.color = rgb(0, 0, 255)
let dragging = null
let hovering = null

poly.onDraw(() => {
if (hovering !== null) {
drawCircle({
pos: poly.pts[hovering],
radius: 16,
})
}
})

onMousePress(() => {
dragging = hovering
})

onMouseRelease(() => {
dragging = null
})

onMouseMove(() => {
hovering = null
const mp = mousePos().sub(poly.pos)
for (let i = 0; i < poly.pts.length; i++) {
if (mp.dist(poly.pts[i]) < 16) {
hovering = i
break
}
}
if (dragging !== null) {
poly.pts[dragging] = mousePos().sub(poly.pos)
}
})

poly.onHover(() => {
poly.color = rgb(200, 200, 255)
})

poly.onCollideEnd(CURSOR, obj => {
poly.color = rgb(255, 0, 0)
poly.onHoverEnd(() => {
poly.color = rgb(255, 255, 255)
})
4 changes: 2 additions & 2 deletions src/kaboom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ const SPRITE_ATLAS_HEIGHT = 2048
// 0.1 pixel padding to texture coordinates to prevent artifact
const UV_PAD = 0.1
const DEF_HASH_GRID_SIZE = 64
const DEF_FONT_FILTER = "nearest"
const DEF_FONT_FILTER = "linear"

const LOG_MAX = 8
const LOG_TIME = 4
Expand Down Expand Up @@ -1976,7 +1976,7 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
const verts = opt.pts.map((pt, i) => ({
pos: new Vec2(pt.x, pt.y),
uv: new Vec2(0, 0),
color: opt.colors ? (opt.colors[i] ?? color) : color,
color: opt.colors ? (opt.colors[i] ? opt.colors[i].mult(color) : color) : color,
opacity: opt.opacity ?? 1,
}))

Expand Down

0 comments on commit 42f1060

Please sign in to comment.