A player has an x, a y, a color, some health — lots of values that belong together. An object bundles them into one thing, with a name for each value.
1. Group values into an object
Write name: value pairs (called properties) inside curly braces, and read them with a dot:
let player = { x: 64, y: 64, color: 12 };
function draw() {
cls(1);
circfill(player.x, player.y, 6, player.color);
}Instead of three loose variables, everything about the player travels together in player.
2. Read and change properties
A property works like any variable — read it, or assign a new value with =:
let player = { x: 64, y: 64 };
function update() {
if (key('ArrowRight')) {
player.x += 2;
}
if (key('ArrowLeft')) {
player.x -= 2;
}
}
function draw() {
cls(1);
circfill(player.x, player.y, 6, 12);
}3. A list of objects
The real power: an array of objects — the standard way to hold many game things that each have their own values. Here every star is an object with its own x and y:
let stars = [];
function update() {
if (stars.length < 40) {
stars.push({ x: rnd(128), y: rnd(128) });
}
}
function draw() {
cls(0);
for (let i = 0; i < stars.length; i++) {
pset(stars[i].x, stars[i].y, 7);
}
}stars[i].x reads the x of the i-th star. This pattern — a list of objects you loop over — is how you’ll manage bullets, enemies, coins, and particles.
Try it: give each star a color and use it. Add a dy to make them fall: in update, stars[i].y += stars[i].dy.
What you learned
- An object groups related values as
name: valueproperties in{ … }. - Read and change a property with a dot:
player.x,player.x += 2. - An array of objects holds many things that each carry their own values.
- Loop over them with
list[i].property— the backbone of bullets, enemies, and more.