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

2012/10/15

Movement using 'x' and 'y'

Penguins_and_Orbs Penguins_and_Orbs

2012/10/15

#
I want to make my character move using 'x' and 'y', so pressing the left key changes 'x' by -5 for example. I think my problem is the fact that it doesn't recognise 'x' and 'y' as coordinates, so changing them does nothing. (I also want him to switch images as he walks, but I think that part's okay). My script so far goes as follows: import greenfoot.*; public class Character extends Actor { private GreenfootImage Image1; private GreenfootImage Image2; private GreenfootImage Image3; private GreenfootImage Image4; private int y; private int x; public Character() { Image1 = new GreenfootImage("Right Hand Backwards.png"); Image2 = new GreenfootImage("Right Hand Forward.png"); Image3 = new GreenfootImage("Left Hand Forward.png"); Image4 = new GreenfootImage("Left Hand Backwards.png"); setImage(Image1); } /** * Act - do whatever the Character wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { switchImage(); checkKeyPress(); checkKeyPress2(); } public void switchImage() //Alternates the images, making the Character more realistic. { } public void checkKeyPress() { if (Greenfoot.isKeyDown("up")) { y=y+5; } if (Greenfoot.isKeyDown("right")) { setImage (Image2); x=x+5; } else { setImage(Image3); } } public void checkKeyPress2() { if (Greenfoot.isKeyDown("left")) { setImage (Image1); x=x-5; } else { setImage(Image4); } if (Greenfoot.isKeyDown("down")) { y=y-5; } } } Thanks.
MatheMagician MatheMagician

2012/10/15

#
You are right, changing x and y does not change the location of the actor. However, you could just put this code at the end of you act cycle:
setLocation(x,y);
Penguins_and_Orbs Penguins_and_Orbs

2012/10/15

#
Thanks! He is now moving, could I ask you how I would alternate the images as I hold down a key? For example, I hold down 'Right' and he switches legs as he moves along. It turns out my code isn't working for that.
MatheMagician MatheMagician

2012/10/15

#
I'm not sure about that one. Your code for it looks fine to me.
Penguins_and_Orbs Penguins_and_Orbs

2012/10/15

#
Okay no worries, thanks for helping with the movement, that was the main bit.
Upupzealot Upupzealot

2012/10/15

#
try this
int PicNum = 0;
public void switchImage() //Alternates the images,making the Character more realistic.
{
    if(PicNum == 0)
    setImage(Image1);
    if(PicNum == 1)
    setImage(Image2);
    if(PicNum == 2)
    setImage(Image3);
    if(PicNum == 3)
    setImage(Image4);
    
    PicNum++;
    if(PicNum = 4)
    PicNum = 1;
}
then call this method in act();
You need to login to post a reply.