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

2020/3/25

if condition meant to prevent out of bound mouse error

LewisEro LewisEro

2020/3/25

#
hey, the second if is meant to prevent the character casting his spell while the mouse is out of the map, as this crashes the game. unfortunately, this approach does not prevent that. what am i doing wrong?
    public void shadowball(){
        if(Greenfoot.isKeyDown("Space")){
        MouseInfo mouse = Greenfoot.getMouseInfo();                     
            if(mouse.getX() > 0 && mouse.getX() < 600 && mouse.getY() > 0 && mouse.getY() < 600){
            Actor shadowball = new Shadowball();
            getWorld().addObject(shadowball, getX(), getY());
            shadowball.turnTowards(mouse.getX(), mouse.getY());
            }
        }        
    }
danpost danpost

2020/3/25

#
You need to make sure that there is a MousInfo object to begin with. If no mouse actions are taken between act steps, getMouseInfo will return a null value. So, start line 4 as follows:
if (mouse != null && mouse.getX() > 0 &&
That will prevent the error; however, it will also limit the shooting of shaadowballs. In other words, some mouse action would need to be happening when the "space" key is pressed to fire. Therefore, you will need to either keep track of the location of the mouse by maintaining fields with its coordinates or change the triggering action to a mouse action like a click.
LewisEro LewisEro

2020/3/25

#
adding mouse != null worked perfectly! im not entirely sure what you mean by the second part, but left mouse is already assigned to throwing a boomering currently, which is why i specifically wanted to use space instead for using spells in general. thanks dan
You need to login to post a reply.