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

2014/5/5

Problem with getObjectsInRange()

1
2
Jonche Jonche

2014/5/5

#
Hi, As I am working on my RPG project, I want to fix a bug but I need to access the code of the getObjectsInRange method since it doesn't properly work with my programm : I have a monster which I hit several times and sometimes, it becomes invincible. Doing some debugging, I found out the actor which hits the monster doesn't get the actor "Monster" with the getObjectsInRange() method. Checking if the world still considers it as being in it, I come to the conclusion there must be an error with the getObjectsInRange() method so I need to know where I could find its source code.. Thank you in advance for your answers!
erdelf erdelf

2014/5/5

#
well, i personally think its a problem with your own collision code, but you can find the source code in the download section . The method is in the actor class.
Jonche Jonche

2014/5/5

#
You might be right, the method is just going further into another java library. I have to look for the bug in my code but I don't really know where to start. My collision method does work but until a point where it doesn't anymore and I don't really know why this is... I will upload some code when I actually know what you want to see.
danpost danpost

2014/5/5

#
Things that may be needed: (1) the act method of the class which contains the collision method (2) the collision method (3) any method the collision method calls (and any those methods call) (4) trace information of any fields used within those methods (5) trace information of any fields used to place conditions on the execution of those methods By 'trace information', I mean how and where the fields are declared, and where and how the value of those fields are assigned and changed. All in all, pretty much anything that you have incorporated into your collision detection (because it could be a combination of things working together that creates the issue -- or , it could be one simple detail that was overlooked). From what it sounds (by what you stated above), it may be a combination of things; but, I could be wrong.
Jonche Jonche

2014/5/6

#
So this is the main method in the class of the actor that wants to get the "Monster" object.
if (Greenfoot.isKeyDown("space"))
      {
           if (hitReload >= hitReloadTime)
           {
             checkIfMonsterNearby();
              Monster monster = (Monster)getNearestActor();
              
              if (monsterIsNear == true){
              monster.healthPoints = setHealth(monster.healthPoints, damage);
              animateAttack();
              monster.wasHit = true;
              hitReload = 0;
              
             }
           }
      }
These two methods are used in it :
public void checkIfMonsterNearby()  
    {
        List<Monster> nearMonsters = getObjectsInRange(39, Monster.class);
        monsterSizeTEST = nearMonsters.size();
        if (nearMonsters.size() != 0){
         Monster monster = (Monster)getNearestActor();
              if(direction == 0){if(getX() - monster.X <= 10 && getY() - monster.Y <= 40 || monster.X - getX() <= 10 && getY() - monster.Y <= 40){monsterIsNear = true;}} 
         else if(direction == 1){if(monster.X - getX() <= 40 && monster.Y - getY() <= 10 || monster.X - getX() <= 40 && getY() - monster.Y <= 10){monsterIsNear = true;}} 
         else if(direction == 2){if(getX() - monster.X <= 10 && monster.Y - getY() <= 40 || monster.X - getX() <= 10 && monster.Y - getY() <= 40){monsterIsNear = true;}} 
         else if(direction == 3){if(getX() - monster.X <= 40 && monster.Y - getY() <= 10 || getX() - monster.X <= 40 && getY() - monster.Y <= 10){monsterIsNear = true;}} 
         else {monsterIsNear = false;}
        }
        else{monsterIsNear = false;}
    }
    
  
    public Actor getNearestActor()                   
    {
        List<Monster> nearActors = getObjectsInRange(40, Monster.class);
        monsterSizeTEST2 = nearActors.size();
        Monster nearestActor = null;
        double nearestDistance = 40;
        double distance; 
        for (int i = 0; i < nearActors.size(); i++)
        {
            distance = getDistance(nearActors.get(i));
            if (distance < nearestDistance)
            {
                nearestActor = nearActors.get(i);
                nearestDistance = distance;
            }
            
        }
        return nearestActor;
    }
I now actually wonder if the coordinate comparison is failing the whole method. I'll go ahead and check that by removing it. I'll tell you if it is fixed.
Jonche Jonche

2014/5/6

