Files
zombie-game/app/Game/Vector2.php
T
2026-09-07 20:37:40 +02:00

92 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Game;
final class Vector2
{
public function __construct(
public float $x,
public float $y,
) {}
public static function zero(): self
{
return new self(0.0, 0.0);
}
public function mulS(float $scalar): self
{
return new self($this->x * $scalar, $this->y * $scalar);
}
public function mulV(self $v): self
{
return new self($this->x * $v->x, $this->y * $v->y);
}
public function divS(float $scalar): self
{
return new self($this->x / $scalar, $this->y / $scalar);
}
public function addS(float $scalar): self
{
return new self($this->x + $scalar, $this->y + $scalar);
}
public function addV(self $v): self
{
return new self($this->x + $v->x, $this->y + $v->y);
}
public function subS(float $scalar): self
{
return new self($this->x - $scalar, $this->y - $scalar);
}
public function subV(self $v): self
{
return new self($this->x - $v->x, $this->y - $v->y);
}
public function dot(self $v): float
{
return $this->x * $v->x + $this->y * $v->y;
}
public function abs(): self
{
return new self(abs($this->x), abs($this->y));
}
public function length(): float
{
return sqrt($this->dot($this));
}
public function lengthSquared(): float
{
return $this->dot($this);
}
public function normalize(): self
{
$length = $this->length();
if ($length < 1.0e-9) {
return new self(0.0, 0.0);
}
return new self($this->x / $length, $this->y / $length);
}
public function rotate(float $angle): self
{
$cos = cos($angle);
$sin = sin($angle);
return new self($this->x * $cos - $this->y * $sin, $this->x * $sin + $this->y * $cos);
}
}