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

2012/9/26

Having one Actor Follow Another? (No turning)

Codybean1 Codybean1

2012/9/26

#
Hey everyone! I want one actor to follow another. More specifically being in the same X Y coords as another actor. Also, if a button is not being pressed, the following actor goes offscreen automatically. Help would be appreciated! :D
Gevater_Tod4711 Gevater_Tod4711

2012/9/26

#
so you want one actor to move to the location of another actor every time? this is simple. You just have to get the reference to the actor. Try this:
public class A extends Actor {
    private B b;
    //some other variables and code;
    
    public A(B b) {
        this.b = b;
    }
    
    public void act() {
        //follow actor b;
        setLocation(b.getX(), b.getY());
    }
}

public class B extends Actor {
    ...
    //somewhere you have to add the object A to the world. So do this:
    private A a = new A(this);//this chould be global;
    getWorld().addObject(a, getX(), getY());//in a method or the construktor;
    ...
}
Of course you have to change the names a and b but then it should work.
Codybean1 Codybean1

2012/9/26

#
I'm trying to implement it but I'm confused between the uppercase and lowercase a's and b's. Can you use weirder symbols " Squggly, Robot," so I'm not inputing it incorrectly? :D
danpost danpost

2012/9/26

#
If the Squggly object is to follow the Robot object and 'space' is the key then
// in the world class constructor
Squggly squggly = new Squggly;
Robot robot = new Robot(squggly);
// the rest is in the Robot class 
// instance fields
Squggly squggly = null;
boolean squgglyShowing = false;
// the constructor
public Robot(Squggly squggly)
{
    this.squggly = squggly;
}
// in the act method
checkSquggly();
// add the method
private void checkSquggly()
{
    if (!squgglyShowing && Greenfoot.isKeyDown("space"))
    {
        getWorld().addObject(squggly, getX(), getY());
        squgglyShowing = true;
    }
    if (squgglyShowing && !Greenfoot.isKeyDown("space"))
    {
        getWorld().removeObject(squggly);
        squgglyShowing = false;
    }
    if (squgglyShowing) squggly.setLocation(getX(), getY());
}
You need to login to post a reply.