Key Q is working wrong

Hey guys,
I have a problem.
I have 2 functions.
key_eAction() and key_qAction().
To start the Functions, i use

 if (key_e) {
    key_e = false;
    key_eAction();
}
if (key_q) {
    key_q = false;
    key_qAction();
}

The Problem: If I don’t use key “Q” to start one of these functions, they booth working correctly.
But if I use the key “Q”, they booty working wrong.
the collision results find with the key “Q” only the terrain, and without it find everything.
If I replece “KEY_Q” with “KEY_F” or some other keys in

inputManager.addMapping("Q", new KeyTrigger(KeyInput.KEY_Q));

it works normally.
What is wrong?

Need more code. This isn’t much to go on.

  private boolean left = false, right = false, up = false, down = false, 
          mouseLeft = false, 
          key_e = false, key_q = false, 
          key_shift = false;

      private void setUpKeys() {
        inputManager.clearMappings();
        inputManager.addMapping("MouseLeft", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
        inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_A));
        inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_D));
        inputManager.addMapping("Up", new KeyTrigger(KeyInput.KEY_W));
        inputManager.addMapping("Down", new KeyTrigger(KeyInput.KEY_S));
        inputManager.addMapping("E", new KeyTrigger(KeyInput.KEY_E));
        inputManager.addMapping("Q", new KeyTrigger(KeyInput.KEY_F)); // KEY_F because KEY_Q make Problems. It works perfectly with KEY_F but wrong with KEY_Q
        inputManager.addMapping("Shift", new KeyTrigger(KeyInput.KEY_LSHIFT));
        inputManager.addMapping("Jump", new KeyTrigger(KeyInput.KEY_SPACE));
        inputManager.addMapping("Esc", new KeyTrigger(KeyInput.KEY_ESCAPE));
        inputManager.addListener(this, "Left");
        inputManager.addListener(this, "Right");
        inputManager.addListener(this, "Up");
        inputManager.addListener(this, "Down");
        inputManager.addListener(this, "Jump");
        inputManager.addListener(this, "Shift");
        inputManager.addListener(actionListener, "E");
        inputManager.addListener(actionListener, "Q");
        inputManager.addListener(actionListener, "MouseLeft");
        inputManager.addListener(actionListener, "Esc");
      }
     private ActionListener actionListener = new ActionListener() {
        public void onAction(String name, boolean keyPressed, float tpf) {
            if (name.equals("Esc") && !keyPressed) { stop(); }
            if (name.equals("MouseLeft") && !keyPressed) { mouseLeft = true; } else { mouseLeft = false; }
            if (name.equals("E") && !keyPressed) { key_e = true; } else { key_e = false; }
            if (name.equals("Q") && !keyPressed) { key_q = true; } else { key_q = false; }
        }
      };
      
      public void key_qAction() { // Take something in left Hand
            CollisionResults results = new CollisionResults();
            Ray ray = new Ray(cam.getLocation(), cam.getDirection());
            game.collideWith(ray, results);
            System.out.println(playerLeftHand);
            if (playerLeftHand.equals("")) {
                System.out.println("ok");
                if (results.size() > 0) {
                    System.out.println("results > 0");
                    CollisionResult closest = results.getClosestCollision();
                    System.out.println(closest.getGeometry().getName());
                    if (closest.getDistance() <= actionDistance) {
                        System.out.println("Distance > ");
                        Node countNode = (Node)closest.getGeometry().getParent();
                        System.out.println(countNode.getName());
                        if (!countNode.getName().equals("Game")) {
                            Node category = (Node) countNode.getParent();
                            if (category.getName().equals("Rocks")) {
                                int id = Integer.parseInt(closest.getGeometry().getName().split("-")[closest.getGeometry().getName().split("-").length-1]);
                                playerLeftHand = "Rocks-"+id;
                            }
                            if (category.getName().equals("Saplings")) {
                                int id = Integer.parseInt(closest.getGeometry().getName().split("-")[closest.getGeometry().getName().split("-").length-1]);
                                playerLeftHand = "Saplings-"+id;
                            }
                            if (category.getName().equals("Sticks")) {
                                int id = Integer.parseInt(closest.getGeometry().getName().split("-")[closest.getGeometry().getName().split("-").length-1]);
                                playerLeftHand = "Sticks-"+id;
                            }
                        }
                    }
                }
            } else {
                if (playerLeftHand.split("-")[0].equals("Rocks") && !animateRock) {
                    int id = Integer.parseInt(playerLeftHand.split("-")[playerLeftHand.split("-").length-1]);
                    Node rock = (Node) rocks.getChild(id+"");
                    Vector3f camDir = cam.getDirection();
                    Vector3f vector;
                    vector = new Vector3f(0,0,0).addLocal(camDir.clone().multLocal(5f));
                    Vector3f newPos = new Vector3f(player.getPhysicsLocation().x+vector.x,player.getPhysicsLocation().y+vector.y,player.getPhysicsLocation().z+vector.z);
                    rock.setLocalTranslation(newPos);
                    rock.setLocalRotation(cam.getRotation());
                    playerLeftHand = "";
                } else if (playerLeftHand.split("-")[0].equals("Saplings")) {
                    if (results.size() > 0) {
                        CollisionResult closest = results.getClosestCollision();
                        if (closest.getDistance() <= actionDistance && closest.getGeometry().getName().split("-")[0].equals("terrain")) {
                            int id = Integer.parseInt(playerLeftHand.split("-")[playerLeftHand.split("-").length-1]);
                            Node sapling = (Node) saplings.getChild(id+"");
                            Quaternion pitch0 = new Quaternion();
                            pitch0.fromAngleAxis(FastMath.PI / 2, new Vector3f(0,0,0));
                            
                            sapling.setLocalTranslation(closest.getContactPoint());
                            sapling.setLocalRotation(pitch0);
                            sapling.setUserData("growUpTimeout", newGrowUpTimer());
                            playerLeftHand = "";
                                
                           
                        }
                    }
                }
            }
                
      }
      public void key_eAction() { // Take something in right Hand
            CollisionResults results = new CollisionResults();
            Ray ray = new Ray(cam.getLocation(), cam.getDirection());
            game.collideWith(ray, results);
            if (playerRightHand.equals("")) {
                if (results.size() > 0) {
                    CollisionResult closest = results.getClosestCollision();
                    if (closest.getDistance() <= actionDistance) {
                        Node countNode = (Node)closest.getGeometry().getParent();
                        if (!countNode.getName().equals("Game")) {
                            Node category = (Node) countNode.getParent();
                            if (category.getName().equals("Rocks")) {
                                int id = Integer.parseInt(closest.getGeometry().getName().split("-")[closest.getGeometry().getName().split("-").length-1]);
                                playerRightHand = "Rocks-"+id;
                            }
                            if (category.getName().equals("Saplings")) {
                                int id = Integer.parseInt(closest.getGeometry().getName().split("-")[closest.getGeometry().getName().split("-").length-1]);
                                playerRightHand = "Saplings-"+id;
                            }
                            if (category.getName().equals("Sticks")) {
                                int id = Integer.parseInt(closest.getGeometry().getName().split("-")[closest.getGeometry().getName().split("-").length-1]);
                                playerRightHand = "Sticks-"+id;
                            }
                        }
                    }
                }
            } else {
                if (playerRightHand.split("-")[0].equals("Rocks") && !animateRock) {
                    int id = Integer.parseInt(playerRightHand.split("-")[playerRightHand.split("-").length-1]);
                    Node rock = (Node) rocks.getChild(id+"");
                    Vector3f camDir = cam.getDirection();
                    Vector3f vector;
                    vector = new Vector3f(0,0,0).addLocal(camDir.clone().multLocal(5f));
                    Vector3f newPos = new Vector3f(player.getPhysicsLocation().x+vector.x,player.getPhysicsLocation().y+vector.y,player.getPhysicsLocation().z+vector.z);
                    rock.setLocalTranslation(newPos);
                    rock.setLocalRotation(cam.getRotation());
                    playerRightHand = "";
                } else if (playerRightHand.split("-")[0].equals("Saplings")) {
                    if (results.size() > 0) {
                        CollisionResult closest = results.getClosestCollision();
                        if (closest.getDistance() <= actionDistance && closest.getGeometry().getName().split("-")[0].equals("terrain")) {
                            int id = Integer.parseInt(playerRightHand.split("-")[playerRightHand.split("-").length-1]);
                            Node sapling = (Node) saplings.getChild(id+"");
                            Quaternion pitch0 = new Quaternion();
                            pitch0.fromAngleAxis(FastMath.PI / 2, new Vector3f(0,0,0));
                            
                            sapling.setLocalTranslation(closest.getContactPoint());
                            sapling.setLocalRotation(pitch0);
                            sapling.setUserData("growUpTimeout", newGrowUpTimer());
                            playerRightHand = "";
                                
                           
                        }
                    }
                }
            }
                
      }

      @Override
      public void simpleUpdate(float tpf) {
    if (key_e) {
            key_e = false;
            key_eAction();
        }
    if (key_q) {
            key_q = false;
            key_qAction();
        }
    }

