• Create Account

We're offering banner ads on our site from just \$5!

### #ActualP0jahn

Posted 15 January 2013 - 12:11 PM

I am more interested in your approach. My way was just an overkill.
So this is what I came up with.

public static double getAngle(float x1, float y1, float x2, float y2)
{
float deltaX = x2 - x1;
float deltaY = y2 - y1;

return Math.atan2(deltaY, deltaX) * 180 / Math.PI;
}

public static float rotateTowardsPoint(float x, float y, float targetX, float targetY, float speed)
{
Point2D.Float normalized = normalize(x, y, targetX, targetY);
double angle = getAngle(x, y, normalized.x, normalized.y);

return (float) clamp(angle, -speed, speed);
}

public static double clamp (double i, double low, double high)
{
return java.lang.Math.max (java.lang.Math.min (i, high), low);
}

public static Point2D.Float normalize(float x1, float y1, float x2, float y2)
{
float dx = x1 - x2;
float dy = y1 - y2;
double length = Math.sqrt( dx*dx + dy*dy );
dx /= length;
dy /= length;

return new Point2D.Float(dx,dy);
}

The results ingame, is that the unit that is suppose to rotate, rotates, but just to the same angle every frame. And the rotation is not even pointing at the target.

### #1P0jahn

Posted 15 January 2013 - 12:10 PM

I am more interested in your approach. My way was just an overkill.

So this is what I came up with.

public static float rotateTowardsPoint(float x, float y, float targetX, float targetY, float speed)
{
Point2D.Float normalized = normalize(x, y, targetX, targetY);
double angle = getAngle(x, y, normalized.x, normalized.y);

return (float) clamp(angle, -speed, speed);
}

public static double clamp (double i, double low, double high)
{
return java.lang.Math.max (java.lang.Math.min (i, high), low);
}


public static double getAngle(float x1, float y1, float x2, float y2)
{
float deltaX = x2 - x1;
float deltaY = y2 - y1;

return Math.atan2(deltaY, deltaX) * 180 / Math.PI;
}

public static Point2D.Float normalize(float x1, float y1, float x2, float y2) { float dx = x1 - x2; float dy = y1 - y2; double length = Math.sqrt( dx*dx + dy*dy ); dx /= length; dy /= length; return new Point2D.Float(dx,dy); }

The results ingame, is that the unit that is suppose to rotate, rotates, but just to the same angle every frame. And the rotation is not even pointing at the target.

PARTNERS