#
The setHealth() method looks like this :
public static int setHealth(int health, int damage) 
    {
        health = health - damage;
        int newHealth = health;
        return newHealth;
    }
and the animateAttack method is empty at the moment.
davmac davmac

2014/5/6

#
Are you using the latest version of Greenfoot?
danpost danpost

2014/5/6

#
The only thing the 'setHealth' method is doing is taking two int values and subtracting one from the other and returning the result. It really does nothing for the class it is in (changes no values within the class itself). Line 9 in your main method might as well just say:
monster.healthPoints = monster.healthPoints-damage;
//   OR
monster.healthPoints -= damage;
and remove the 'setHealth' method. Even the name sounds strange for a 'static' method. The class itself does not have a health value, only the objects created from it do. I have a feeling that you issue is mainly in the 'checkIfMonsterNearby' method. The OR'ing (' || ') does not make sense in them. Try AND'ing them all.
Jonche Jonche

2014/5/6

#
Yes I do have the latest version of greenfoot. Thanks danpost for pointing these things out for me. Since I was programming this game as I was beginning with the Java language, there are these kind of useless methods everywhere ^^. Anyway, changing these things don't change my problem. As I play, once in the game, only one monster becomes invincible. Therefore there must be something, like a variable in the Monster that makes him unvulnerable, I'll go ahead and look for the problem. If you know anything that interacts with the getObjectsInRange method, let me know.
danpost danpost

2014/5/6

#
Please post the code for your Monster class.
Jonche Jonche

2014/5/7

