I have a processing script for a 2-dimensional Minecraft clone. I am currently stuck at placing blocks, as I need them to be snapped to a grid of size block_size
. Here is the code:
final float block_size = 8;
final float ground_level = 8;
final float sky_level = 256;
final float x_min = 0;
final float x_max = 256;
class Player {
float x;
float y;
boolean facing;
Player(float spawn_x, float spawn_y) {
x = spawn_x;
y = spawn_y;
}
void move() {
if (keyPressed) {
if (key == CODED) {
switch(key) {
case 'a':
x--;
facing = false;
break;
case 'd':
x++;
facing = true;
break;
case ' ':
y--;
}
} else {
switch(keyCode) {
case LEFT:
x--;
facing = false;
break;
case RIGHT:
x++;
facing = true;
break;
case UP:
y--;
}
}
}
}
void physics() {
if (y < ground_level) {
y++;
}
x = constrain(x, x_min, x_max);
y = constrain(y, ground_level, sky_level);
}
void place_block() {
}
void break_block() {
}
}
class Block {
Block(float x_, float y_) {
}
void display() {
}
}
Player player = new Player(2, (x_max - x_min) / 2);
ArrayList<Block> blocks = new ArrayList<Block>();
The problem is in the Block(float x_, float y_)
constructor. I need to make sure that x
is never above x_
, as close as possible to x_
, and also a multiple of block_size
. Same for y
.
I tried x = floor(x_ / block_size) * block_size;
, but it didn't work. Does anyone have a line or two of code that I could use?