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

2014/12/17

PROBLEMS with using keys to control an actor

lionkitten lionkitten

2014/12/17

#
New to Greenfoot! Please help! import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Player here. * * @author (your name) * @version (a version number or a date) */ public class Player extends Actor { /** * Act - do whatever the Player wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act () { move(); lookForFlag(); checkKeyPress(); } public void move() { if ( Greenfoot.getRandomNumber(100) < 10 ) { turn(5); } } public void lookForFlag() { if (canSee(Flag.class)) { eat(Flag.class); } } public void checkKeyPress() { int speed = 3; if(Greenfoot.isKeyDown("up")) setLocation(getX(), getY() - speed); if(Greenfoot.isKeyDown("down")) setLocation(getX(), getY() + speed); if(Greenfoot.isKeyDown("left")) setLocation(getX() - speed, getY()); if(Greenfoot.isKeyDown("right")) setLocation(getX() + speed, getY()); } }
danpost danpost

2014/12/17

#
I do not see any problems with the code as far as the actor moving by key press. What looks funny is that you are having the rotation of the image of the actor randomly change by the implementation of the 'move' method.
fejfo fejfo

2014/12/17

#
I don't if it is the problem but in check key press you're if don't have { } try this : public void checkKeyPress() { int speed = 3; if(Greenfoot.isKeyDown("up")) { setLocation(getX(), getY() - speed); } if(Greenfoot.isKeyDown("down")) { setLocation(getX(), getY() + speed); } if(Greenfoot.isKeyDown("left")) { setLocation(getX() - speed, getY()); } if(Greenfoot.isKeyDown("right")) { setLocation(getX() + speed, getY()); } }
You need to login to post a reply.