Greenfoot: java.lang.ClassCastException: Obstacle cannot be cast to BallProjectile

267 Views Asked by At

Alright, so I get this error when I try to make it so that when BallProjectile collides with an obstacle, the ball stops and makes a new one.

// Checks if the ball is colliding with an obstace, then stops it if it is

BallProjectile obstacleCollision = (BallProjectile) getOneIntersectingObject(Obstacle.class);
        if (obstacleCollision != null)
        {
            xSpeed = 0;
            ySpeed = 0;
            myWorld.addObject(new BallProjectile(), 50, 559);
            return;
        }

How do I stop this error? Note that obstacle is just that, a circle created to get in the way of the ball.

1

There are 1 best solutions below

3
On BEST ANSWER

The only place where you're doing a cast in the code provided is:

BallProjectile obstacleCollision = (BallProjectile) getOneIntersectingObject(Obstacle.class);

So I think it's where your problem is. Seems like the return of this method cannot be cast as BallProjectile

EDIT:

To verify your collision you could do either:

Obstacle obstacleCollision = (Obstacle) getOneIntersectingObject(Obstacle.class);
if(obstacleCollision != null) {
   //do your things here
}

OR

Actor obstacleCollision = getOneIntersectingObject(Obstacle.class);
if(obstacleCollision != null) {
   //do your things here
}

Both approaches should work the same way