I'm writing a Transform script for a Monogame project and I'm trying for a few days now to fix the Rotate method of this script, but without success.
Currently, the Parent transform only rotates around itself and also its Children does not translate around the specified Point (the Parent), only around themselves and with a lot of imprecision. When tested in other scenarios, the RotatePoint method is working correctly, but not when used in the Rotate method written below.
public class Tranform
{
public Vector2 Position
{
get { return new Vector2 (x, y); }
set { return x = value.X; y = value.Y; }
}
public float Rotation
{
get { return rotation; }
set { rotation = value; }
}
public void Rotate(float degrees)
{
this.rotation += degrees;
if (rotation >= 360) rotation = 0;
if (rotation <= -360) rotation = 0;
foreach (var child in this.Children)
{
child.Position = RotatePoint(child.Position, this.Position, degrees);
child.Rotate(degrees);
}
}
public override void Update(GameTime time)
{
if (Keyboard.GetState().IsKeyDown(Keys.A))
{
Translate(-1, 0);
Rotate(-1 * (float)time.ElapsedGameTime.TotalMilliseconds);
}
if (Keyboard.GetState().IsKeyDown(Keys.D))
{
Translate(1, 0);
Rotate(1 * (float)time.ElapsedGameTime.TotalMilliseconds);
}
}
public override void Render(SpriteBatch sprite_batch)
{
sprite_batch.Draw(pixel, this.Position, this.Boundaries, Color.White, MathHelper.ToRadians (this.Rotation), this.Origin, 1, SpriteEffects.None, 0);
}
public Vector2 RotatePoint(Vector2 point, Vector2 origin, float degrees)
{
float radians = MathHelper.ToRadians(degrees);
Vector2 rotation_origin = new Vector2(point.X - origin.X, point.Y - origin.Y);
double radius = Math.Sqrt(rotation_origin.X * rotation_origin.X + rotation_origin.Y * rotation_origin.Y);
float x = (float)((radius * Math.Cos(radians)) + origin.X);
float y = (float)((radius * Math.Sin(radians)) + origin.Y);
return new Vector2(x, y);
}
}
I'm creating the objects like this:
var parent = new Tranform();
parent.Position = new Vector2(0, 0);
parent.Scale = new Vector2(100, 100);
parent.Origin = new Vector2(50, 50);
child.SetParent(parent);