Getting started with angles
Angles are important for Radar, Movement, and Targeting.
Contents
Absolute Bearing
Absolute Bearing is the absolute angle from your robot to another robot. You can calculate it in onScannedRobot as
e.getBearing() + getHeading()
The robot's heading is an absolute angle, and the bearing to the scanned robot is a relative angle.
To get the other robot's Absolute Bearing to you, add 180 degrees (Math.PI). To get the perpendicular angle so you can orbit them, add 90 degrees (Math.PI/2). NanoBots typically orbit with Math.cos(e.getBearingRadians()) instead.
Moving to an angle
The easiest way to move your robot at a certain angle is the following:
angle = targetAngle - getHeadingRadians(); setAhead(Math.cos(angle) * bigNumber); setTurnRightRadians(Math.tan(angle));
An alternative to slowly turning your robot with Utils.normalRelativeAngle, this technique reverses movement direction when the robot needs to make a very large turn.
Utils.normalRelativeAngle
Angles are only meaningful in a certain range, so simple arithmetic can cause problems. Luckily, Robocode provides a method to normalize relative angles. This is used very often in targeting to get the gun turn amount:
setTurnGunRight(Utils.normalRelativeAngle(absoluteBearing + targetingOffset - getGunHeading()));
Utils.normalAbsoluteAngle
This method normalizes absolute angles (0 to 360 degrees). It is useful when counting data about all angles around the robot. Cotillion uses it for Multiple Choice Pattern Matching.
Comparing angles
To calculate how far one angle is from another, you can use Math.abs(Utils.normalRelativeAngle(angleA - angleB)).
Relative bins
For Visit Count Stats with relative angles, you need to have a total number of bins and a middle factor index. To convert a relative angle to a bin index, you can normalize the angle to 0-1, multiply by the number of bins and round, then add the middle factor.
statistics[index = ((int)Math.round((angle / MAX_ANGLE) * BINS) + MIDDLE)]++;
To convert an index into an angle, simply invert:
angle = (index - MIDDLE) * MAX_ANGLE / BINS;
Absolute bins
Absolute bins don't need a middle factor index, and the maximum angle is a full circle.
statistics[index = ((int)Math.round((angle / 360) * BINS))]++; angle = (index - MIDDLE) * 360 / BINS;