A journey from a simple class to a game with the Java language https://mcgivrer.github.io/fromClassToGame/ , and open Hub https://www.openhub.net/p/fromClassToGame.
The TextObject
will be used to display text on screen. Starting from a standard GameObject
, we just have to add 2
more properties:
As we have already done for the GameObject, we will add as Fluent API a setFont(Font)
and a setText(String)
to the
existing one.
public class TextObect extends GameObject {
public Font font;
public String text;
public TextObject(String name, double x, double y) {
super(name, x, y);
}
public TextObject setFont(Font font) {
this.font = font;
return this;
}
public TextObject setText(String text) {
this.text = text;
return this;
}
}
The Render.draw(Graphics,GameObject)
must be modified to let it renderer the TextObject
. In a first run, we will use a
simple if to capture the nature of the object to be rendered:
public class Render {
//...
private void draw(Graphics2D g, GameObject go) {
String goClazzName = go.getClass().getName();
// rendering the already existing GameObject
if (GameObject.class.getName().equals(goClazzName)) {
// rendering the new TextObject
} else if (TextObject.class.getName().equals(goClazzName)) {
TextObject to = (TextObject) go;
g.setColor(to.color);
g.setFont(to.font);
g.drawString(to.text, (int) (to.x), (int) (to.y));
}
}
//...
}
You just have to create a Text Object and add is to the Game objects list:
import fr.snapgames.fromclasstogame.core.scenes.AbstractScene;
class DemoScene extends AbstractScene {
//...
public void create() {
//...
InputStream is = Game.class.getClassLoader().getResourceAsStream("fonts/FreePixel.ttf");
Font textFont = Font.createFont(Font.TRUETYPE_FONT, is);
TextObject text = new TextObject("text", 10, 10)
.setText("Sample from class to game")
.setFont(textFont);
add(text);
//...
}
//...
}
TIPS
The TextObject is verified by the feature Game_can_render_multiple_objects.feature.