#
There you go. It is quite long though.
private boolean joeIsNear = false;
   private boolean joeIsHere = false;
   private int lastImage = 1;
   
   public int expDrop = 0;
   public boolean wasHit;
   int lifePercentage;
   int imageCounter;
   double healthPercentage;
   public int healthPoints; 
   public int maxHealth;
   public int monsterDamage;
   boolean hMove;
   int moveAmmount = 50;
   int whatMove;
   boolean vMove;
   int joePosition;        /**This variable is Joe's position compared to a monster. 0 is top-right, 1 is bot-right, 2 is bot-left, 3 is top-left.**/
   int posNeg;
   int counter = 0;
   private int attackCounter = 0;
    
   public int aggroRange;
   
   public int X;
   public int Y;
    
   public GreenfootImage standLeft;
   public GreenfootImage standRight;
   public GreenfootImage currentImage; 
   public GreenfootImage voidImage;
    
    public Monster()    /**The constructor of every monster will just initialize the first image, and set the imageCounter to 40.**/
    {
        wasHit = false;
        setImage (standRight);
        imageCounter = 40;
        attackCounter = 0;
        lastImage = 1;
    }
    
    public void act() /**A more than normal act method.**/
    {
        if(attackCounter == 0){
        
        checkIfJoeIsNear();
        checkIfJoeIsHere();
        checkHealthPercentage();
        moveMaybe();
        setCoordinates();
        checkIfWasHitLately();
        getWorld().addObject (new HealthBar(lifePercentage), getX(), getY() - 25);
        checkHealth();
        }
        else {
        setCoordinates();
        checkHealthPercentage();
        getWorld().addObject (new HealthBar(lifePercentage), getX(), getY() - 25);    
        animateAttack();
        checkIfWasHitLately();
        checkHealth();
        }
    }   
    
    public void checkIfJoeIsNear()      /**In this method, the monster is going to determine if Joe is anywhere nearby, actually it's going to check if he's 300px near**/
       {
             if (getX() - Joe.joeX < 300 && Joe.joeY - getY() < 300 && getX() - Joe.joeX > 0 && Joe.joeY - getY() > 0) {joeIsNear = true;} 
        else if (getX() - Joe.joeX < 300 && getY() - Joe.joeY < 300 && getX() - Joe.joeX > 0 && getY() - Joe.joeY > 0) {joeIsNear = true;} 
        else if (Joe.joeX - getX() < 300 && Joe.joeY - getY() < 300 && Joe.joeX - getX() > 0 && Joe.joeY - getY() > 0) {joeIsNear = true;} 
        else if (Joe.joeX - getX() < 300 && getY() - Joe.joeY < 300 && Joe.joeX - getX() > 0 && getY() - Joe.joeY > 0) {joeIsNear = true;} 
        else {joeIsNear = false;}
       }
       
       public void checkIfJoeIsHere()       /**This one, comparing to the other, is just going to check if joe's in attack range.**/
    {
             if (getX() - Joe.joeX < 40 && Joe.joeY - getY() < 40 && getX() - Joe.joeX > 0 && Joe.joeY - getY() > 0) {joeIsHere = true;} 
        else if (getX() - Joe.joeX < 40 && getY() - Joe.joeY < 40 && getX() - Joe.joeX > 0 && getY() - Joe.joeY > 0) {joeIsHere = true;} 
        else if (Joe.joeX - getX() < 40 && Joe.joeY - getY() < 40 && Joe.joeX - getX() > 0 && Joe.joeY - getY() > 0) {joeIsHere = true;} 
        else if (Joe.joeX - getX() < 40 && getY() - Joe.joeY < 40 && Joe.joeX - getX() > 0 && getY() - Joe.joeY > 0) {joeIsHere = true;} 
        else {joeIsHere = false;}
    }
    
    public void moveMaybe()     /**Here you're going to see the monster move, if it wants to : Joe can be next to the monster, in which case it will attack and not move.**/
    {
       if (joeIsNear == true){moveTowardsJoe();}
       else{
            if (moveAmmount <= 50){monsterReposition();}
            else {
            if (Greenfoot.getRandomNumber(50) < 1){monsterMove();}
            }
       }
    }
    
    public void moveTowardsJoe()        /**the monster has located Joe, it is now going towards him.**/
    {
        if (joeIsHere == false){
            
            
            if (getNearestMove() == 0 && canMoveX() != 1)
            {
                horizontalMove(2);
                setImage(standRight);
                currentImage = getImage();
            }
            
            if (getNearestMove() == 1 && canMoveY() != 4)
            {
                verticalMove(2);
            }
            
            if (getNearestMove() == 2 && canMoveX() != 2)
            {
                horizontalMove(-2);
                setImage(standLeft);
                currentImage = getImage();
            }
            
            if (getNearestMove() == 3 && canMoveY() != 3)
            {
                verticalMove(-2);
            }
            
        }
        else{ if (counter >  30){attack();}
              counter ++;}
    }
    
        public void attack()        /**Pikachu, thunder attack !**/
    {
          Joe.actualHealth = Joe.actualHealth - monsterDamage;
          counter = 0;
          attackCounter = 30;
          animateAttack();
    }    
    
    public int getNearestMove()     /**In this method, the way moving towards Joe is going to be determined: The longest way is going to be walked.**/
    {
        int bestMove = 0;
        int moveDirection = 0;
        int [] testMove;
        testMove = new int [4];
        
        if(Joe.joeX - getX() < 300 && Joe.joeX - getX() >= 0){testMove[0] = Joe.joeX - getX();}
        if(getX() - Joe.joeX < 300 && getX() - Joe.joeX >= 0){testMove[2] = getX() - Joe.joeX;}
        
        if(getY() - Joe.joeY < 300 && getY() - Joe.joeY >= 0){testMove[1] = getY() - Joe.joeY;}
        if(Joe.joeY - getY() < 300 && Joe.joeY - getY() >= 0){testMove[3] = Joe.joeY - getY();}
        
        for (int i = 0; i < 4; i++)
        {
            if ( testMove[i] > bestMove)
            {
                bestMove = testMove[i];
                moveDirection = i;
            }
        }
        
        return moveDirection;
    }
    
    public void monsterMove()       /**These are random moves that are done by the monster if he's not feeling like attacking.**/
    {
        posNeg = Greenfoot.getRandomNumber(2);
        whatMove = Greenfoot.getRandomNumber(2);
        if (whatMove == 0){hMove = false;}
        else if (whatMove == 1){hMove = true;}
        moveAmmount = 0;
       }
       
    public void monsterReposition()     /** This is the actual moves mentioned just above**/
    {
        if (hMove == true)
        {
            if(posNeg == 0 && canMoveX() != 1){horizontalMove(1);setImage(standRight);currentImage = getImage();}
            if(posNeg == 1 && canMoveX() != 2){horizontalMove(-1);setImage(standLeft);currentImage = getImage();}
            moveAmmount++;
        }
        if (hMove == false)
        {
            if(posNeg == 0&& canMoveY() != 4){verticalMove(1);}
            if(posNeg == 1&& canMoveY() != 3){verticalMove(-1);}
            moveAmmount++;
        }
    }
       
    public void setCoordinates()        /**Determination of the coordinates of the monster in order for Joe to know where they are.**/
    {
           X = getX();
           Y = getY();
    }
    
    public void checkHealth()       /**If you have no health, you can't live on this planet anymore, sorry bro.**/
    {
        if (healthPoints <= 0) {die();}
    }
    
    public void checkHealthPercentage()     /**Here we are going to find out, how much health the monster has in order to create a proportional HealthBar.**/
    {
        healthPercentage = healthPoints*100 / maxHealth;
        if (healthPoints*100 / maxHealth == 100){lifePercentage = 0;} 
        else if (healthPoints*100/maxHealth >= 75){lifePercentage = 1;}
        else if (healthPoints*100/maxHealth >= 50){lifePercentage = 2;}
        else if (healthPoints*100/maxHealth >= 25){lifePercentage = 3;}
        else if (healthPoints*100/maxHealth > 0){lifePercentage = 4;}
        
    }
    
    public void die()       /**If you have no health you're going to be sent here. Sorry for real now, bro.**/
    {
        if(Greenfoot.getRandomNumber(5) == 1)
        {getWorld().addObject (new Potion(),getX(),getY());}
        Joe.experience += expDrop;
        Joe.checkExperience();
        getWorld().addObject (new Boulotte(), Greenfoot.getRandomNumber(800),Greenfoot.getRandomNumber(800));
        getWorld().removeObject(this);
    }
    
    public void checkIfWasHitLately()       /**If the monster gets punched or whatever, it's going to blink for a few seconds, this method is responsible for this animation.**/
    {
        if (wasHit){imageCounter = 0;}
        if (imageCounter < 30)
        {
            
            if (lastImage < 2){setImage (currentImage); lastImage ++;}
            else if (lastImage >= 2 ){setImage(voidImage); lastImage ++;}
            if (lastImage >= 5){lastImage = 0;}
            imageCounter ++;
            wasHit = false;
        }
        if(imageCounter <= 0) {lastImage =1;}
    }
    
    public void animateAttack() /** This method is responsible for doing the attack move, which is going to stop the monster for a few seconds while it's attacking**/
    {
        if (attackCounter <= 0){attackCounter =0;}
        else 
        {
         attackCounter --;
         attackVisual();
        }
    }
    
    public void attackVisual()  /**This method will do the animation of the monster attacking Joe.**/
    {
        if (attackCounter > 0){setImage("frog.png");}
        else{setImage(currentImage);}
    }
    
    public int canMoveX()
    {
        List <Block> nearObstacle = getObjectsInRange(60, Block.class);
        int value = 0;
        
        Block nearestObstacle = null;
        double nearestDistance = 60;
        double distance; 
        for (int i = 0; i < nearObstacle.size(); i++)
        {
            double distX = nearObstacle.get(i).getX();
            double distY = nearObstacle.get(i).getY();
            
            double diffX = distX - getX();
            double diffY = distY - getY();
            
            distance = Math.hypot(diffX, diffY);  
            
            if (distance < nearestDistance)
            {
                nearestObstacle = nearObstacle.get(i);
                nearestDistance = distance;
            }
            
        }
         if(nearestObstacle != null){
         Block block = nearestObstacle;
         int blockX = block.getX() - getX();
         int blockY = block.getY() - getY();
         if(blockX < 35 && blockX > 0){if(blockY < 35 && blockY > -35){value = 1;}} /**The block is on the right**/
         else if(blockX > -35 && blockX < 0){if(blockY < 35 && blockY > -35){value = 2;}} /**The block is on the left**/
        }
        return value;
    }
    
    public int canMoveY()
    {
        List <Block> nearObstacle = getObjectsInRange(60, Block.class);
        int value = 0;
        
        Block nearestObstacle = null;
        double nearestDistance = 60;
        double distance; 
        for (int i = 0; i < nearObstacle.size(); i++)
        {
            double distX = nearObstacle.get(i).getX();
            double distY = nearObstacle.get(i).getY();
            
            double diffX = distX - getX();
            double diffY = distY - getY();
            
            distance = Math.hypot(diffX, diffY);  
            if (distance < nearestDistance)
            {
                nearestObstacle = nearObstacle.get(i);
                nearestDistance = distance;
            }
            
        }
        if(nearestObstacle != null){
         Block block = nearestObstacle;
         int blockX = block.getX() - getX();
         int blockY = block.getY() - getY();
         if(blockY < 35 && blockY > 0){if(blockX < 35 && blockX >-35){value = 3;}} /**The block is on top**/
         else if(blockY > -35 && blockY < 0){if(blockX < 35 && blockX >-35){value = 4;}} /**The block is beneath**/
         }
        return value;
    }
