FreshRSS

Normální zobrazení

Jsou dostupné nové články, klikněte pro obnovení stránky.
PředevčíremHlavní kanál
  • ✇Recent Questions - Game Development Stack Exchange
  • keyPressed is not working after adding ActionListener to JButtonYehonatan
    I have a serious problem while trying to build a menu for my game. I've added two JButton to a main JPanel and added an ActionListener for each of them. The main JPanel also contains the game JPanel which have the keyPressed method inside keyController. That's how it looks - Main ->       JPanel ->         JButton, JButton,         JPanel which contains the game and keyPressed function inside KeyController class which worked fine before I added the ActionListener for JButton. For some
     

keyPressed is not working after adding ActionListener to JButton

I have a serious problem while trying to build a menu for my game. I've added two JButton to a main JPanel and added an ActionListener for each of them. The main JPanel also contains the game JPanel which have the keyPressed method inside keyController.

That's how it looks -
Main ->
      JPanel ->
        JButton, JButton,
        JPanel which contains the game and keyPressed function inside KeyController class which worked fine before I added the ActionListener for JButton.

For some reason after I added an ActionListener for each of the button, the game JPanel is not getting any keyPreseed events nor KeyRealesed.

Does anyone know the solution for my situation?
Thank you very much!

Main window -

  Scanner in = new Scanner(System.in);

    JFrame f = new JFrame("Square V.S Circles");
    f.setUndecorated(true);
    f.setResizable(false);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);


    f.add(new JPanelHandler());
    f.pack();

    f.setVisible(true);
    f.setLocationRelativeTo(null);

JPanelHandler(main JPanel) -

  super.setFocusable(true);


        JButton mybutton = new JButton("Quit");
        JButton sayhi = new JButton("Say hi");

        sayhi.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Hi");
        }
        });      

         mybutton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e)
        {
           System.exit(0);
        }
        });      
        add(mybutton);
        add(sayhi);
        add(new Board(2));

Board KeyController(The code inside is working so it's unnecessary to put it here) -

private class KeyController extends KeyAdapter {


    public KeyController()
    {
        ..Code
    }


    @Override
    public void keyPressed(KeyEvent e) {

    ...Code

    }

    @Override
    public void keyReleased(KeyEvent e){

     ...Code

    }


}
  • ✇Recent Questions - Game Development Stack Exchange
  • How do I fix java.lang.ClassNotFoundException: org.lwjgl.glfw.GLFWDoggo4
    I have not used Java in a while and thought I might try LWJGL with OpenGL and GLFW. I am using Apache Maven as a Build System. It lets me compile the program, but when I run it, it says: Exception in thread "main" java.lang.NoClassDefFoundError: org.lwjgl/glfw/GLFW at com.OpenGLTest.app.Main.main(Main.java:25) Caused by: java.lang.ClassNotFoundException: org.lwjgl.glfw.GLFW at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java.641) at java.base/jdk.int
     

How do I fix java.lang.ClassNotFoundException: org.lwjgl.glfw.GLFW

I have not used Java in a while and thought I might try LWJGL with OpenGL and GLFW. I am using Apache Maven as a Build System. It lets me compile the program, but when I run it, it says:

Exception in thread "main" java.lang.NoClassDefFoundError: org.lwjgl/glfw/GLFW
    at com.OpenGLTest.app.Main.main(Main.java:25)
Caused by: java.lang.ClassNotFoundException: org.lwjgl.glfw.GLFW
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java.641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:525)
    ... 1 more

My code is:

// Main.java
package com.OpenGLTest.app;

import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;

import java.nio.*;

import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;

public class Main {

  private static long window;
  private static final int WIDTH = 800;
  private static final int HEIGHT = 600;
  private static final String TITLE = "OpenGL Window";

  public static void main(String[] args) {
    // CHECK
    if (!glfwInit()) {
      System.err.println("ERROR: GLFW IS NOT INSTALLED");
      System.exit(-1);
    }
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    glfwWindowHint(GLFW_VISIBLE, 0);
    glfwWindowHint(GLFW_RESIZABLE, 0);

    window = glfwCreateWindow(WIDTH, HEIGHT, TITLE, NULL, NULL);
    if (window == NULL) {
      System.err.println("ERROR: FAILED TO CREATE GLFW WINDOW");
    }

    glfwMakeContextCurrent(window);

    glfwShowWindow(window);
  }
}

My LWJGL version is 3.3.3 My JRE is 17

I am sorry if the answer is obvious. Somehow the only kinda answer I found on the internet is http://forum.lwjgl.org/index.php?topic=6994.0:

https://stackoverflow.com/questions/34413/why-am-i-getting-a-noclassdeffounderror-in-java

How to solve this entirely depends on how you invoke the java command, whether you use an >IDE and which one you use, whether you use the Java 9+ Module System or the classpath and >whether you use a Java build system (like Maven, Gradle, Ant+Ivy).

libGDX using Stage and Actor produces different camera angles on desktop and Android Phone

