This site requires JavaScript, please enable it in your browser!
Greenfoot back
darkmist255
darkmist255 wrote ...

2011/12/10

Missing return statement?

darkmist255 darkmist255

2011/12/10

#
I'm making a slightly modified version of my collision detector that will return what side the collision happened on, but it tells me I'm missing a return statement, even though I've made an "else return". What is wrong in this:
    public String detectCollisionReturnSide(int moveSpeed, int xMomentum, int yMomentum)
    {
        NonPassable object;
        if(getOneIntersectingObject(NonPassable.class) != null)
        {
            object = (NonPassable) getOneIntersectingObject(NonPassable.class);
            if(object.getY() >= (getY() - 15)) //gives angled illusion
            {
                if(xMomentum > 0) //moving right
                {
                    return "CollidedRight";
                }
                if(xMomentum < 0) //moving left
                {
                    return "CollidedLeft";
                }
                if(yMomentum > 0) //moving down
                {
                    return "CollidedDown";
                }
                if(yMomentum < 0) //moving up
                {
                    return "CollidedUp";
                }
            }
        }
        else
        {
            return "noCollision";
        }
    }
Do I maybe have a bracket in the wrong place? It's my understanding that if I have the "else" statement, this should work. Any help appreciated :D!
Builderboy2005 Builderboy2005

2011/12/10

#
Java see's that there are certain cases where a Return will not be encountered. Like if getOneIntersectingObject() is not null, it will enter the If statement, but if object.getY() is not greater than getY()-15, it will skip over the next 4 If statements, and then reach the else. Since the first If was indeed true, the Else is not executed. The best solution in this case would be to remove the else altogether and simply have: return "noCollision"; at the very last line.
darkmist255 darkmist255

2011/12/10

#
So if a "return" is reached, does it execute beyond that, or does it end there? That was my original reason, I though that without the "else" it would just always return "noCollision".
davmac davmac

2011/12/10

#
Once a "return" is reached, the method finishes execution.
darkmist255 darkmist255

2011/12/10

#
Thanks! I got it working! The first opponent is now finished, and the game engine is 90% complete. Now for some visible progress :D!
You need to login to post a reply.