danpost danpost

2014/5/7

#
I do not see anywhere in the class where a Monster object is given any health points.
Jonche Jonche

2014/5/7

#
Well since I want to do many monsters, the initialisation of the health points is done in a subclass so I can divide the Monster class in many subclasses in order to have some variety of monsters.
danpost danpost

2014/5/7

#
Jonche wrote...
Well since I want to do many monsters, the initialisation of the health points is done in a subclass so I can divide the Monster class in many subclasses in order to have some variety of monsters.
Then: (1) do not create any Monsters directly from the Monster class; (2) do not re-declare the 'healthpoints' field in the subclasses; only set the value of it in the constructor of the subclasses, like so:
healthpoints = 100;}
(3) any other fields that are declared in the Monster class must not be re-declared in the sub-classes
Jonche Jonche

2014/5/7

#
Yes it is done. Meanwhile I changed the way I looked for monsters by the way. It looks like this :
if (Greenfoot.isKeyDown("space"))
      {
           if (hitReload >= hitReloadTime)
           {
             checkIfMonsterNearby();
              if (monsterIsNear == true){
              monster.healthPoints -= damage;
              animateAttack();
              monster.wasHit = true;
              hitReload = 0;
              monster = null;
             }
           }
      }
      else {}

 public void checkIfMonsterNearby()  
    {
        List<Monster> nearMonsters = getObjectsInRange(39, Monster.class);
        monsterSizeTEST = nearMonsters.size();
        if (nearMonsters.size() != 0){
         double nearestDistance = 39;
         double distance; 
         for (int i = 0; i < nearMonsters.size(); i++)
         {
            distance = getDistance(nearMonsters.get(i));
            if (distance < nearestDistance)
            {
                monster = nearMonsters.get(i);
                nearestDistance = distance;
            }
         }
         
              if(direction == 0){if(getX() - monster.getX() <= 10 && getY() - monster.getY() <= 40 && monster.getX() - getX() <= 10 && getY() - monster.getY() >= 0){monsterIsNear = true;}} /** UP **/
         else if(direction == 1){if(monster.getX() - getX() <= 40 && monster.getY() - getY() <= 10 && monster.getX() - getX() >= 0 && getY() - monster.getY() <= 10){monsterIsNear = true;}} /** RIGHT **/
         else if(direction == 2){if(getX() - monster.getX() <= 10 && monster.getY() - getY() <= 40 && monster.getX() - getX() <= 10 && monster.getY() - getY() >= 0){monsterIsNear = true;}} /** DOWN **/
         else if(direction == 3){if(getX() - monster.getX() <= 40 && monster.getY() - getY() <= 10 && getX() - monster.getX() >= 0 && getY() - monster.getY() <= 10){monsterIsNear = true;}} /** LEFT **/
         else {monsterIsNear = false;}
        }
        else{monsterIsNear = false;}
    }
As the attack method used twice the method to look for a monster and created one list for each method, I thought it would be better to have only one list instead of two and therefore directly check the position of the nearest monster in the list and attack this monster. I initialized a private Monster field at the start of my Class
There are more replies on the next page.
1
2