HIDE NAV

RoboCode: Aiming Basics

The following RoboCode basic Robot demonstrates how to reliably point the turret at another scanned robot.

HowToAimForDummies.java


package ceccs;

import robocode.Robot;
import robocode.ScannedRobotEvent;

import java.awt.*;

public class HowToAimForDummies extends Robot {
    @Override
    public void run() {
	// change your colors if you wish
	setColors(Color.cyan, Color.darkGray,Color.white);

        while(true){
            turnRadarLeft(10000);
        }
    }

    @Override
    public void onScannedRobot(ScannedRobotEvent event) {
        stop();
        double scanBearing = event.getBearing();
        double gunBearing = getGunHeading() - getHeading();
	double amountToTurnGunToScan = scanBearing - gunBearing;

	/** 
	  The amount to turn will point the gun at the target, 
	  but may not be the smallest rotation. 
	  The below two loops will ensure the smallest roatation is made. 
	*/

        while(amountToTurnGunToScan > 180) {
            amountToTurnGunToScan = amountToTurnGunToScan - 360;
        }
        while(amountToTurnGunToScan < -180) {
            amountToTurnGunToScan = amountToTurnGunToScan + 360;
	}
	// Optional printout for verification
	System.out.println("I need to turn gun " + amountToTurnGunToScan);
        turnGunRight(amountToTurnGunToScan);
        return;

    }
}