From 42f1060662f270e75cbb37ab2ecf6201860b975b Mon Sep 17 00:00:00 2001 From: tga Date: Thu, 26 Oct 2023 14:22:26 +0800 Subject: [PATCH] improve polygon example --- examples/polygon.js | 83 +++++++++++++++++++++++++++++++-------------- src/kaboom.ts | 4 +-- 2 files changed, 60 insertions(+), 27 deletions(-) diff --git a/examples/polygon.js b/examples/polygon.js index ca1fcc50b..eb1dc167f 100644 --- a/examples/polygon.js +++ b/examples/polygon.js @@ -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) }) diff --git a/src/kaboom.ts b/src/kaboom.ts index 8d3a62e92..c6e0be83b 100644 --- a/src/kaboom.ts +++ b/src/kaboom.ts @@ -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 @@ -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, }))