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

2013/5/6

Character Movement

Hawx_ Hawx_

2013/5/6

#
Can anyone help? I'm trying to make a character move up, down, left and right but I don't know the code for up and down. I'd like the character to always be of the same rotation. Here's the code I'm using at the moment :
    public void movement()
    {
        iif(Greenfoot.isKeyDown("right"))
        {
            move (3);
        }
        if(Greenfoot.isKeyDown("left"))
        {
            move (-3);
        }
        if(Greenfoot.isKeyDown("up"))
        
        //Here's where I'm stuck
        {
            move;
        }
    }    
Thanks, Hawx
holla holla

2013/5/6

#
If you just want to move an Object, without rotating the image, just use this:
setLocation(int x, int y) ;
With your example:
if(Greenfoot.isKeyDown("up"))  
      
    //Here's where I'm stuck  
    {  
      y = y - 1;  // -1 is for how far the object should move
       setLocation(x, y) ;
    }  
Hawx_ Hawx_

2013/5/6

#
I'm applying this to my class above and it's saying ".class expected" ??
  if(Greenfoot.isKeyDown("up"))
        {
            setLocation(int 0, int 3) ; 
        }
danpost danpost

2013/5/6

#
Here are a couple ways to fix the movement so that all four directions are accounted for. The first is as follows:
public void movement()
{
    if(Greenfoot.isKeyDown("right")) move(3);
    turn(90);
    if(Greenfoot.isKeyDown("down")) move(3);
    turn(90);
    if(Greenfoot.isKeyDown("left")) move(3);
    turn(90);
    if(Greenfoot.isKeyDown("up")) move(3);
    turn(90);
}
By the end of the method, the actor is back in its proper rotation (none) with no visible sign of it turning at all. The other way is to use the 'setLocation' method instead of 'move'
public void movement()
{
    if(Greenfoot.isKeyDown("right")) setLocation(geX()+3, getY());
    if(Greenfoot.isKeyDown("left")) setLocation(getX()-3, getY());
    if(Greenfoot.isKeyDown("down")) setLocation(getX(), getY()+3);
    if(Greenfoot.isKeyDown("up")) setLocation(getX() getY()-3);
}
holla holla

2013/5/6

#
Yeah, you need to remove the both int like so:
 if(Greenfoot.isKeyDown("up"))  
      {  
          setLocation(0,3) ;   
      }  
Now, if you want a dynamic version, do it like this:
     if(Greenfoot.isKeyDown("up"))  
      {  
          int x = getX();
          int y = getY();
          int ny = getY()-1;
          setLocation(x,ny) ;   
      }  
Hawx_ Hawx_

2013/5/6

#
Thanks Holla and Danpost :D
You need to login to post a reply.