Hello.
I had no problems with sprite rotation at the specified point … until I decided to make it smooth.
In the end, I got this result: Imgut gif
The sprite makes a full circular turn, and I don’t know how to solve it. Tell me how to solve it, please.
Here is my example:
float AngleToTarget(float x1, float y1, float x2, float y2, float radian)
{
var dX = x1 - x2;
var dY = y1 - y2;
return (float)(Math.Atan2(dY, dX) - radian);
}
void Update()
{
Vector2 mp = Exts.GetMousePosOnMap();
Vector2 cp = CenterPos;
var target = AngleToTarget(cp.X, cp.Y, mp.X, mp.Y, DEMath.ANGLE_IN_RADIAN_90);
Angle += (target - Angle) / 8f; // smooth
}
This will work by choosing always the smaller angle of the 2 possible.
Also never forget to multiply by deltatime so it’s framerate-independent.
And a speed-paramter is handy for tweaking the turning-speed
float Speed = 10f;
void Update()
{
Vector2 mp = Exts.GetMousePosOnMap();
Vector2 cp = CenterPos;
var target = AngleToTarget(cp.X, cp.Y, mp.X, mp.Y, DEMath.ANGLE_IN_RADIAN_90);
var delta = target - Angle;
delta += (delta > MathHelper.Pi) ? -MathHelper.TwoPi : (delta < -MathHelper.Pi) ? MathHelper.TwoPi : 0;
Angle += delta * Speed * (float)gameTime.ElapsedGameTime.TotalSeconds;
}
1 Like
nkast
July 3, 2018, 2:55pm
3
2 Likes
Thank! I got this solution:
public static float SmoothLookTo(float currentAngle, Vector2 center, Vector2 target, float speed)
{
var target = AngleToTarget(center, target);
var delta = target - currentAngle;
delta += (delta > MathHelper.Pi)
? -MathHelper.TwoPi
: (delta < -MathHelper.Pi) ? MathHelper.TwoPi : 0;
currentAngle += delta * speed;
return MathHelper.WrapAngle(currentAngle);
}