public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
for(GameObject tempObject : handler.object){
if(tempObject.getID() == ObjectID.Player){
if(key == KeyEvent.VK_D){ tempObject.setVelX(0); }
if(key == KeyEvent.VK_A){ tempObject.setVelX(0); }
if(key == KeyEvent.VK_S){ tempObject.setVelY(0); }
if(key == KeyEvent.VK_W){ tempObject.setVelY(0); }
}
}
if(Game.getChat().isWorking()){
Game.getChat().passText(e.getKeyChar(e.getKey));
//.replaceAll("Space", " ").replaceAll("Period", ".").replaceAll("Backspace","").replaceAll("Shift","Shift").replaceAll("Slash","/").replaceAll("comma",",")
}
}
}
This code basically checks when a user releases a key while typing something in the chat box for my game. Then it passes it onto a method that basically sets the text to be rendered in the game to that. This really doesn't matter though, the problem is this:
As you can see, those annoying boxes only appear when I have shift being released.
More code:
KeyInput:
http://pastebin.com/BM8yZ1i6
Game Class:
http://pastebin.com/vViQ23pS
Static Chat:
http: (slash slash) pastebin (dot) com/CgQE7SgN
ChatManager:
http: (slash slash) pastebin (dot) com/yVM5rdUs
Additional info:
when I System out the text that is being typed, the boxes are not boxes, they are question marks instead.
Related
After doing a few small things i have decided to try my hand at a text based rpg. I am only using the console as i again am learning still. I am however at this point running into an issue i cant seem to get passed nor find any help on. I have my Game class which holds my main method as well as a few other classes one of which is my Player class. Within my Player class i have this:
public void playerControls(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_W)
{
System.out.println("Up");
}
if (key == KeyEvent.VK_A)
{
System.out.println("Left");
}
if (key == KeyEvent.VK_S)
{
System.out.println("Down");
}
if (key == KeyEvent.VK_D)
{
System.out.println("Right");
}
if (key == KeyEvent.VK_I)
{
System.out.println("Inventory");
}
if (key == KeyEvent.VK_O)
{
System.out.println("Options");
}
if (key == KeyEvent.VK_M)
{
System.out.println("Map");
}
if (key == KeyEvent.VK_C)
{
System.out.println("Character");
}
}
Then inside of my Game class i have within my main method:
//START OF GAME
do
{
player.playerControls(e);
validInput = true;
System.out.println("!!!!!!!!!!enter the intro story here!!!!!!!!!");
} while (gameRun);
}
The problem i am having is that i get an error saying e cannot be resolved to a variable when i run it as null i also throw errors. My question is how do I (like this/also "properly") call the playerControls from my players class into my Game class so that i can run the game and allow user input. Thank you for any answers. Have a great day :)
Instead of having your method require a KeyEvent you can just read the console input.
do {
String input = System.console().readLine();
//Change playerControls(KeyEvent e) to playerControls(String e)
player.playerControls(input);
validInput = true;
System.out.println("!!!!!!!!!!enter the intro story here!!!!!!!!!");
} while (gameRun);
Yes there is a way to do this with a single Char instead of a String, but it is not easy enough in my opinion for a starter.
Now you also would have to change your playerControls-method further:
public void playerControls(String e){
switch(e){
case "Up": system.out.println("Up");
break;
//Do so with all controls
}
Instead of the break which is to stop executing every following case(which will happen if you forget the break) you could use return;.
Wasn't sure how to word the title.
I have some code for my "space invaders" type game. I made the entire thing just making adjustments. To shoot, i use spacebar. The problem is im able to hold spacebar and it continually shoots. I would rather have to press it multiple times (if i hold it down.. for it not to continually fire) How would i change it?
*here is the code i believe is the source of the problem. If the source is located elsewhere please say so.
private class KeyInputHandler extends KeyAdapter {
private int pressCount = 1;
/**
* key pressed
*/
public void keyPressed(KeyEvent e) {
if (waitingForKeyPress) {
return;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
firePressed = true;
}
}
/**
* Key Released
*/
public void keyReleased(KeyEvent e) {
if (waitingForKeyPress) {
return;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
firePressed = false;
}
}
added code
public class ShotEntity extends Entity {
//vertical speed
private double moveSpeed = -300;
private Game game;
private boolean used = false;
/**
* Create a new shot from the player
*/
public ShotEntity(Game game,String sprite,int x,int y) {
super(sprite,x,y);
this.game = game;
dy = moveSpeed;
}
/**
* Request that this shot moved based on time
*/
public void move(long delta) {
super.move(delta);
if (y < -100) {
game.removeEntity(this);
}
}
//collision
public void collidedWith(Entity other) {
// prevents double kills.
if (used) {
return;
}
// alien killed
if (other instanceof AlienEntity) {
game.removeEntity(this);
game.removeEntity(other);
game.notifyAlienKilled();
used = true;
}
}
}
Listen for two seperate key events. One when the key is pressed, and one when it is released. Now, you make a boolean.
public boolean myBoolean;
When the key is pressed, set the boolean to true (myBoolean==true)and if it is released, set it to false (myBoolean==false).
Now, create a simple if statement:
if(myBoolean==true){ //Key is being held down
//execute this code
//Have nothing be done
}
Thats it!
P.S. If you want, you can have one separate method to clean up the code. This method could just change the value of the boolean:
public void changeValueOfBoolean(Boolean b){
if(b = true){
return false;
}
if(b==false){
return true;
}
}
It's very simple. Let me know if you need any help, and if this was helpful, please mark it as best answer. Feel free to ask me any questions, I am always happy to help!
Clarifications:
Okay, so we have this boolean, right? Now, this boolean essencialy decides whether the key is pressed or not.
Say we press the button:
Because the key is being held down, we make the boolean myBoolean as true. Now, because the user is holding the key down, we want to do nothing, right? That's why we created that if statement:
if(myBoolean==true){ //Key is being held down
//execute this code
//Have nothing be done
}
It says, if the boolean is true, then we won't do anything. Recall, the boolean is true when the key is being held down, remember? So, when the key is held down, the boolean is true, and nothing will be done.
Now, when the user releases the key:
Now, say the user has pressed the key. This will call two listeners. One listener for when the key is pressed and another for when it is released. If the user just presses the key, myBoolean will end as false, since they have let go of the key. Therefore, we can execute some code when myBoolean is false (shooting).
**In summary:
myBoolean is true when when the key is being held down. So, when it is true, we do nothing. myBoolean is false when the user lets go of the key, and there, we shoot the space invaders.**
Simple, just have a Boolean variable which causes the ship to shoot only when it is true. Then set it to true in the space bar is pressed and set it to false when the ship shoots. I can't show you how to implement it in your program as I don't know how your shoot method works. However, if you were to post the method which causes the ship to shoot then, I could show you how to implement it or, you could try your self.
How can I get characters without pressing the Enter key?
Actually I want to build a game so I need to get characters as moves and then do the moves without the Enter key being pressed.
You could add a keyListener if your using swing example of keyListener:
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_UP)
{
//code here
}
else if(keyCode == KeyEvent.VK_DOWN)
{
//code here
}
//etc...
}
For example I am still learning keyListeners as well. but, to make a e.g Rectangle move you could make a private rectangle call it in your paintComponent() rect.fillRect(0,0,10,10) then use the keyListener to check for input.
public void keyPressed(KeyEvent e){
if (rect.getKeyCode() == KeyEvent.VK_S)
if (rect.getKeyCode() == KeyEvent.VK_F)
xa = 2;
if (rect.getKeyCode() == KeyEvent.VK_E)
ya = 2;
if (rect.getKeyCode() == KeyEvent.VK_D)
ya = -2;
}
EDIT: After, reading that you are not using Swing, it would help to provide some code or further expand on the details of what you want the key to do when pressed in your game.
you should take a look at:
System.in.read();
It reads the next byte of data from the input stream.
So basicaly what im trying to do is using LWJGL now making my player move in the game. The player is currently moving but he doesnt keep mooving while you are holding the button..
public void update(){
while(Keyboard.next()){
if(Keyboard.getEventKey() == Keyboard.KEY_RIGHT) {
if(Keyboard.getEventKeyState()){
System.out.println("KEY DOWN!");
player.playerMovingRight();
}
else{
System.out.println("KEY RELEASED!");
}
}
}
I tried using a while(Keyboard.getEventKeyState()) but it just made the game crash and it wouldnt recognise if i release the key.
So how can i make my player keep moving if you hold the button instead of having to rapidly press the key to move. And how would i make it work if the player is holding 2 buttons at the same time?
Updated code:
public void update(){
while(Keyboard.next()){
//If key escape is down we shut the application down
if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)){
System.exit(0);
}
//If key up was pressed move up
else if(Keyboard.getEventKey() == Keyboard.KEY_UP) {
if(Keyboard.getEventKeyState()){
System.out.println("KEY DOWN!");
moveUp = true;
}
else{
System.out.println("KEY RELEASED!");
moveUp = false;
}
}
//If key down was pressed move down
else if(Keyboard.getEventKey() == Keyboard.KEY_DOWN) {
if(Keyboard.getEventKeyState()){
System.out.println("KEY DOWN!");
moveDown = true;
}
else{
System.out.println("KEY RELEASED!");
moveDown = false;
}
}
if(moveUp == true){
player.playerMovingUp();
}
if(moveDown == true){
player.playerMovingDown();
}
}
Im still having the same problem with the code, Im starting to think its they Keyboard.next() that is preventing me from holding the button and the player still moves.
What you need is a boolean flag which triggers when the button is pressed down, and is untriggered when the button is released. The flag would then be added to an if statement before the movement code. Like so:
if(Keyboard.getEventKey() == Keyboard.KEY_RIGHT) {
if(Keyboard.getEventKeyState()){
System.out.println("KEY DOWN!");
flag = true;
}
else{
System.out.println("KEY RELEASED!");
flag = false;
}
}
}
//player movement code
if(flag) {
player.playerMovingRight();
}
The way to do it with multiple keys is to use an array of boolean triggers and repeating the checks for each key.
While the above answer will work, LWJGL has the capability to detect if a key is being held down. It is not enabled by default though, so you need to enable it. To do this just set this flag to true somewhere in your input initialization.
Keyboard.enableRepeatEvents(true);
Now in your event loop, just do this check on your keys to see if it is a repeat (held down key).
if(Keyboard.isRepeatEvent())
Here is a small sample to see how to check a key for different key states.
while(Keyboard.next())
{
if(Keyboard.getEventKey() == Keyboard.KEY_A)
if(Keyboard.getEventKeyState())
{
if(Keyboard.isRepeatEvent())
// Key held down
else
// Key pressed
}
else
// Key released
}
while(Keyboard.next()) is supposed to be used with events.
In your case, you don't want to only do something, when an event gets triggered. But you want to determine many times per second, whether a key is pressed or not. If it is, you want to do something (e.g. move).
So it's the best solution to use the Keyboard.isKeyDown() function.
A little example:
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {
System.out.println("pressing KEY_UP");
}
if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
System.out.println("pressing KEY_DOWN");
}
if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
System.out.println("pressing KEY_LEFT");
}
if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
System.out.println("pressing KEY_RIGHT");
}
Also, a good tutorial can be found here.
I found a very good tutorial about how to create games with Java2D. In this tutorial there is a section called 'Moving sprites' that shows how to move a little spacecraft image on the screen. I was playing with the craft and realized that it was "blocking" on screen sometimes. After some tests and thinking about the problem I found out that the blocking problem was happening because when you use the arrows of the keyboard sometimes you press Left and Right at same time for example, and this blocks the movement.
So my question is: how do I handle this kind of keyboard event - when you are pressing LEFT button keep pressing it and then press RIGHT button - so the character movement is not blocked?
I think this is very common to happen because when you are playing you switch from left to right but for an instant you are pressing left and right at the same time.
You can do this in multiple ways. One way is to use booleans in your program.
You can set booleans to true when you press a certain key and to false when you release them. ie:
int x,xSpeed;
boolean movingLeft = false;
boolean movingRight = false;
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){
movingLeft = true;
}
if(key == KeyEvent.VK_RIGHT){
movingRight = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){
movingLeft = false;
}
if(key == KeyEvent.VK_RIGHT){
movingRight = false;
}
}
public void moving(){
if(movingLeft){
x -= xSpeed;
}
if(movingRight){
x += xSpeed;
}
}
Ok let's look at this code. Because we're using the 'else if' you either move right, or you move left. I haven't test this code so not quite sure if this will work :)
Let me know what you think and good luck!