简体   繁体   中英

C++ to PHP Translation

I'm trying to understand the answer (copy/pasted below) that is laid out here: https://stackoverflow.com/a/3838294/1541165

The problem is that it's in C++ and I want to apply the described solution in PHP.

Can someone help with just a bit of the translation? Like what would Ax - Bx look like in PHP?

first step; move the origin point.

x' = Ax - Bx y' = Ay - By

second step, perform rotation

x'' = x' * cos(C) - y' * sin(C) = (Ax-Bx) * cos(C) - (Ay-By) * sin(C)

y'' = y' * cos(C) + x' * sin(C) = (Ay-By) * cos(C) + (Ax-Bx) * sin(C)

third and final step, move back the coordinate frame

x''' = x'' + Bx = (Ax-Bx) * cos(C) - (Ay-By) * sin(C) + Bx

y''' = y'' + By = (Ay-By) * cos(C) + (Ax-Bx) * sin(C) + By

And presto! we have our rotation formula. I'll give it to you without all those calculations:

Rotating a point A around point B by angle C

Ax' = (Ax-Bx) * cos(C) - (Ay-By) * sin(C) + Bx

Ay' = (Ay-By) * cos(C) + (Ax-Bx) * sin(C) + By

A and B are just C++ structures containing two floats, to achieve this in PHP, you'd make a simple "Point" class:

class Point {
    public $X;
    public $Y;
    public function __construct($x = 0, $y = 0) {
        $this->X = $x;
        $this->Y = $y;
    }
}

Once you have this class, you can create points A and B like so:

$A = new Point(0, 1);
$B = new Point(1, 0);

With these two points, and a rotation angle $C in radians:

$C = 3.14;

// The long way
$x1 = $A->X - $B->X;
$y1 = $A->Y - $B->Y;

$sinC = sin($C);
$cosC = cos($C);

$x2 = $x1 * $cosC - $y1 * $sinC;
$y2 = $y1 * $cosC + $x1 * $sinC;

$resultX = $x2 + $B->X;
$resultY = $y2 + $B->Y;

// The quick way
$sinC = sin($C);
$cosC = cos($C);

$diff = new Point($A->X - $B->X, $A->Y - $B->Y);
$result = new Point($diff->X * $cosC - $diff->Y * $sinC + $B->X, 
                    $diff->Y * $cosC + $diff->X * $sinC + $B->Y);

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM