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

2015/8/7

Need an Actor to follow another actor!

Hpage17 Hpage17

2015/8/7

#
Hey, so I'm doing a project in class, and I want an enemy to follow an Actor. If someone could give me code to use or a game that has this, plz show or tell me ASAP!
jackandjim jackandjim

2015/8/8

#
so it a little depends on what game you have in any case you will need getMethods for your actor like this one :
1
2
3
public int getX(){
    return xPos;
}
your enemy now wants to move to your actor let's say its like a mario 2d game where you want the enemy just to move on the x-axis then how your enemy follows your actor could look like this (in the enemy class)
1
2
3
4
5
6
7
8
9
10
11
//all this happens in enemy class
//xPos = the actual position of the enemy
//speed = the speed of the enemy
 
private void followActor(){
    if(xPos < actor.getX()){
        xPos =  xPos + speed;
    }else if(xPos > actor.getX()){
        xPos =  xPos - speed;
    }
}
danpost danpost

2015/8/8

#
jackandjim wrote...
in any case you will need getMethods for your actor like this one :
1
2
3
public int getX(){
    return xPos;
}
This method is quite redundant. You already have a 'getX' method from the Actor class that you can use on any actor within a world object, which gets the value from the private Actor class 'x' field.
so it a little depends on what game you have
Indeed, the viewing direction and the particular movement of the enemy you require play a part in how it is coded and the code itself could be quite simple or quite complex.
jackandjim jackandjim

2015/8/8

#
Oh yeah, you're right Haven't used greenfoot soooo long I forgot about that
Hpage17 Hpage17

2015/8/9

#
Ok, I will try as soon as I have my computer.
You need to login to post a reply.