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

2018/3/5

Game Crashing When Class Goes Out of The World Even Though It's Set To Delete It When It Reaches The Edge

SchoolCoder38 SchoolCoder38

2018/3/5

#
I have to submit this project and I'm having an error with this code and I can't figure out what's causing it. Help would be very appreciated, thanks in advance!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    public void act()
    {
    controlTheArrow();
    removeTheArrow();
    move(4);
 
    Actor actor = getOneIntersectingObject(Target.class);
        if (actor !=null)
        {
            ShootingGameWorld gameWorld = (ShootingGameWorld)getWorld();
            gameWorld.removeObject(actor);
            gameWorld.removeObject(this);
         
    }  
 }   
 public void controlTheArrow()
 {
     if (Greenfoot.isKeyDown ("right"))
     {
         turn(1);
     }
     if (Greenfoot.isKeyDown ("left"))
     {
         turn(-1);
     }
  }
  public void removeTheArrow()
  {
    int xCoord = getX();
    int yCoord = getY();
      if(yCoord<=0)
    {
            World gameWorld = getWorld();
            gameWorld.removeObject(this);
             
    }
    if(xCoord>=1499)
    {
        World gameWorld = getWorld();
        gameWorld.removeObject(this);
    }
 }
}
danpost danpost

2018/3/5

#
You cannot move an arrow if it is removed from the world. As well, you cannot check for an intersecting target after the arrow is removed from the world. And how about the other two edges (bottom and left) -- I would think the arrow would be removed if reaching either of them also. Instead of the 'removeTheArrow' method, maybe you can use 'isAtEdge' and concatenate the possible conditions for removal into one statement:
1
2
3
4
5
6
7
8
public void act()
{
    controlTheArrow();
    move(4);
    Actor actor = getOneIntersectingObject(Target.class);
    if (actor != null) getWorld().removeObject(actor);
    if (actor != null || isAtEdge()) getWorld().removeObject(this);
}
SchoolCoder38 SchoolCoder38

2018/3/6

#
Thank you very much! This worked great and now my game is finished!
danpost wrote...
You cannot move an arrow if it is removed from the world. As well, you cannot check for an intersecting target after the arrow is removed from the world. And how about the other two edges (bottom and left) -- I would think the arrow would be removed if reaching either of them also. Instead of the 'removeTheArrow' method, maybe you can use 'isAtEdge' and concatenate the possible conditions for removal into one statement:
1
2
3
4
5
6
7
8
public void act()
{
    controlTheArrow();
    move(4);
    Actor actor = getOneIntersectingObject(Target.class);
    if (actor != null) getWorld().removeObject(actor);
    if (actor != null || isAtEdge()) getWorld().removeObject(this);
}
You need to login to post a reply.