Scaling a triangle up or down given it's vertices and center point

I am writing a program using OpenGL and I am trying to write a function that allows the user to click on a triangle and increase/decrease the size of the triangle by hitting keys on the keyboard. I understand how to handle key presses, but I am having a little trouble with the math.

If I have a triangle's three vertices and center point stored, how can I upscale the triangle? In other words, how can I manipulate the current vertices to make the triangle larger without altering the center point?

This was my first attempt at up-scaling, where v1, v2, and v3 are the vertices of the triangle and A, B, and C are the vertices of the triangle after being scaled up:

//distance from center to v1
double distance = center - v1;
distance = distance * 1.25;
Vector3d A = center + distance;

v1(0) = A(0);
v1(1) = A(1);

// v2
distance = center - center;
distance = distance * 1.25;
Vector3d B = center + distance;

v2(0) = B(0);
v2(1) = B(1);

// v3
distance = center - v3;
distance = distance * 1.25;
Vector3d C = center + distance;

v3(0) = C(0);
v3(1) = C(1);

edit: I am using the Eigen library, so v1(0) means the x-coordinate of vertex v1 and v1(1) means the y-coordinate of vertex v1

1 answer

  • answered 2018-10-11 20:26 Dominik Mokri┼í

    The line

    double distance = center - v1;

    is certainly wrong. Both center and v1 are points. That means that they have two or three components (depending on whether you work in 2D or 3D) and therefore distance cannot be a double (i.e., a scalar) but has to be a vector.

    This is how I would compute A (computation of B and C will be analogous):

    vector3d A;
    for(std::size_t i = 0; i < 3; ++i)
      A(i) = center(i) + 1.25 * (V1(i) - center(i));

    The part V1(i) - center(i) represents the i-th coordinate of the vector (V1 - center). The right hand-side also represents "walking in the same direction from center but 1.25-times as far."

    A few further notes

    • From your sample it is not clear, whether you work in 2D or 3D. On the one hand, you use vector3d, on the other hand you seem to manipulate with the x- and y-coordinates only.
    • I don't understand, why you used v1(0) = A(0); From how I understand your question, A is already the answer.
    • Instead of copy-pasting the essentially identical code three times (once for A, once for B and once for C) it might be useful to turn it into a function that you can call three times.

    Good luck with your task!