Trying to make a triangle that can rotate and move by applying the same transformations to all three points

358 Views Asked by At

I am trying to make boids simulation and for that I need triangles that move and rotate.

I made a Triangle and a Boid struct.

struct Triangle
{
    olc::vf2d p1 = { 0.0f,   0.0f };
    olc::vf2d p2 = { -5.0f,  10.0f };
    olc::vf2d p3 = { 5.0f,  10.0f };
};

struct Boid
{
    Boid()
    {
    }

    Boid(olc::vf2d _position, float _angle) : position(_position), angle(_angle)
    {
    };

    olc::vf2d position = { 0.0f, 0.0f };
    float angle = 0.0f;
};

Then I made a boid and a triangle by instantiating the above two structs.

Boid boid = Boid(olc::vf2d(300, 150), 0.0f)
Triangle triangle;

Now here is the bit that does not work.

            //Everything here is in a while loop

            boid.angle += 0.005f;
            //rotation and offset
            float x1 = triangle.p1.x * cosf(boid.angle) + boid.position.x;
            float y1 = triangle.p1.y * sinf(boid.angle) + boid.position.y;

            float x2 = triangle.p2.x * cosf(boid.angle) + boid.position.x;
            float y2 = triangle.p2.y * sinf(boid.angle) + boid.position.y;
                       
            float x3 = triangle.p3.x * cosf(boid.angle) + boid.position.x;
            float y3 = triangle.p3.y * sinf(boid.angle) + boid.position.y;

            FillTriangle(
                (int)x1, (int)y1,
                (int)x2, (int)y2,
                (int)x3, (int)y3,
                olc::BLUE
                )

Here what I am attempting to do is to offset and rotate each point by same angle. I was hoping by doing this, the three points would still maintain the triangle structure(since they are moving and rotating exactly the same) but It doesn't and it rotates really weirdly. How can I move and rotate the triangle properly? It would also be nice if someone explained why what I am doing does not work. I am new at this stuff.

1

There are 1 best solutions below

0
On BEST ANSWER

That does not look like a proper rotation to me. A quick search for a 2D rotation matrix yields something more like this:

x' = cos(theta) * x - sin(theta) * y
y' = sin(theta) * x + cos(theta) * y

i.e.

float x1 = triangle.p1.x * cosf(boid.angle) - triangle.p1.y * sinf(boid.angle) + boid.position.x;
float y1 = triangle.p1.x * sinf(boid.angle) + triangle.p1.y * cosf(boid.angle) + boid.position.y;

And keep in mind that this rotation will of course rotate each point about the origin. Your triangle is not centered at the origin; rather, one of the triangle's three points lies exactly on the origin, so your triangle will simply rotate around that point. This can be fixed by centering your triangle on the origin.