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

2017/5/6

enemies follow player without moving into wall

mr.tim_r mr.tim_r

2017/5/6

#
How can I make that enemies who follow my player don“t move through walls?
public void followPlayer() 
    {

        {  
            int dist = 300;  
            Actor closest = null;  

            if(!getObjectsInRange(dist, Player.class).isEmpty())  
            {  
                for (Object obj: getObjectsInRange(dist, Player.class))  
                {  

                    Actor Player = (Actor) obj;  
                    move(1);
                    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

2017/5/6

#
There are various ways to do that. Using a "line-of-sight" object is one of the most common ways. Also, it may help to keep the last location of chased player in an enemy that had one in its sights (so the enemy could proceed toward that location (when the player moves behind a wall) to see if sight on the player can be re-acquired (if no other player is currently in sight). Here is a link to an earlier discussion on a LineOfSight object.
You need to login to post a reply.