Trying to work with collisions and I used the chapter 10 marbles code but it wont work.
This Comes Up:
Here is the code:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to Fruit at Fruit.checkCollision(Fruit.java:34) at Fruit.act(Fruit.java:25) at greenfoot.core.Simulation.actActor(Simulation.java:568) at greenfoot.core.Simulation.runOneLoop(Simulation.java:526) at greenfoot.core.Simulation.runContent(Simulation.java:215) at greenfoot.core.Simulation.run(Simulation.java:205)
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* This code describes the Fruit class.
*/
public class Fruit extends SmoothMover
{
private static final double DIAMETER = 54.0;
private static final int RADIUS = 27;
public void act()
{
if ( atWorldEdge() )
{
turn(17);
}
if ( Greenfoot.getRandomNumber(100) < 10 )
{
turn( Greenfoot.getRandomNumber(90)-45);
}
move();
checkCollision();
}
/**
* Check whether we are colliding with another marble.
*/
private void checkCollision()
{
// first, get all fruit whose image intersects (we don't need to check the others)
Fruit fruit = (Fruit) getIntersectingObjects(Fruit.class);
for (Fruit fruit : fruit) {
if ( haveHit(fruit) ) {
doCollision(fruit);
}
}
}
/**
* We have hit another fruit. Perform the collision now (that is: compute the new vectors of
* movement for us and the other fruit).
*/
private void doCollision(Fruit fruit)
{
double dx = this.getExactX() - fruit.getExactX();
double dy = this.getExactY() - fruit.getExactY();
int direction = (int) Math.toDegrees(Math.atan2(dy, dx));
double angle = direction - getMovement().getDirection();
// if the not 90 < angle < 270 then we're hit from behind and don't want to move the other ball
if (Math.abs(angle) < 90 || Math.abs(angle) > 270) {
return;
}
double length = Math.cos(Math.toRadians(angle)) * getMovement().getLength();
fruit.addForce( new Vector (direction, length) );
//fruit.setMoving(true);
this.addForce (new Vector (direction + 180, length) );
//System.out.println("dir (after): " + direction + " " + this);
}
/**
* Check whether we have hit the given fruit. We have hit it if its distance from us
* (measured at the centre points) is less then our diameter.
*/
private boolean haveHit(Fruit fruit)
{
int dx = Math.abs (this.getX() - fruit.getX());
int dy = Math.abs (this.getY() - fruit.getY());
double distance = Math.sqrt(dx*dx+dy*dy);
return distance < DIAMETER;
}
}

