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

2014/2/4

How to move an object by another

BGY12C BGY12C

2014/2/4

#
Hey, our teacher knows less than we in greenfoot and we have to programm a little game. but nobody knows enough. I want that my person can move an object while holding an key. and when I stop pressing the button it should fall. I'm searching for hours but I don't check anything. I'm very sad :( Thank you
Gevater_Tod4711 Gevater_Tod4711

2014/2/4

#
To move the other object you need to get a reference to this object. When you person is touching this object you can use the getOneIntersectingObject method. Otherwhise you need to get the reference somewhere else. Maybe this tutorial can help you: Greenfoot Tutorial 6. When you have got the reference to the object you can move it like this:
1
2
3
4
5
6
7
8
9
public void setLocation(int x, int y) {
    if (Greenfoot.isKeyDown("space")) {//you can also use any other key;
        Actor actor = getOneIntersectingObject(OtherObject.class);//here you have to use the right classname of the object you want to move.
        if (actor != null) {
            actor.setLocation(actor.getX() + (x - getX()), actor.getY() + (y - getY()));//move the actor the same distance as your object;
        }
    }
    super.setLocation(x, y);//make your originally object move;
}
BGY12C BGY12C

2014/2/5

#
Thanks, but where should I paste the code? To the object which should be moved or to the object which move the other? The object which should move the other is called Siggi our main charakter and the object which should be moved is called Tische (= tables). And heben means pull. Here is my current code in the object Siggi:
1
2
3
4
5
6
7
8
9
public void heben(int x, int y){
    if(Greenfoot.isKeyDown("q")){
        Siggi siggi = getOneIntersectingObject(Tische.class);
        if(siggi != null){
            siggi.setLocation(siggi.getX() + (x - getX()), siggi.getY() + (y - getY()));
        }
    }
    super.setLocation(x, y);
}
Gevater_Tod4711 Gevater_Tod4711

2014/2/5

#
When your main character is called Siggi the code I gave you abouve goes into this class. Not in a special method just somewhere in the class (because the method setLocation(int, int) is already defined in the class Actor so you override this method.) If the Tisch is the object which is moved you can use this class in the getOneIntersectingObject method:
1
2
3
4
5
6
7
8
9
public void setLocation(int x, int y) { 
    if (Greenfoot.isKeyDown("q")) {
        Actor actor = getOneIntersectingObject(Tische.class);
        if (actor != null) { 
            actor.setLocation(actor.getX() + (x - getX()), actor.getY() + (y - getY()));
        
    
    super.setLocation(x, y);
}
You need to login to post a reply.