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

2021/6/25

Text in Greenfoot?

Jhoffi Jhoffi

2021/6/25

#
How can i add a text to a world, which changes when i press a specific button (for example the space button)? Example: Text shown: Hello World (I press space) Text shown: Goodby World
Gbasire Gbasire

2021/6/25

#
in an actor :
if(Greenfoot.isKeyDown("space"))
    getWorld().showText("Goodbye World", 100, 100);
else
    getWorld().showText("Hello World", 100, 100);
//put any number you want instead of 100
in a world :
if(Greenfoot.isKeyDown("space"))
    showText("Goodbye World", 100, 100);
else
    showText("Hello World", 100, 100);
//put any number you want instead of 100
Jhoffi Jhoffi

2021/6/26

#
but know I have to hold space, and how can I do that with more than 2 text´s ( If i wan´t like "hi world" as a text, too.
Gbasire Gbasire

2021/6/26

#
if you just want to hold space once, do this :
//outside of a method, just in your class
boolean hasPressedSpace = false;
//then, in a method
if(Greenfoot.isKeyDown("space"))
    hasPressedSpace = true;
if(hasPressedSpace)
    getWorld().showText("Goodbye World", 100, 100);
else 
    getWorld().showText("Hello World", 100, 100);
I'm still not sure what you meant by "with more than 2 texts". Please explain with more details
danpost danpost

2021/6/26

#
Jhoffi wrote...
but know I have to hold space, and how can I do that with more than 2 text´s ( If i wan´t like "hi world" as a text, too.
// outside
String[] greeting = { "Hi", "Hello" };
// in world constructor
showText(greeting[Greenfoot.getRandomNumber(2)]+" World", 100, 100);
// in act
if ("space".equals(Greenfoot.getKey()) showText("Goodbye World", 100, 100);
danpost danpost

2021/6/26

#
You could also do it this way:
// outside
String[] salutation = { "Hi", "Hello", "Goodbye" };
// in constructor
salute(Greenfoot.getRandomNumber(2));
// in act
if ("space".equals(Greenfoot.getKey()) salute(2);
// added method
private void salute(int index)
{
    showText(salutation[index]+" World", 100, 100);
}
You need to login to post a reply.