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

2013/7/3

moving object forward after offset

davemib123 davemib123

2013/7/3

#
I am trying to check when my Hero makes impact with an object at a specific point I want to bounce it back. I have this at the moment:
 if (getOneObjectAtOffset(-30, -40, Mario.class) != null || getOneObjectAtOffset(-30, 40, Mario.class) != null)   
        {  
             System.out.println("hit block left");
            //Mario.setLocation(getX() - 30, getY());

        }  
        if (getOneObjectAtOffset(30, -40, Mario.class) != null || getOneObjectAtOffset(30, 40, Mario.class) != null)   
        {  
             System.out.println("hit block right");
        } 
How do I move Mario -30 on the first if statement and +30 on the second?
Gevater_Tod4711 Gevater_Tod4711

2013/7/3

#
Therefore you need to get the reference to Mario to make him move. Try it like this:
List<Hero> heros = getObjectsInRange(60, Hero.class);
if (heros != null && !heros.isEmpty()) {
    Hero mario = heros.get(0);
    mario.setLocation(mario.getX() - 30, mario.getY());//or any other movement you want;
}
davmac davmac

2013/7/3

#
There's no need to check heros != null in the code above - getObjectsInRange(...) cannot return null.
Gevater_Tod4711 Gevater_Tod4711

2013/7/3

#
Oh yes the check for != null is superfluous in this case. It's only necessary if an Actor is returned not a List.
davmac davmac

2013/7/3

#
Also, there's a better way to go about this; roughly:
    Mario mario = getOneObjectAtOffset(-30, -40, Mario.class);
    if (mario == null) {
        mario = getOneObjectAtOffset(-30, 40, Mario.class);
    }

    if (mario != null)
    {
        System.out.println("hit block left");  
        mario.setLocation(getX() - 30, getY());  // possibly needs adjusting!
    }
      
    // repeat above for right hand side
davemib123 davemib123

2013/7/3

#
That's great. I've just tried out both methods and they work great with some minor tweaking :)
You need to login to post a reply.