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

2016/12/13

How to make the actor move differently depending on where the mouse is

AuroraGamer AuroraGamer

2016/12/13

#
So I'm working on a game that would use mouse or keyboard input to control the character. I have the keyboard input. In other games where I've used both I just have the actor turn towards the location of the mouse, but that won't work for this game. I have for seperate gif files, one walking left, right, away (moving up the screen) and forwards (moving down the screen). I tried to just use an if statement;
if (mi.getX() >= getX())
{
move(5);
setImage(right.getCurrentImage());
}
and have one of those for each direction, but that didn't seem to work, so I was hoping somebody could help me out.
danpost danpost

2016/12/13

#
In order to have any consistent animation, you must restrict movement to one of the four ordinal directions (E, S, W or N). The major issue then is what to do when the mouse is at or near halfway between two adjacent directions (SE, SW, NW or NE). You do not want the animation to flicker between two different gifs; or the actor to face in one of the ordinal directions while moving diagonally (just would not look right). I would suggest breaking up the possible angles that can be moved in (if the mouse is in an in-between area, the actor will not move). This can be done by first getting the angle toward the mouse (either the latest non-null MouseInfo object should be saved or the last know location should be). Then, after checking to see if the mouse is at least 5 cells away, determine if the angle is within 22 degrees of an ordinal angle before moving:
// determining direction
int mX = mi.getX();
int mY = mi.getY();
int rotation = getRotation();
turnTowards(mX, mY);
int angle = getRotation();
setRotation(rotation);
int direction = 0;
if ((angle+22)%90 > 45)
{
    direction = ((angle+22)/90)%4; // 0=East, 1=South, 2=West, 3=North
    // move and animate here
}
.
You need to login to post a reply.