I want to write text on the screen for my game, for things like fps, random text for items and stuff. How can I write that text?
Is it possible without the Basic Game class? Isn't there a command like this g.drawString("Hello World", 100, 100);
?
I want to write text on the screen for my game, for things like fps, random text for items and stuff. How can I write that text?
Is it possible without the Basic Game class? Isn't there a command like this g.drawString("Hello World", 100, 100);
?
Update: this answer is now outdated, and does not work at all with the latest versions of LWJGL. Until I update this answer fully, I recommend that you look here: https://jvm-gaming.org/t/lwjgl-stb-bindings/54537
You could use the TrueType fonts feature in the Slick-util library.
Using a common font is easy, just create the font like this:
TrueTypeFont font;
Font awtFont = new Font("Times New Roman", Font.BOLD, 24); //name, style (PLAIN, BOLD, or ITALIC), size
font = new TrueTypeFont(awtFont, false); //base Font, anti-aliasing true/false
If you want to load the font from a .ttf
file, it's a little more tricky:
try {
InputStream inputStream = ResourceLoader.getResourceAsStream("myfont.ttf");
Font awtFont = Font.createFont(Font.TRUETYPE_FONT, inputStream);
awtFont = awtFont.deriveFont(24f); // set font size
font = new TrueTypeFont(awtFont, false);
} catch (Exception e) {
e.printStackTrace();
}
After you have successfully created a TrueTypeFont
, you can draw it like this:
font.drawString(100, 50, "ABC123", Color.yellow); //x, y, string to draw, color
For more information, you can look at the documentation for TrueTypeFont
and java.awt.Font
, and the Slick-Util tutorial I got most of this code from.
Try Making a BufferedImage
of required size. Then get its Graphics and draw a String. Then Convert it to a ByteBuffer
and render it in OpenGL
.
String text = "ABCD";
int s = 256; //Take whatever size suits you.
BufferedImage b = new BufferedImage(s, s, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g = b.createGraphics();
g.drawString(text, 0, 0);
int co = b.getColorModel().getNumComponents();
byte[] data = new byte[co * s * s];
b.getRaster().getDataElements(0, 0, s, s, data);
ByteBuffer pixels = BufferUtils.createByteBuffer(data.length);
pixels.put(data);
pixels.rewind();
Now pixels
contains the required Image data you need to draw.
Use GL11.glTexImage2D()
function to draw the byte buffer.
glTexImage2D()
in this case? –
Radiocommunication glTexImage2D()
in this case? –
Radiocommunication © 2022 - 2024 — McMap. All rights reserved.
drawString()
type method, which implies you want simplicity - JMonkey will make things simpler in this respect (and many others). – Aery