Hi,

I've been going over the Gravitational Movement tutorial on RoboWiki however I may have come across an error. Im reluctant to say that it is due to the fact that I may have overlooked something. This is taken directly from the RoboWiki website.

These are the declerations:

static Point2D.Double[] enemyPoints = new Point2D.Double[NUMBER_OF_ENEMIES];
int count = 0;

This is the code:

public void onScannedRobot(ScannedRobotEvent e) {
        double absBearing = e.getBearingRadians() + getHeadingRadians();
        enemyPoints[count]=new Point2D.Double( getX()+e.getDistance()*Math.sin(absBearing), getY()+e.getDistance()*Math.cos(absBearing));
        if(count++ >= getOthers()){ 
            count = 0;
        }

        double xForce=0, yForce= 0;
        double distance;
        for(int i=0; i<getOthers() && enemyPoints[i] != null; i++){
            absBearing = Utils.normalAbsoluteAngle(Math.atan2(enemyPoints[i].x-getX(), enemyPoints[i].y-getY()));
            distance = enemyPoints[i].distance(getX(),getY()); 
            xForce -= Math.sin(absBearing) / (distance * distance); 
            yForce -= Math.cos(absBearing) / (distance * distance); 
        }
        double angle = Math.atan2(xForce, yForce);

        if (xForce == 0 && yForce == 0) {
            // If no force, do nothing
        } else if(Math.abs(angle-getHeadingRadians())<Math.PI/2){
            setTurnRightRadians(Utils.normalRelativeAngle(angle-getHeadingRadians()));
            setAhead(Double.POSITIVE_INFINITY);
        } else {
            setTurnRightRadians(Utils.normalRelativeAngle(angle+Math.PI-getHeadingRadians()));
                setAhead(Double.NEGATIVE_INFINITY);
        }
    }

From stepping through the debugger I found that its because @:

if(count++ >= getOthers()){ //where getOthers() == 2
    count = 0;
}

count incriments to 2 after the check and on the next parse line 3 incurs an arrayindexoutofboundsexception:2.

Is it as simple as changing

if(count++ >= getOthers())

to

if(count++ >= getOthers()-1)

Not having the best understanding of turn mechanics I'm worried that there will be a trickle down effect causing issues later in the code when trying to define other enemyPoints

Thanks!

 

Last edit: Michael Skolarikis 2020-02-23