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

2012/2/18

character movement

Nemean Nemean

2012/2/18

#
im trying to move only in the y direction (up and down). This is my code 2 and 3 are for the y movement, 3 is up and 2 is down. 3 works, but its much slower than moving left or right. Also 2 moves in a diagonal.
public void move(int direction)
    {
        
        if (direction == 0)
        {
            int x = (int) Math.round(getX() + Math.cos(0) * WALKING_SPEED);
            int y = (int) Math.round(getY() + Math.sin(0) * WALKING_SPEED);
            setLocation(x, y);
        }
        if (direction == 1)
        {
            int x = (int) Math.round(getX() - Math.cos(0) * WALKING_SPEED);
            int y = (int) Math.round(getY() + Math.sin(0) * WALKING_SPEED);
            setLocation(x, y);
        }
        if (direction == 2)
        {
            int x = (int) Math.round(getX() + Math.cos(.5) * WALKING_SPEED);
            int y = (int) Math.round(getY() + Math.sin(0) * WALKING_SPEED);
            setLocation(y, x);
        }
        if (direction == 3)
        {
            int x = (int) (Math.round(getX() + Math.cos(0) * WALKING_SPEED)) + ((int) (Math.round(getX() - Math.cos(0) * WALKING_SPEED)));
            int y = (int) (Math.round(getY() - Math.sin(1) * WALKING_SPEED)) + ((int) Math.round(getY() + Math.sin(0) * WALKING_SPEED));
            x = (x/2);
            y = (y/2);
            setLocation(x, y);
        }
    }
danpost danpost

2012/2/18

#
If your actor is only to move 'up' and 'down', then you do not need to use all this code with Math functions and all. Even if you have it as a sub-class of Mover, you do not have to utilize this code. I threw this code together, controlling the direction with the arrow keys
        int dx = 0, dy = 0;
        if (Greenfoot.isKeyDown("up")) dy -= WALKING_SPEED;
        if (Greenfoot.isKeyDown("down")) dy += WALKING_SPEED;
//         if (Greenfoot.isKeyDown("left")) dx -= WALKING_SPEED;
//         if (Greenfoot.isKeyDown("right")) dx += WALKING_SPEED;
        setLocation(getX() + dx, getY() + dy);
which would suffice for a simple up/down motion. Just put it in your actor's act method.
You need to login to post a reply.