You’re not extending anything that might be mapping to that key? Did you start from an example/demo?

I only use the key in this code and I have no other mappings

Q is mapped by default to the FlyByCamera I think. I don’t know the consequences of adding 2 mappings to one key, but you use the cameras position anyway, and Q will send it up

inputManager.addMapping(CameraInput.FLYCAM_RISE, new KeyTrigger(KeyInput.KEY_Q));

from

I think, that is the problem, but how can I remove all keys from flycam?

flyCam.unregisterInput();

Is not working :confused:

You could use this method to delete all:

flyCam.unregisterInput();

If you just want to delete that “Q” entry, then rather use this:

inputManager.deleteMapping(CameraInput.FLYCAM_RISE);

Booth won’t delete the inputs. I can use “Q” and every other key from flycam… :confused:

What exactly is your problem?

The key Q is not working correctly, because flycam use this key and
flyCam.unregisterInput();
and
inputManager.deleteMapping(CameraInput.FLYCAM_RISE);
do not remove the key from flycam. The only thing that works is
flyCam.setEnabled(false);
, but if i do this, I can’t rotate the camera with the mouse.

flyCam.setEnabled(false);

?

It disable the flycam functions and keys, but I need the flyCam to look around with the mouse.

I guess the issue with this is that you have to call it in the simpleUpdate, not in the init (once, not on every frame).
The thing is, appstates are initialized after the simple init… so if you disable it in the simpleInit it’s re enabled just right after.

