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

2013/12/14

I'm a horrible programmer

Lethal_Vitamin Lethal_Vitamin

2013/12/14

#
My Scenario There is ABSOLUTELY no reason why the man can not move in all 4 directions.
davmac davmac

2013/12/14

#
Is that supposed to be a question? Your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if ("w".equals(Greenfoot.getKey())) {
      setLocation(getX(), getY() - 1);
  }
 
  if ("s".equals(Greenfoot.getKey())) {
      setLocation(getX(), getY() + 1);
  }
 
  if ("d".equals(Greenfoot.getKey())) {
      setLocation(getX() + 1, getY());
  }
 
  if ("a".equals(Greenfoot.getKey())) {
      setLocation(getX() - 1, getY());
  }
Seeing as calling Greenfoot.getKey() actually consumes the key, you'll never see the 's', 'd' or 'a' keys with this code. Call Greenfoot.getKey() once, save the value in a variable, and then test for the values you are interested in.
davmac davmac

2013/12/14

#
Documentation for getKey method: "Get the most recently pressed key, since the last time this method was called. If no key was pressed since this method was last called, it will return null."
Lethal_Vitamin Lethal_Vitamin

2013/12/14

#
Sorry. What exactly do you mean by "consumes"?
Lethal_Vitamin Lethal_Vitamin

2013/12/14

#
Mmm, I get it now. I appreciate you taking the time to help all of us newbies.
danpost danpost

2013/12/14

#
It means that the method 'getKey' acts like a buffer. Once you get a key from it, it no longer holds that value. Think of it like this:
1
2
3
4
5
6
7
List<String> enteredKeys = new ArrayList<String>(); // this is a list to hold the individually keystrokes in the order that they are entered
 
public String getKey()
{
    if (enteredKeys.isEmpty()) return null; // if the list is empty, return a 'null' value
    return enteredKeys.remove(0); // otherwise, remove and return the first element in the list
}
Since the element is no longer in the list, it cannot be retrieved again by calling 'getKey' again.
You need to login to post a reply.