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

2015/12/28

Motion problems with actor

kimberlmao kimberlmao

2015/12/28

#
Help, I have a homework in school to make my actor move up, down, left and right. I have been trying codes of mirroring the image and changing the X and Y coordinates, and so far I have 2 problems: 1) I do not want my actor to move Northeast/Northwest, Southeast/Southwest, but it keeps on moving that way whenever I press the up/down key; 2) My actor keeps on flipping when I press the up/down/left/right, even if I have the getImage().mirrorHorizontally/Vertically() code. How do I solve this problem? Can anyone help me? Thanks. :) (Here's my code, btw if you need it)
        if (Greenfoot.isKeyDown("right"))
        {
            getImage().mirrorHorizontally();
            setLocation(getX()+1, getY());
            move(1);
        }
        if (Greenfoot.isKeyDown("left"))
        {
            setLocation(getX()-1, getY());
            move(-1);
        }
        if (Greenfoot.isKeyDown("up"))
        {
            getImage().mirrorVertically();
            setLocation(getX(), getY()-1);
            move(1);
        }
        if (Greenfoot.isKeyDown("down"))
        {
            getImage().mirrorVertically();
            setLocation(getX(), getY()+1);
            move(-1);
        }
danpost danpost

2015/12/29

#
With the code given as above, while any key is down, each act cycle it remains down will cause the image to mirror itself (a mirrored image that is mirrored becomes the original image -- hence the switching back and forth). Your diagonal movement while up/down is used is due to both 'setLocation' and 'move' movement commands being used together; in this case, use 'setLocation' only. You can replace secondary 'if' commands with 'else if' to prevent 'up' or 'down' with 'left' or 'right' from moving the actor diagonally. For the image issue, save the two images used in fields so you can set the proper ones with the 'left' and 'right' keys:
private GreenfootImage rightImage;
private GreenfootImage leftImage;

// in constructor of class
rightImage = getImage();
leftImage = new GreenfootImage(rightImage);
leftImage.mirrorHorizontally();
Then you can use 'setImage(rightImage)', 'setImage(leftImage)', 'setRotation(0)' and 'setRotation(90)' with the key checking code.
kimberlmao kimberlmao

2015/12/29

#
Thank you! :)
You need to login to post a reply.