Then it is time to write your own camera control. (Doesn’t really need to be an app state!)

import com.jme3.app.Application;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.input.InputManager;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.AnalogListener;
import com.jme3.input.controls.MouseAxisTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.math.FastMath;
import com.jme3.math.Matrix3f;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;

/**
 * Simple camera control
 */
public class CameraControl extends AbstractAppState implements AnalogListener {

	private Camera cam;
	private float rotationSpeed = 1f;
	private String[] mappings;
	private InputManager inputManager;    
	private final Quaternion camRotation = new Quaternion();
	private float fieldOfView = 45;

	@Override
	public void initialize(AppStateManager stateManager, Application app) {
		super.initialize(stateManager, app);
		this.inputManager = app.getInputManager();
		this.cam = app.getCamera();
		registerWithInput();
		resetCamera();
	}

	@Override
	public void cleanup() {
		resetCamera();
		inputManager.deleteMapping("MYCAM_Left");
		inputManager.deleteMapping("MYCAM_Right");
		inputManager.deleteMapping("MYCAM_Up");
		inputManager.deleteMapping("MYCAM_Down");
		super.cleanup();
	}

	/*
	 * Resets the position, looking direction etc. to standard values
	 * Important when the game restarts.
	 */
	public void resetCamera() {
		Vector3f left = new Vector3f(-1, 0, 0);
		Vector3f up = new Vector3f(0, 1, 0);
		Vector3f direction = new Vector3f(0, 0, -1);
		cam.setAxes(left, up, direction);   
	}

	/**
	 * Sets the roation speed of the camera
	 * @param rotationSpeed 
	 */
	public void setRotationSpeed(float rotationSpeed) {
		this.rotationSpeed = rotationSpeed;
	}

	public void registerWithInput() {

		mappings = new String[]{
			"MYCAM_Left",
			"MYCAM_Right",
			"MYCAM_Up",
			"MYCAM_Down"
		};

		// both mouse and button - rotation of cam
		inputManager.addMapping("MYCAM_Left", new MouseAxisTrigger(0, true));
		inputManager.addMapping("MYCAM_Right", new MouseAxisTrigger(0, false));
		inputManager.addMapping("MYCAM_Up", new MouseAxisTrigger(1, false));
		inputManager.addMapping("MYCAM_Down", new MouseAxisTrigger(1, true));		
					
		inputManager.addListener(this, mappings);
		inputManager.setCursorVisible(false);
		
		
	}

	private void rotateCamera(float value, Vector3f axis) {
		Matrix3f mat = new Matrix3f();
		mat.fromAngleNormalAxis(rotationSpeed * value, axis);

		Vector3f up = cam.getUp();
		Vector3f left = cam.getLeft();
		Vector3f dir = cam.getDirection();

		mat.mult(up, up);
		mat.mult(left, left);
		mat.mult(dir, dir);
		
		camRotation.fromAxes(left, up, dir);
		camRotation.normalizeLocal();

		float[] angles = new float[3];
		camRotation.toAngles(angles);
	
		cam.setAxes(camRotation);
	}

	@Override
	public void onAnalog(String name, float value, float tpf) {
		if (isEnabled()) {				
			switch (name) {
				case "MYCAM_Left":
					rotateCamera(value, Vector3f.UNIT_Y);
					break;
				case "MYCAM_Right":
					rotateCamera(-value, Vector3f.UNIT_Y);
					break;
				case "MYCAM_Up":
					rotateCamera(-value, cam.getLeft());
					break;
				case "MYCAM_Down":
					rotateCamera(value, cam.getLeft());
					break;
				default: break;
			}
		}
	}
}

You use this when you attach this state to the state manager.

CameraControl camControl = new CameraControl();
stateManager.attach(camControl);

Oh yeah, I forgot :weary:

1 Like

It Works! Thank you so much! :smiley:
The problem is solved!

So much this. FlyCam is only a starter camera control… real games will need something completely different.

But it is the best way. :slight_smile:

1 Like