libGDX using Stage and Actor produces different camera angles on desktop and Android Phone.

Here are pictures demonstrating the problem: http://brandonyuh.minus.com/mFpdTSgN17VUq

On the desktop version, the image takes up most all the screen. On the Android phone it only takes up a bit of the screen.

Here's the code (not my actual project but I isolated the problem):

package com.me.mygdxgame2;
import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.scenes.scene2d.*;
public class MyGdxGame2 implements ApplicationListener {
    private Stage stage;
    public void create() {
        stage = new Stage();
        stage.addActor(new ActorHi());
    }
    public void render() {
        Gdx.gl.glClearColor(0, 1, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.draw();
    }
    public void dispose() {}
    public void resize(int width, int height) {}
    public void pause() {}
    public void resume() {}
    public class ActorHi extends Actor {
        private Sprite sprite;
        public ActorHi() {
            Texture texture = new Texture(Gdx.files.internal("data/hi.png"));
            texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
            sprite = new Sprite(new TextureRegion(texture, 0, 0, 128, 128));
            sprite.setBounds(0, 0, 300.0f, 300.0f);
        }
        public void draw(SpriteBatch batch, float parentAlpha) {
            sprite.draw(batch);
        }
    }
}

Why does this happen?

Collision avoidance and perching behaviour for Boids in a Voxel game

I am currently trying to figure out how to efficiently detect collisions in combination with a boid simulation in a 3D Minecraft clone written in java.

For single entities i already implemented a box collider implementation which checks against nearby voxels, but for hundreds to thousands of boids this seems like a huge overhead. As boids tend to stick together i believe there might be a better approach than checking every single boid in the flock if it collides.

I was thinking about precomputing a signed distance field for each voxel. This could then be used by the boids to sample if they need to steer away from any obstacles. (Resulting in more of a collision avoidance).

The issue i am trying to solve is how to implement perching for boids. I would like my boids to land on the ground from time to time. I am not sure if this is even possible using only an SDF.

  • ✇Recent Questions - Game Development Stack Exchange
  • Connecting bodies together in jbox2dZiv the fire
    Im trying to connect bodies together to make some sort of a "building" system or more specifically im trying to make multiple "blocks" connect to eachother but Struggling to figure out what's the best method to do it I tried using joints (created a jointDef and a joint) but I have no idea how. I can make a single large body but I want different parts of the body to have different friction values
     

Connecting bodies together in jbox2d

Im trying to connect bodies together to make some sort of a "building" system or more specifically im trying to make multiple "blocks" connect to eachother but Struggling to figure out what's the best method to do it I tried using joints (created a jointDef and a joint) but I have no idea how. I can make a single large body but I want different parts of the body to have different friction values

