Whenever particles touches the wall, it would give a "java.lang.ClassCastException: Wall cannot be cast to ball" error and crash.
Here is the code:
The method responsible for this is collision2().
import greenfoot.*;
import java.util.List;
public class ball extends Actor
{
public int SPEEDX;
public int SPEEDY;
public int wait;
public int wait2;
public int speed;
public ball() //This is the speed of the ball X and Y direction.
{
speed = 4;
SPEEDX=5-Greenfoot.getRandomNumber(speed);
SPEEDY=5-Greenfoot.getRandomNumber(speed);
wait=10;
wait2=10;
setImage("Ball_Red.png");
GreenfootImage img=getImage();
img.scale(25,25);
setImage(img);
}
private void collision()// This checks the collision of the balls when they collide.
{
if (wait==0)
{
ball actor = (ball)getOneIntersectingObject(ball.class);
if ((actor!=null))
{ wait=2;
actor.wait=2;
int spx=SPEEDX;
int spy=SPEEDY;
SPEEDX=actor.SPEEDX;
SPEEDY=actor.SPEEDY;
actor.SPEEDX=spx;
actor.SPEEDY=spy;
}
}
else
wait--;
}
private void collision2()// This checks the collision of the balls when they collide.
{
if (wait==0)
{
ball actor = (ball)getOneIntersectingObject(Wall.class);
if ((actor!=null))
{ wait=2;
actor.wait=2;
int spx=SPEEDX;
int spy=SPEEDY;
SPEEDX=actor.SPEEDX;
SPEEDY=actor.SPEEDY;
actor.SPEEDX=spx;
actor.SPEEDY=spy;
}
}
else
wait--;
}
public void act()
{
int x=getX();
int y=getY();
collision();
collision2();
x=x+(int)SPEEDX;
y=y+(int)SPEEDY;
if (x<10)
{
x=10;
SPEEDX=-SPEEDX;
}
if (x>getWorld().getWidth()-10)
{
x=getWorld().getWidth()-10;
SPEEDX=-SPEEDX;
}
if (y<10)
{
y=10;
SPEEDY=-SPEEDY;
}
if (y>getWorld().getHeight()-10)
{
y=getWorld().getHeight()-10;
SPEEDY=-SPEEDY;
}
setLocation(x, y);
}
}