- Home /
The question is answered, right answer was accepted
Rotate a point around another point?
I have groups of soldiers which move together in formation. Right now in rows and columns, and they form square-like formations. However, whenever I set the angle to anything other than 0 in the following algorithm, they clump and don't form up properly. What is wrong with my logic?
int dimx = chunkFormationDimensions[ i ].Value.x;
int dimy = chunkFormationDimensions[ i ].Value.y;
float centerx = chunkFormationPosition[ i ].Value.x;
float centery = chunkFormationPosition[ i ].Value.y;
float spacex = chunkFormationSpacing[ i ].Value.x;
float spacey = chunkFormationSpacing[ i ].Value.y;
float angle = math.radians( chunkFormationRotation[ i ].Value ); // chunkFormationRotation[ i ].Value; //
for ( int j = 0; j < unitBuffer.Length; j++ )
{
Entity entity = unitBuffer[ j ].Entity;
int col = j % dimx;
int row = j / dimx;
float unitx = centerx - ( dimx * spacex ) / 2 + ( col * spacex );
float unity = centery - ( dimy * spacey ) / 2 + ( row * spacey );
unitx = math.cos( angle ) * ( unitx - centerx ) - math.sin( angle ) * ( unity - centery ) + centerx;
unity = math.sin( angle ) * ( unitx - centerx ) + math.cos( angle ) * ( unity - centery ) + centery;
unitFormationPositionFromEntity[ entity ] = new UnitFormationPosition { Value = new float2( unitx , unity ) };
}
Answer by Bunny83 · Apr 19, 2020 at 03:55 AM
I haven't checked all of your code but I do see a major mistake. You're modifying "unitx" before you calculate "unity". Therefore your "unity" calculation uses the wrong unitx value.
What you can also see immediately that you can simplify your unitx and y calculation before your rotation. You subtract the row / col indices from centerx / y and before applying the rotation you subtract centerx / y. Therefore centerx and y cancel:
float s = math.sin( angle );
float c = math.cos( angle );
// [ ... ]
float unitx = spacex * (col - dimx * 0.5f);
float unity = spacey * (row - dimy * 0.5f);
float newUnitx = c * unitx - s * unity + centerx;
float newUnity = s * unitx + c * unity + centery;
As you can see it becomes much simpler when you remove centerx and y. I also stored the sine and cosine into seperate variables since they are always the same for the same angle. Therefore they can be calculated once before the loops.
Thank you! I completely missed that.. I gotta slow down lol
Answer by jmailloux11 · Apr 18, 2020 at 05:46 PM
transform.RotateAround(other gameobject's transform)
is a much simpler way to do it.
Follow this Question
Related Questions
3D Video within Scene 1 Answer
New Input system mouse returns wrong values 0 Answers
Looking at a target in 2D 0 Answers
What's a more efficient way to sort an array into multiple groups? 1 Answer
2D Animation does not start 1 Answer