  • ✇Recent Questions - Game Development Stack Exchange
  • Jbox2d simulation runs slowlyZiv the fire
    I wanted to use jbox2d for my project but I have a issue the physics simulation is running very slowly I tried to change game loops and it did not run any faster the best solution I found is still like half the speed it should be game loop code (FPS = 60): double drawInterval = 1000000000/FPS; double delta = 0; long lastTime = System.nanoTime(); long currentTime; while(thread != null) { currentTime = System.nanoTime(); delta+= (currentTime-lastTime)/drawInte
     

Jbox2d simulation runs slowly

I wanted to use jbox2d for my project but I have a issue the physics simulation is running very slowly I tried to change game loops and it did not run any faster the best solution I found is still like half the speed it should be

game loop code (FPS = 60):

    double drawInterval = 1000000000/FPS;
    double delta = 0;
    long lastTime = System.nanoTime();
    long currentTime;
    while(thread != null) {
        currentTime = System.nanoTime();


        delta+= (currentTime-lastTime)/drawInterval;


        float md = (float) (delta/1000000.0);

        lastTime = currentTime;

        if(delta >= 1) {
            world.step((float)delta ,8,3);

            tick(delta);
            System.out.println("e");
            repaint();
            delta--;

        }

    }
  • ✇Recent Questions - Game Development Stack Exchange
  • Comparison of 2 different quaternion axesACR115
    I am trying to compare the Z-axis and the X-axis of two different quaternions in a way that would give me the Euler angles about the X and Y axes to line up the two different axes. In my program, the first quaternion (whose X-axis we are trying to line up) only rotates about the z and y axes and is the one being rotated first. Whereas the second quaternion (whose Z-axis we are trying to line up) only rotates about the x and y axis and is the one being rotated to match the other quaternion. Curre
     

Comparison of 2 different quaternion axes

I am trying to compare the Z-axis and the X-axis of two different quaternions in a way that would give me the Euler angles about the X and Y axes to line up the two different axes. In my program, the first quaternion (whose X-axis we are trying to line up) only rotates about the z and y axes and is the one being rotated first. Whereas the second quaternion (whose Z-axis we are trying to line up) only rotates about the x and y axis and is the one being rotated to match the other quaternion. Currently, I've been able to deduce the direct distance to line up the axes though am struggling to break the angles into pitch and yaw.

  • ✇Recent Questions - Game Development Stack Exchange
  • Resize font when screen resizes desktop LibgdxAndy
    I create my font using the following code: public BitmapFont createFont(FreeTypeFontGenerator ftfg, float dp) { FreeTypeFontParameter f = new FreeTypeFontParameter(); f.size = (int)(dp * Gdx.graphics.getDensity()); f.color = Color.BLACK; f.minFilter = Texture.TextureFilter.Nearest; f.magFilter = Texture.TextureFilter.MipMapLinearNearest; ftfg.scaleForPixelHeight((int)(dp * Gdx.graphics.getDensity())); return ftfg.generateFont(f); } myFont = createFont(new FreeTypeFo
     

Resize font when screen resizes desktop Libgdx

I create my font using the following code:

public BitmapFont createFont(FreeTypeFontGenerator ftfg, float dp)
{
    FreeTypeFontParameter f = new FreeTypeFontParameter();
    f.size = (int)(dp * Gdx.graphics.getDensity());
    f.color = Color.BLACK;
    f.minFilter = Texture.TextureFilter.Nearest;
    f.magFilter = Texture.TextureFilter.MipMapLinearNearest;
    ftfg.scaleForPixelHeight((int)(dp * Gdx.graphics.getDensity()));
    return ftfg.generateFont(f);
}

myFont = createFont(new FreeTypeFontGenerator(Gdx.files.internal("Fonts/Roboto-Black.ttf")), 16);

I have some labels to which I set the font using:

Label myLabel= new Label("Text", uiSkin);
        myLabel.setWrap(true);
        myLabel.getStyle().font = myFont;

How I create the stage:

Stage collectionStage = new Stage(new StretchViewport(Gdx.graphics.getWidth(), Gdx.graphics.getWidth()));

I also tried with no viewport or with other viewports.

In my resize method:

public void resize(int width, int height) {
    Viewport viewport = collectionStage.getViewport();
    viewport.update(width, height, false);
    viewport.apply();
}

The problem is that when I resize the window on Desktop the font gets distorted. Do I have to create another font in the resize method, and then for each label that I have, reassign the new font? Or should I do something else?

  • ✇Recent Questions - Game Development Stack Exchange
  • Graphics2D.drawImage not workingZerro97
    I'm trying to come up with my own game using Java AWT after watching a few video tutorials. However, I encountered a problem where I cannot draw an external image file that I loaded using the BufferedImage object. The problem seems to be on the method that I'm using to draw the image on the screen, where I'm using Graphics2D.drawImage() method to draw. Here is part of my code (I modified and skipped parts that seemed irrelevant to the topic): Window Class public class Window extends JPanel{
     

Graphics2D.drawImage not working

I'm trying to come up with my own game using Java AWT after watching a few video tutorials. However, I encountered a problem where I cannot draw an external image file that I loaded using the BufferedImage object.

The problem seems to be on the method that I'm using to draw the image on the screen, where I'm using Graphics2D.drawImage() method to draw.


Here is part of my code (I modified and skipped parts that seemed irrelevant to the topic):

Window Class

public class Window extends JPanel{
    public Window(int width, int height) {
        JFrame frame = new JFrame("Zerro's Game");
        
        frame.setPreferredSize(new Dimension(width, height));
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
        frame.pack();
    }
}

Game Class

public class Game extends JFrame implements Runnable {
    // Dimension for Main Frame
    private static final int WIDTH = 640;
    private static final int HEIGHT = 480;

    // Image
    private BufferedImage image;
    private Graphics2D g;

    public void run() {
        this.requestFocus();
        
        // For rendering purposes
        image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        g = (Graphics2D) image.getGraphics();
        
        //Game Loop
        long now;
        long updateTime;
        long wait;

        final int TARGET_FPS = 60;
        final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
        
        while (isRunning) {
            now = System.nanoTime();
            
            update();
            render();
            
            updateTime = now - System.nanoTime();
            wait = (OPTIMAL_TIME - updateTime) / 1000000;
                    
            try {
                Thread.sleep(wait);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void render() {
        if(gameState == STATE.GAME) {
            handler.render(g);
        } else if(gameState == STATE.MENU) {
            menu.render(g);
        }
    }

Menu Class

public class Menu extends KeyAdapter{
    private BufferedImage image;

    public void render(Graphics2D g) {
        try {
            image = ImageIO.read(getClass().getResource("/Pixel_Background.png"));
            g.drawImage(image, 0, 0, null);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

This code results in making empty frame without any content inside. I confirmed that it properly loads an image by using System.out.println(image.getHeight()) which prints out the exact height of an image that I'm using.

I've seen some comments in the internet that I need to use paintComponent() method. However, I'm just wondering if it's not a good idea to use paintComponent() in game development as the video tutorials (3 of them) that I watched didn't use such method to draw images.

Also, I'm wondering about the reason why we pass in the Graphics2D object as parameter in all the render() methods.

❌
❌