0

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 A.x - B.x look like in PHP?

first step; move the origin point.

x' = A.x - B.x y' = A.y - B.y

second step, perform rotation

x'' = x' * cos(C) - y' * sin(C) = (A.x-B.x) * cos(C) - (A.y-B.y) * sin(C)

y'' = y' * cos(C) + x' * sin(C) = (A.y-B.y) * cos(C) + (A.x-B.x) * sin(C)

third and final step, move back the coordinate frame

x''' = x'' + B.x = (A.x-B.x) * cos(C) - (A.y-B.y) * sin(C) + B.x

y''' = y'' + B.y = (A.y-B.y) * cos(C) + (A.x-B.x) * sin(C) + B.y

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

A.x' = (A.x-B.x) * cos(C) - (A.y-B.y) * sin(C) + B.x

A.y' = (A.y-B.y) * cos(C) + (A.x-B.x) * sin(C) + B.y

0

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.