Ir al contenido

Your first script

Esta página aún no está disponible en tu idioma.

Coins are zones the server places in the level. The first player to touch a coin gets a point; the coin comes back 10 seconds later. Each player sees their own score in the corner and hears a sound when they get a coin.

  1. Declare what the scripts use in manifest.json:

    manifest.json
    {
    "server": { "entry": "scripts/server/main.js" },
    "client": { "entry": "scripts/client/main.js" },
    "capabilities": ["players", "net", "nativeUI", "world", "level"]
    }

    (Only the new lines are shown; keep the rest of your manifest.)

  2. The server keeps the score. Create scripts/server/main.js:

    scripts/server/main.js
    // Coins: x, y = the bottom-left corner, in level units (30 = one block; the ground row is y = 90..120).
    const COINS = [
    { id: "coin1", x: 300, y: 90 },
    { id: "coin2", x: 600, y: 150 },
    { id: "coin3", x: 900, y: 90 },
    ];
    const taken = new Set();
    const score = {};
    for (const c of COINS) gdmp.zones.add({ id: c.id, x: c.x, y: c.y, width: 30, height: 30 });
    gdmp.zones.onEnter(e => {
    if (!e.zone.startsWith("coin") || taken.has(e.zone)) return;
    taken.add(e.zone);
    score[e.playerId] = (score[e.playerId] || 0) + 1;
    gdmp.state.set("score:" + e.playerId, score[e.playerId]); // every client sees it
    gdmp.net.send(e.playerId, "coin", { zone: e.zone }); // tell the player who took it
    gdmp.time.after(10000, () => taken.delete(e.zone)); // the coin comes back
    });
    gdmp.players.onLeave(p => {
    delete score[p.id];
    gdmp.state.delete("score:" + p.id);
    });
  3. Each player’s screen shows their score. Create scripts/client/main.js:

    scripts/client/main.js
    const panel = gdmp.ui.createWindow({ title: "", x: 20, y: 20, width: 220, height: 40, transparent: true });
    const label = panel.addLabel({ text: "Coins: 0", x: 0, y: 0, width: 220, height: 40, font: 1, size: 0.8 });
    function myId() {
    const me = gdmp.players.list().find(p => p.isLocal);
    return me ? me.id : null;
    }
    gdmp.state.onChanged(e => {
    if (e.key === "score:" + myId()) label.setText("Coins: " + (e.deleted ? 0 : e.value));
    });
    gdmp.net.onMessage(m => {
    if (m.channel === "coin") gdmp.audio.play({ gd: "achievement_01" });
    });
  4. Test it: in Build, press ESC → Test (save and play).

Call Where What it did
gdmp.zones.add / onEnter server coins as rectangles players enter
gdmp.state.set server the score, shared with every client
gdmp.net.send server a private “you got a coin” to one player
gdmp.time.after server the coin comes back later
gdmp.ui.createWindow client a label in GD’s own font
gdmp.state.onChanged client update the label when the score changes
gdmp.audio.play client one of GD’s own sounds