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

2020/3/23

adding omnidirectional attack animation

LewisEro LewisEro

2020/3/23

#
Hey, I want my character to attack into the direction of a mouse click and momentarily change his sprite to the corresponding attacking sprite (i named them upHit.png, downHit.png etc.). The pasted code is working, but only for 2 opposing directions at the time, in this case up and down. I think I understand why, which would mean this approach would probably not work, to begin with. I had another idea of dissecting the area around the player into 4 45 degree angles and working with that, not quite sure how that would be implemented though. Maybe the current approach would work but with a few more conditions?
    private void attackAnimation(){
        MouseInfo mouse = Greenfoot.getMouseInfo();
        if(Greenfoot.mouseClicked(getWorld())){
             if(getX() < mouse.getX()){
                 setImage("rightHit.png");
             }
             else setImage("leftHit.png");             
        }
        if(Greenfoot.mouseClicked(getWorld())){
             if(getY() < mouse.getY()){
                 setImage("downHit.png");
             }
             else setImage("upHit.png");             
        }
    }
RcCookie RcCookie

2020/3/23

#
Hello Lewis, the problem with your code is that if the mouse is clicked at all both if-statements will be true. That means that the image is first being set to left or right but immediatly after that to up or down. Try this one:
private void attackAnimation(){
    MouseInfo mouse = Greenfoot.getMouseInfo();
    if(Greenfoot.mouseClicked(getWorld())){
        if(getX()>mouse.getX()){
            if(getY()>mouse.getY()){
                if(mouse.getX()-getX()>mouse.getY()-getY()) setImage("hitRight.png");
                else setImage("hitDown.png");
            }
            else{
                if(mouse.getX()-getX()>getY()-mouse.getY()) setImage("hitRight.png");
                else setImage("hitUp.png");
            }
        }
        else{
            if(getY()>mouse.getY()){
                if(getX()-mouse.getX()>mouse.getY()-getY()) setImage("hitLeft.png");
                else setImage("hitDown.png");
            }
            else{
                if(getX()-mouse.getX()>getY()-mouse.getY()) setImage("hitLeft.png");
                else setImage("hitUp.png");
            }
        }
    }
}
Also, you may want to put a try/catch statement around that code block as it will throw an error if the mouse is outsite of the screen. RcCookie
You need to login to post a reply.