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

2019/1/11

Error when bullet istouching and set Hp on enemy

dev4ltar dev4ltar

2019/1/11

#
here is my code on bullet
public void act() 
    {
        // Add your action code here.
        setRotation(direction);
        move(speed);
        
        if (isAtEdge()){
            getWorld().removeObject(this);
        }else{
            hittingEnemy (); //error here
        }
        
    }

private void hittingEnemy (){
        if (isTouching (Enemy.class)){
            getWorld().addObject(new Boom(), getX(), getY());
            getWorld().removeObject(this);
            removeTouching(Enemy.class); //and here 
            MyWorld.setScore(10); 
        }
    }
it give error "java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed." and i want when we hit the enemy, enemy's hp - 1 and when enemy hp = 0 it removed code on enemy
//private static int Ehp = 2;
    
    public static void setEhp(int dmg){
        Ehp = Ehp + dmg;
    }
    
    public void die(){
        if ( Ehp < 1 ){
        getWorld().removeObject(this);
       }
    }
Thanks for helping
danpost danpost

2019/1/11

#
Just move line 19 in your bullet snippet up a line or two. It cannot remove a touching actor (or even touch one) if the actor is not in the world -- where line 18 removes it from the world.
dev4ltar dev4ltar

2019/1/12

#
thanks xD , and about the hp for the enemy is the code correct? i want to change the "removeTouching(Enemy.class);" with "Enemy.setEhp(-1);" so it require 2 hit before the enemy die, i have tried a few times but i don't know which part that didn't work
dev4ltar dev4ltar

2019/1/12

#
i have try some but it kill all enemy, then i have fix it so it require 2 hit for each enemy but instead it kill on second hit i.e Enemy 1 get 1 hit, Enemy 2 get 1 hit and destroyed, Enemy 1 need to hit 2 times again so it need 3 time, while i want each enemy have their own hp and destroyed in 2 hit, pls help and thank you very much
dev4ltar dev4ltar

2019/1/12

#
//bullet
private void hittingEnemy (){
        if (isTouching (Enemy.class)){
            getWorld().addObject(new Boom(), getX(), getY());
            Enemy.setEhp(-1); 
            getWorld().removeObject(this);
            MyWorld.setScore(10); 
        }

//enemy
 public static int Ehp = 2;
    public static void setEhp(int dmg){
       Ehp = Ehp + dmg;
    }
    
    public void die(){
        if ( this.Ehp < 1 ){
            getWorld().removeObject(this);   
        }
    }

danpost danpost

2019/1/12

#
To do that, you will need to remove the word "static" from your code (both occurrences above).
dev4ltar dev4ltar

2019/1/12

#
thanks, will try :D
You need to login to post a reply.