To add gravity to your 3D environment, you'll typically want to incorporate a simple physics simulation that updates the camera's position over time. This involves simulating gravitational acceleration and updating the vertical position accordingly.
Here’s a basic implementation of gravity:
-
Define Gravity Variables: Create variables that define gravity, vertical velocity, and whether the camera is in the air.
-
Physics Update Function: Create a function to update the camera's position based on gravity.
-
Modify the Main Loop: Call this physics update function every frame to simulate the effect of gravity.
Here's how you can integrate these steps into your existing code:
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;
import java.nio.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.stb.STBImage.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
public class Main {
private long window;
private int width = 800;
private int height = 600;
private int textureID;
// Camera and movement parameters
private float posX = gridSize / 2.0f, posZ = gridSize / 2.0f;
private float posY = gridSize + 2.0f;
private float yaw = 0.0f;
private float pitch = -45.0f;
private float speed = 0.1f;
// Gravity parameters
private float gravity = -0.05f;
private float verticalVelocity = 0.0f;
private boolean isJumping = false;
// Mouse settings
private double lastMouseX = width / 2.0;
private double lastMouseY = height / 2.0;
private boolean firstMouse = true;
private boolean dragging = false;
// Grid parameters
private static final int gridSize = 16;
private static final float blockSize = 1.0f;
private static final float groundLevel = gridSize + 2.0f;
public static void main(String[] args) {
new Main().run();
}
public void run() {
init();
loop();
glfwFreeCallbacks(window);
glfwDestroyWindow(window);
glfwTerminate();
glfwSetErrorCallback(null).free();
}
private void init() {
GLFWErrorCallback.createPrint(System.err).set();
if (!glfwInit())
throw new IllegalStateException("Unable to initialize GLFW");
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
window = glfwCreateWindow(width, height, "16x16x16 Block Grid", NULL, NULL);
if (window == NULL)
throw new RuntimeException("Failed to create the GLFW window");
glfwSetFramebufferSizeCallback(window, (window, newWidth, newHeight) -> {
this.width = newWidth;
this.height = newHeight;
glViewport(0, 0, width, height);
updateProjection();
});
glfwSetCursorPosCallback(window, (window, xpos, ypos) -> {
if (dragging) {
if (firstMouse) {
lastMouseX = xpos;
lastMouseY = ypos;
firstMouse = false;
}
double xOffset = xpos - lastMouseX;
double yOffset = lastMouseY - ypos; // This line originally reversed
lastMouseX = xpos;
lastMouseY = ypos;
float sensitivity = 0.1f;
yaw += xOffset * sensitivity; // Inverted yaw control
pitch += yOffset * sensitivity; // Inverted pitch control
if (pitch > 89.0f) pitch = 89.0f;
if (pitch < -89.0f) pitch = -89.0f;
}
});
glfwSetMouseButtonCallback(window, (window, button, action, mods) -> {
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
dragging = !dragging;
glfwSetInputMode(window, GLFW_CURSOR, dragging ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL);
firstMouse = true;
}
});
glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
dragging = false;
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS && !isJumping) {
verticalVelocity = 0.2f; // Initial jump velocity
isJumping = true;
}
});
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwShowWindow(window);
GL.createCapabilities();
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
textureID = loadTexture("src/minecraft_block.png");
updateProjection();
}
private int loadTexture(String filePath) {
if (!Files.exists(Paths.get(filePath))) {
throw new RuntimeException("Texture file not found: " + filePath);
}
try (MemoryStack stack = stackPush()) {
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
IntBuffer comp = stack.mallocInt(1);
stbi_set_flip_vertically_on_load(true);
ByteBuffer image = stbi_load(filePath, w, h, comp, 4);
if (image == null) {
throw new RuntimeException("Failed to load texture file: " + stbi_failure_reason());
}
int textureID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w.get(), h.get(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
stbi_image_free(image);
return textureID;
}
}
private void updateProjection() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float aspectRatio = (float) width / height;
float fov = 45.0f;
float near = 0.1f;
float far = 1000.0f;
float top = (float) Math.tan(Math.toRadians(fov / 2)) * near;
float bottom = -top;
float left = bottom * aspectRatio;
float right = top * aspectRatio;
glFrustum(left, right, bottom, top, near, far);
glMatrixMode(GL_MODELVIEW);
}
private void loop() {
while (!glfwWindowShouldClose(window)) {
processInput();
applyGravity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Calculate the camera direction based on yaw and pitch
float cosYaw = (float) Math.cos(Math.toRadians(yaw));
float sinYaw = (float) Math.sin(Math.toRadians(yaw));
float cosPitch = (float) Math.cos(Math.toRadians(pitch));
float sinPitch = (float) Math.sin(Math.toRadians(pitch));
float lookX = cosYaw * cosPitch;
float lookY = sinPitch;
float lookZ = sinYaw * cosPitch;
gluLookAt(posX, posY, posZ, posX + lookX, posY + lookY, posZ + lookZ, 0.0f, 1.0f, 0.0f);
glBindTexture(GL_TEXTURE_2D, textureID);
renderGrid();
glfwSwapBuffers(window);
glfwPollEvents();
}
}
private void processInput() {
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
posX += speed * Math.cos(Math.toRadians(yaw));
posZ += speed * Math.sin(Math.toRadians(yaw));
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
posX -= speed * Math.cos(Math.toRadians(yaw));
posZ -= speed * Math.sin(Math.toRadians(yaw));
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { // Swapped with A
posX -= speed * Math.sin(Math.toRadians(yaw));
posZ += speed * Math.cos(Math.toRadians(yaw));
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { // Swapped with D
posX += speed * Math.sin(Math.toRadians(yaw));
posZ -= speed * Math.cos(Math.toRadians(yaw));
}
}
private void applyGravity() {
if (posY > groundLevel) {
verticalVelocity += gravity;
posY += verticalVelocity;
} else {
posY = groundLevel;
verticalVelocity = 0;
isJumping = false;
}
}
private void renderGrid() {
for (int x = 0; x < gridSize; x++) {
for (int y = 0; y < gridSize; y++) {
for (int z = 0; z < gridSize; z++) {
glPushMatrix();
glTranslatef(x * blockSize, y * blockSize, z * blockSize);
renderBlock();
glPopMatrix();
}
}
}
}
private void renderBlock() {
glBegin(GL_QUADS);
// Front Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(blockSize, 0.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(blockSize, blockSize, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(0.0f, blockSize, 0.0f);
// Back Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(0.0f, 0.0f, blockSize);
glTexCoord2f(1.0f, 0.0f); glVertex3f(blockSize, 0.0f, blockSize);
glTexCoord2f(1.0f, 1.0f); glVertex3f(blockSize, blockSize, blockSize);
glTexCoord2f(0.0f, 1.0f); glVertex3f(0.0f, blockSize, blockSize);
// Top Face
glTexCoord2f(0.0f, 1.0f); glVertex3f(0.0f, blockSize, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(blockSize, blockSize, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(blockSize, blockSize, blockSize);
glTexCoord2f(1.0f, 1.0f); glVertex3f(0.0f, blockSize, blockSize);
// Bottom Face
glTexCoord2f(1.0f, 1.0f); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(blockSize, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(blockSize, 0.0f, blockSize);
glTexCoord2f(1.0f, 0.0f); glVertex3f(0.0f, 0.0f, blockSize);
// Right Face
glTexCoord2f(1.0f, 0.0f); glVertex3f(blockSize, 0.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(blockSize, blockSize, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(blockSize, blockSize, blockSize);
glTexCoord2f(0.0f, 0.0f); glVertex3f(blockSize, 0.0f, blockSize);
// Left Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(0.0f, blockSize, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(0.0f, blockSize, blockSize);
glTexCoord2f(0.0f, 1.0f); glVertex3f(0.0f, 0.0f, blockSize);
glEnd();
}
private void gluLookAt(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
float[] f = new float[3];
float[] up = new float[3];
float[] s = new float[3];
float[] u = new float[3];
f[0] = centerX - eyeX;
f[1] = centerY - eyeY;
f[2] = centerZ - eyeZ;
normalize(f);
up[0] = upX;
up[1] = upY;
up[2] = upZ;
normalize(up);
s[0] = f[1] * up[2] - f[2] * up[1];
s[1] = f[2] * up[0] - f[0] * up[2];
s[2] = f[0] * up[1] - f[1] * up[0];
normalize(s);
u[0] = s[1] * f[2] - s[2] * f[1];
u[1] = s[2] * f[0] - s[0] * f[2];
u[2] = s[0] * f[1] - s[1] * f[0];
buffer.put(new float[]{
s[0], u[0], -f[0], 0,
s[1], u[1], -f[1], 0,
s[2], u[2], -f[2], 0,
0, 0, 0, 1
});
buffer.flip();
glMultMatrixf(buffer);
glTranslatef(-eyeX, -eyeY, -eyeZ);
}
private void normalize(float[] vector) {
float length = (float) Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2]);
if (length != 0) {
vector[0] /= length;
vector[1] /= length;
vector[2] /= length;
}
}
}
Key Changes:
- Gravity Variables: Added
gravity, verticalVelocity, and isJumping to manage the camera's vertical movement.
- Jumping Mechanism: Introduced a space key check to initiate a jump by setting an initial upward velocity.
applyGravity Function: Updates the camera's vertical position based on the current velocity and applies gravity. If the camera reaches the ground, it stops falling and resets jump-related variables.
This simple gravity simulation will allow your camera to fall until it reaches the ground level defined by groundLevel. You can adjust the gravity and initial jump velocity to fine-tune the effect to your liking.