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

2016/12/2

Need help with collision method

miahg17 miahg17

2016/12/2

#
My Hostile actor moves toward my Player Actor. If it intersects an Obstacle it needs to not go through but treat as a wall. I've tried many different variations of turn(int) and move(int) /get and setRotation() from Player, etc. combinations but all are inconsistent and result in the Actor jumping through the Obstacle or speeding up, etc. The current method for collision detection and avoidance is bounceAtWall() in the Hostile Class posted below:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Hostile here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Hostile extends Actor
{
   private Player player;
    
    public Hostile(Player player){
        this.player = player;
    }
    
    /**
     * Act - do whatever the Red wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
    
    }
    
    public void chasePlayer()
    {
        if (player == null || player.getWorld() == null || getWorld() == null){
            return;
        }
        
        turnTowards(player.getX(),player.getY());
    
        /*int dX = player.getX() - getX();
        int dY = player.getY() - getY();
        setRotation((int) (180 * Math.atan2(dY, dX) / Math.PI));
        */
    }
    
    public void isAtHole(){
       Hole hole = (Hole) getOneIntersectingObject(Hole.class);
       if(hole!=null){
            World board = (World) getWorld();
            board.removeObject(this);
          
       }
    }
    
    public void killPlayer(){
        if (getWorld() == null){
            return;
        }
        Player player = (Player) getOneIntersectingObject(Player.class);
        if(player!=null){
            World board = (World) getWorld();
            board.removeObject(player);
        } 
        
    }
    
    public void bounceAtWall(){
        if (getWorld() == null){
            return;
        }
        if(getOneIntersectingObject(Obstacle.class)!= null){
            int rot = getRotation();
            setRotation(-rot);
            move(5);
            
            
          
        }
    }
danpost danpost

2016/12/2

#
Negating the rotation does not necessarily turn the actor around. For two examples, -180 is the same direction as 180; and -0 is the same as 0. The rotations at which it will turn around are at 90 and 270. What you want to do is just add (or subtract) 180 from the current rotation to turn the actor around. Change line 67 to:
setRotation(rot+180);
or replace lines 66 and 67 with:
turn(180);
You need to login to post a reply.