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

2015/5/26

Moving an Object right without changing orientation (arrow keys)

alittle_bit alittle_bit

2015/5/26

#
Hey Guys, Ive startd myself alittlebit of a project which hopefully will end with a 2d RPG maze... thing (not sure on if you get teh idea) but Ive hit an obstacle that involves moving right with teh arrow keys without having to visually turn the 'player'. I want to avoid doing what you do with basic Java using x and y to move the image however it looks to be between that and looking in the Greenfoot library which could be avoided if you guys have any good ideas. Thanks for the help in advance anyways, I see no reason to give teh code since its just the basics but it may help give an idea on what im looking for:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Hero extends Actor
{
    /**
     * Will orientate the player in the correct direction
     */
    public Hero ()
    {
        turn(270);
    }
     
    public void act()
    {
        if (Greenfoot.isKeyDown("Up"))
        {
            move(1);
            Greenfoot.delay(5);
        }
        if (Greenfoot.isKeyDown("Right"))
        {
            move(1);
            Greenfoot.delay(5);
        }
    }   
}
Super_Hippo Super_Hippo

2015/5/26

#
Like this?
1
2
3
4
5
6
int dx=0, dy=0;
if (Greenfoot.isKeyDown("up")) dy--;
if (Greenfoot.isKeyDown("down")) dy++;
if (Greenfoot.isKeyDown("right")) dx++;
if (Greenfoot.isKeyDown("left")) dx--;
if (dx != 0 || dy != 0) setLocation(getX()+dx, getY()+dy);
danpost danpost

2015/5/26

#
If you would rather use 'move' instead of 'setLocation', you will need to incorporate an int field in the class to hold the current direction of the actor;
1
private int direction;
Then, the basic format of your act method would be as follows:
1
2
3
4
5
6
7
public void act()
{
    setRotation(direction);
    turnAndMove(); // do turning and moving (using 'move' method)
    direction = getRotation();
    setRotation(0);
}
This will only have your actor "rotated" behind the scenes. It will always be shown upright.
You need to login to post a reply.