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

2014/6/29

How do you make enemies follow a player?

Novaa Novaa

2014/6/29

#
I know there are forms telling you to set the rotation towards the player and move towards it, but with my enemy textures I need a way where they move towards the player without turning. Can anyone help?
danpost danpost

2014/6/29

#
You will only see the end result of what an act method does. What you do during it will not be seen:
turnTowards(/* location coordinates */);
move(/* speed */);
setRotation(0);
Adding the last statement above keeps the player upright. BTW, there is a way to actually be able to see what an act method is doing during its execution, however, that requires extra coding and no other actors will be doing their normal actions while the act method is executing.
Novaa Novaa

2014/6/29

#
@Danpost The followHuman method I have been using stops working when I add the setRotation(0) it stops working and they run into the wall. help?
public void followHuman()  
    {  
        int dist = 1000;  
        Actor closest = null;  
          
        if(!getObjectsInRange(dist, Player.class).isEmpty())  
        {  
        for (Object obj: getObjectsInRange(dist, Player.class))  
        {  
       
            Actor Player = (Actor) obj;  
            move(2);
            int playerDist = (int) Math.hypot(Player.getX() - getX(), Player.getY() - getY());  
            if (closest == null || playerDist< dist)  
            {  
                    closest = Player;  
                    dist = playerDist;  
            }  
        }  
        turnTowards(closest.getX(),closest.getY());  
        }     
    } 
danpost danpost

2014/6/29

#
I think you want line 12 placed after line 20; otherwise, your enemy will move for all actors in the direction currently facing and then turn toward the closest one at the end. Also, with the move inside the loop, like that, the distances will be changing while you are trying to figure out the closest one, which may give false results.
You need to login to post a reply.