/** * When scanning a robot we need to add it to the collection of scanned objects so it can be used * later for updates to the bots movement. */ public void onScannedRobot(ScannedRobotEvent e) { double targetBearing = getHeading() + e.getBearing(); double tmpX = getX() + e.getDistance() * Math.sin(Math.toRadians(targetBearing)); double tmpY = getY() + e.getDistance() * Math.cos(Math.toRadians(targetBearing)); String name = e.getName(); if (name.equals(GOAL_NAME)) { foundGoal = true; } obstacles.put(name, new Enemy(tmpX, tmpY, e.getBearing())); setTurnRadarRight(getRadarTurnRemaining()); }
public void run() { setAllColors(Color.GREEN); setTurnRadarRight(Double.POSITIVE_INFINITY); double robotX, robotY; double robotHeading, angleToGoal, angleToObs; double adjustment; double obsAngle, obsAdjustment; double angleDiff; double speedToGoal, speedFromObs; Enemy temp; obstacles = new HashMap<String, Enemy>(10); while (true) { if (foundGoal) { robotX = getX(); robotY = getY(); goalX = obstacles.get(GOAL_NAME).x; goalY = obstacles.get(GOAL_NAME).y; // Adjust robocode's returned heading so that 0 aligns with the positive x-axis instead of // the positive y-axis. // Also make it so that positive angle indicates a counter clockwise rotation instead of the // clockwise style // returned by robocode. robotHeading = 360 - (getHeading() - 90); angleToGoal = Math.toDegrees(Math.atan2(goalY - robotY, goalX - robotX)); if (angleToGoal < 0) { angleToGoal += 360; } adjustment = angleToGoal - robotHeading; adjustment = normalizeAngle(adjustment); speedToGoal = calcRobotSpeedLinear(robotX, robotY, goalX, goalY); // Calculate how the robot's heading and speed should be affected by objects that it has // located // as it explores the world. Iterator it = obstacles.entrySet().iterator(); while (it.hasNext()) { System.out.println("Iterating through objects."); Map.Entry pairs = (Map.Entry) it.next(); // If the current item in the Iterator isn't the goal. if (!pairs.getKey().equals(GOAL_NAME)) { temp = (Enemy) pairs.getValue(); speedFromObs = calcObjRepulseSpeed(robotX, robotY, temp.x, temp.y); // If the robot is in range of the object to be affected by it's repulsion. if (speedFromObs != 0) { obsAngle = Math.toDegrees(Math.atan2(robotY - temp.y, robotX - temp.x)); if (obsAngle < 0) obsAngle += 360; angleDiff = obsAngle - angleToGoal; angleDiff = normalizeAngle(angleDiff); adjustment += (angleDiff * (speedFromObs / speedToGoal)); speedToGoal -= speedFromObs; } } // Was getting a null pointer exception when using this. The internet lied about its // usefulness. // it.remove(); // avoids a ConcurrentModificationException } adjustment = normalizeAngle(adjustment); setTurnLeft(adjustment); // ahead(speedToGoal); setAhead(speedToGoal); } execute(); } }