Created
November 11, 2022 21:43
-
-
Save jlavelle/66039d3fad7ee8eafb671b45e41693f6 to your computer and use it in GitHub Desktop.
A p5.js sketch that demonstrates how to detect which tiles are covered by a viewport.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const width = 800 | |
const height = 800 | |
const rows = 20 | |
const cols = 20 | |
const rowSize = height / rows | |
const colSize = width / cols | |
const vWidth = 200 | |
const vHeight = 200 | |
function setup() { | |
createCanvas(width, height) | |
} | |
function draw() { | |
background(240, 240, 240) | |
translate(-0.5, -0.5) | |
strokeWeight(1) | |
border() | |
grid() | |
cover(mouseX, mouseY) | |
viewport(mouseX, mouseY) | |
} | |
function viewport(x, y) { | |
push() | |
noFill() | |
stroke(200, 0, 0) | |
rect(x, y, vWidth, vHeight) | |
pop() | |
} | |
function border() { | |
push() | |
translate(0.5, 0.5) | |
line(0, 0, width, 0) | |
line(0, 0, 0, height) | |
line(0, height, width, height) | |
line(width, 0, width, height) | |
pop() | |
} | |
function grid() { | |
for (let x = 0; x < cols; ++x) { | |
for (let y = 0; y < rows; ++y) { | |
line(0, y * rowSize, width, y * rowSize) | |
line(x * colSize, 0, x * colSize, height) | |
} | |
} | |
} | |
function cover(x, y) { | |
push() | |
fill(0, 100, 0, 30) | |
const {lower, upper} = coveredTiles(x, y) | |
for (let col = lower.x; col < upper.x; ++col) { | |
for (let row = lower.y; row < upper.y; ++row) { | |
rect(col * colSize, row * rowSize, colSize, rowSize) | |
} | |
} | |
pop() | |
} | |
function coveredTiles(x, y) { | |
const csx = Math.floor(x / colSize) | |
const csy = Math.floor(y / rowSize) | |
const cex = Math.ceil((x + vWidth) / colSize) | |
const cey = Math.ceil((y + vHeight) / rowSize) | |
return { lower: {x: csx, y: csy }, upper: {x: cex, y: cey} } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment