swf2ass/src/Vector2.php

91 lines
2.3 KiB
PHP

<?php
namespace swf2ass;
class Vector2 {
/** @var numeric */
public $x;
/** @var numeric */
public $y;
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
/**
* @return numeric[]
*/
public function toArray() : array{
return [$this->x, $this->y];
}
public function equals(Vector2 $b, $epsilon = Constants::EPSILON): bool {
return ($b->x === $this->x or abs($b->x - $this->x) <= $epsilon) and ($b->y === $this->y or abs($b->y - $this->y) <= $epsilon);
}
public function distance(Vector2 $b): float {
return sqrt(pow($this->x - $b->x, 2) + pow($this->y - $b->y, 2));
}
public function distanceSquare(Vector2 $b): float {
return pow($this->x - $b->x, 2) + pow($this->y - $b->y, 2);
}
public function invert(): Vector2 {
return new Vector2($this->y, $this->x);
}
public function add(Vector2 $b): Vector2 {
return new Vector2($this->x + $b->x, $this->y + $b->y);
}
public function sub(Vector2 $b): Vector2 {
return new Vector2($this->x - $b->x, $this->y - $b->y);
}
public function abs(): Vector2 {
return new Vector2(abs($this->x), abs($this->y));
}
/**
* @param Vector2 $b
* @return numeric
*/
public function dot(Vector2 $b) {
return $this->x * $b->x + $this->y * $b->y;
}
public function squaredLength() : float {
return $this->x * $this->x + $this->y * $this->y;
}
public function normalize() : Vector2{
$len = $this->squaredLength();
if($len > 0){
return $this->divide(sqrt($len));
}
return new Vector2(0, 0);
}
public function vectorMultiply(Vector2 $b): Vector2 {
return new Vector2($this->x * $b->x, $this->y * $b->y);
}
public function multiply($size): Vector2 {
return new Vector2($this->x * $size, $this->y * $size);
}
public function divide($size): Vector2 {
return new Vector2($this->x / $size, $this->y / $size);
}
public function toPixel($twipSize = Constants::TWIP_SIZE): Vector2 {
return $this->divide($twipSize);
}
public function __toString() {
return "Vector2({$this->x}, {$this->y})";
}
}