KO

← Collision

튜토리얼 — Collision

1. 확장 설치

프로젝트에서 게임에 확장을 추가하세요:

bin/jumphp extension:add <game> jumphp/collision

엔진이 시작할 때 스스로 찾으므로 연결할 것이 없습니다.

2. A circle pushed out of a wall and a hexagon, a ray to the cursor

src/Extensions/에 씬을 만들고(또는 extension:add로 복사) 아래 코드를 읽으세요. 주석에 누를 키가 적혀 있습니다.

<?php

namespace App\Extensions\Collision;

use JumPHP\Collision\Box;
use JumPHP\Collision\Circle;
use JumPHP\Collision\Collision;
use JumPHP\Collision\CollisionWorld;
use JumPHP\Collision\Polygon;
use JumPHP\Renderer\Renderer;
use JumPHP\Scene\AbstractScene;

/**
 * Sample of jumphp/collision: a circle (arrows) is pushed out of a wall and a hexagon, and a ray from it to the mouse stops where it meets them.
 * JUMPHP_SCENE='App\Extensions\Collision\CollisionSample' bin/jumphp run <game>
 */
final class CollisionSample extends AbstractScene
{
    public const LABEL = 'A circle pushed out of a wall and a hexagon, a ray to the cursor';

    private Circle $player;

    public function __construct(private CollisionWorld $world)
    {
    }

    public function enter(array $params = []): void
    {
        $this->world->reset(48);
        $this->world->add('wall', new Box($this->width() / 2, 20, 16, $this->height() - 40));
        $this->world->add('hexagon', Polygon::regular($this->width() * 0.25, 60, 26, 6, 15));
        $this->player = new Circle(30, $this->height() - 30, 10);
        $this->world->add('player', $this->player);
    }

    public function update(float $dt): void
    {
        $this->player->translate($this->actions()->axis('left', 'right') * 90 * $dt, $this->actions()->axis('up', 'down') * 90 * $dt);
        $this->world->update('player');
        foreach ($this->world->collisions() as [$a, $b, $hit]) {
            if ($a === 'player' || $b === 'player') {
                [$dx, $dy] = $a === 'player' ? $hit->pushOutOfFirst() : $hit->pushOutOfSecond();
                $this->player->translate($dx, $dy);
                $this->world->update('player');
            }
        }
    }

    public function render(Renderer $r): void
    {
        $r->clear([14, 16, 30]);
        foreach ($this->world->all() as $id => $shape) {
            if ($shape instanceof Circle) {
                $r->fillCircle((int)$shape->x, (int)$shape->y, (int)$shape->radius, '#5fd0ff');
            } else {
                $points = $shape instanceof Box ? $shape->toPolygon()->points : ($shape instanceof Polygon ? $shape->points : []);
                foreach ($points as $i => $p) {
                    $q = $points[($i + 1) % count($points)];
                    $r->drawLine((int)$p[0], (int)$p[1], (int)$q[0], (int)$q[1], '#c8a0ff');
                }
            }
        }
        $mouse = $this->engine->input->getMouse();
        $others = array_filter($this->world->all(), fn ($id) => $id !== 'player', ARRAY_FILTER_USE_KEY);
        $hit = Collision::raycast($this->player->x, $this->player->y, $mouse->x - $this->player->x, $mouse->y - $this->player->y, $others);
        $r->drawLine((int)$this->player->x, (int)$this->player->y, (int)($hit->x ?? $mouse->x), (int)($hit->y ?? $mouse->y), $hit ? '#ffcc00' : '#557755');
    }
}

실행:

JUMPHP_SCENE='App\Extensions\Collision\CollisionSample' bin/jumphp run <game>

3. Sixty circles bouncing and pushed apart: the world and its spatial hash

src/Extensions/에 씬을 만들고(또는 extension:add로 복사) 아래 코드를 읽으세요. 주석에 누를 키가 적혀 있습니다.

