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

2013/5/16

help whit shooting

gust.ramos gust.ramos

2013/5/16

#
hi! i have a problem with my project. i have a spaceship, and i need to set 2 differents shoots: one kind of shoot (like a bullet) that kills some kind of enemies (the little ones), and one kind of shoot (like a bomb) that kills other kind of enemies (the big ones). i have two classes of weapons: bullets and bombs, and i need to fire them with different buttons on the keyboard, with the code inside the spaceship actor. in the spaceship´s act method, i´m using a sentence like this if("c".equals(Greenfoot.getKey())){ newBomb(); }else if ("x".equals(Greenfoot.getKey())){ newBullet(); } with the newBomb() and newBullet() methods created in the same class (Spaceship). It compiles, but at the moment of pressing the keys that calls the shoots, only one ot them works. The spaceship fires the weapond that is in the first "if". In this case, at the moment of pressing "c" key, the spaceship shoot a new bomb. But, if i press the "x" key, the ship doesn´t fire the newBullet! And if a put in reversal order the sentence, first the newBullet and after the newBomb, the space fires the newBullet. and there is no newBomb. can you help me please? i´m frustrated with the situation... thanks!! ps: i´m from Chile, and i don´t speak in english very well, so, sorry about the mistakes in the text... sorry!
danpost danpost

2013/5/18

#
The problem with the code is what I have made bold: if("c".equals(Greenfoot.getKey())){ newBomb(); }else if ("x".equals(Greenfoot.getKey())){ newBullet(); } You are calling 'getKey' twice within the same act cycle. The second call will always return 'null'. So, what you need to do is save what is returned the first time in a local field and use its value for comparing.
String key = Greenfoot.getKey();
if("c".equals(key)) newBomb();
if("x".equals(key)) newBullet();
You need to login to post a reply.