<?php

namespace App\Extensions\Collision;

use JumPHP\Collision\Circle;
use JumPHP\Collision\CollisionWorld;
use JumPHP\Renderer\Renderer;
use JumPHP\Scene\AbstractScene;

/**
 * Sample of jumphp/collision: sixty circles in a box, found in contact by the world's spatial hash (not 1800 pairs), pushed apart by the
 * minimum translation; red while touching. Click adds one under the cursor.
 * JUMPHP_SCENE='App\Extensions\Collision\WorldSample' bin/jumphp run <game>
 */
final class WorldSample extends AbstractScene
{
    public const LABEL = 'Sixty circles bouncing and pushed apart: the world and its spatial hash';

    /** @var array<int, array{0: float, 1: float}> id => velocity */
    private array $speed = [];

    private int $contacts = 0;

    public function __construct(private CollisionWorld $world)
    {
    }

    public function enter(array $params = []): void
    {
        $this->world->reset(24);
        $this->speed = [];
        for ($i = 0; $i < 60; $i++) {
            $this->spawn(20 + ($i * 37) % ($this->width() - 40), 20 + ($i * 53) % ($this->height() - 40), $i);
        }
    }

    private function spawn(float $x, float $y, int $seed): void
    {
        $id = count($this->speed);
        $this->world->add($id, new Circle($x, $y, 6 + $seed % 4));
        $a = $seed * 2.399;
        $this->speed[$id] = [cos($a) * (30 + $seed % 40), sin($a) * (30 + $seed % 40)];
    }

    public function update(float $dt): void
    {
        $mouse = $this->engine->input->getMouse();
        if ($mouse->isPressed(1) && count($this->speed) < 200) {
            $this->spawn($mouse->x, $mouse->y, count($this->speed));
        }
        foreach ($this->speed as $id => [$vx, $vy]) {
            $c = $this->world->get($id);
            [$x, $y] = $c->center();
            $x += $vx * $dt;
            $y += $vy * $dt;
            if ($x < $c->radius || $x > $this->width() - $c->radius) {
                $vx = -$vx;
                $x = max($c->radius, min($this->width() - $c->radius, $x));
            }
            if ($y < $c->radius || $y > $this->height() - $c->radius) {
                $vy = -$vy;
                $y = max($c->radius, min($this->height() - $c->radius, $y));
            }
            $this->speed[$id] = [$vx, $vy];
            $c->moveTo($x, $y);
            $this->world->update($id);
        }
        $pairs = $this->world->collisions();
        $this->contacts = count($pairs);
        foreach ($pairs as [$a, $b, $hit]) {
            $first = $this->world->get($a);
            $second = $this->world->get($b);
            $first->translate(-$hit->nx * $hit->depth / 2, -$hit->ny * $hit->depth / 2);
            $second->translate($hit->nx * $hit->depth / 2, $hit->ny * $hit->depth / 2);
            $this->world->update($a);
            $this->world->update($b);
        }
    }

    public function render(Renderer $r): void
    {
        $r->clear([16, 18, 34]);
        $touching = [];
        foreach ($this->world->collisions() as [$a, $b]) {
            $touching[$a] = $touching[$b] = true;
        }
        foreach ($this->world->all() as $id => $shape) {
            [$x, $y] = $shape->center();
            $r->fillCircle((int)$x, (int)$y, (int)$shape->radius, isset($touching[$id]) ? '#ff5050' : '#4c8bf5');
        }
        $this->font()->draw($r, count($this->speed) . ' SHAPES  ' . $this->contacts . ' CONTACTS  CLICK: ADD ONE', 4, $this->height() - 10, 1, [230, 230, 240]);
    }
}

실행:

JUMPHP_SCENE='App\Extensions\Collision\WorldSample' bin/jumphp run <game>

4. 확인

bin/jumphp test <game>
bin/jumphp shot <game>

Collision 문서