Handling multiple key events libgdx - libgdx

I am trying to make a game using the libgdx framework.
I am using an InputAdapter to check for key press events, everything works fine until more than 3 keys are pressed at once.
I need 3 or more than 3 key events if player is moving diagonally and shooting at the same time.
For some reason the input adapter only registers first 2 key events and no new press event is registered until one of the keys is up.
public class MyInputProcessor extends InputAdapter{
public boolean keyDown(int k)
{
switch (k)
{
case Keys.LEFT:
MyInput.setKey(MyInput.LEFT, true);
break;
case Keys.UP:
MyInput.setKey(MyInput.UP, true);
break;
case Keys.DOWN:
MyInput.setKey(MyInput.DOWN, true);
break;
case Keys.RIGHT:
MyInput.setKey(MyInput.RIGHT, true);
break;
case Keys.Z:
MyInput.setKey(MyInput.SHOOT, true);
break;
case Keys.ESCAPE:
MyInput.setKey(MyInput.ESC, true);
break;
}
return true;
}
public boolean keyUp(int k)
{
switch (k)
{
case Keys.LEFT:
MyInput.setKey(MyInput.LEFT, false);
break;
case Keys.UP:
MyInput.setKey(MyInput.UP, false);
break;
case Keys.DOWN:
MyInput.setKey(MyInput.DOWN, false);
break;
case Keys.RIGHT:
MyInput.setKey(MyInput.RIGHT, false);
break;
case Keys.Z:
MyInput.setKey(MyInput.SHOOT, false);
break;
case Keys.ESCAPE:
MyInput.setKey(MyInput.ESC, false);
break;
}
return true;
}
}

Related

Libgdx Box2d Jumping through

I want to make a jump like in the Mario game. When you are under the platform and you jump, you can then pass through the collider.
When a player's velocity is going down, colliders should wake up. I know that I should use ContactListener, but when I'm using the contact.setEnable(false) method nothing happens.
My contact listener (ground checker works perfectly)
world.setContactListener(new ContactListener() {
#Override
public void beginContact(Contact contact) {
if(contact.getFixtureA().getBody().getUserData() == "ground" && contact.getFixtureB().getUserData() == "groundChecker"){
character.isGrounded = true;
System.out.println(" Colliding");
}
}
#Override
public void endContact(Contact contact) {
}
#Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
});
What and where should I put to get effect like this.
enter image description here
enter image description here
Collider should have only one side, have somebody deal with it?
Found a solution I hope it will be helpfull.
world.setContactListener(new ContactListener() {
#Override
public void beginContact(Contact contact) {
//setting isGrounded boolean variable in our character class, but we need to check "player" velocity, because we don't want to enable jumping when only ground will passed througt
if(contact.getFixtureA().getBody().getUserData() == "ground" && contact.getFixtureB().getUserData() == "groundChecker" && (contact.getFixtureB().getBody().getLinearVelocity().y < 0 || contact.getFixtureB().getBody().getLinearVelocity().y == 0)){
character.isGrounded = true;
}
}
#Override
public void endContact(Contact contact) {
}
#Override
public void preSolve(Contact contact, Manifold oldManifold) {
//we have to disable contact when our "player" fixture collide with "ground" fixture
if(contact.getFixtureA().getBody().getUserData() == "ground" && contact.getFixtureB().getUserData() == "player"){
contact.setEnabled(false);
}
//and we need to disable contact when our "groundChecker" will collide with "ground" and we need to check what velocity.y of player body is, when it is bigger than 0 contact should be falsed
if(contact.getFixtureA().getBody().getUserData() == "ground" && contact.getFixtureB().getUserData() == "groundChecker" && contact.getFixtureB().getBody().getLinearVelocity().y > 0){
contact.setEnabled(false);
}
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
});
We have to disable contact when our "player" fixture collide with "ground" fixture.
Like this.
if(contact.getFixtureA().getBody().getUserData() == "ground" && contact.getFixtureB().getUserData() == "player"){
contact.setEnabled(false);
}
And we need to disable contact when our "groundChecker" will collide with "ground" and we need to check what velocity.y of player body is, when it is bigger than 0, contact should be falsed.
if(contact.getFixtureA().getBody().getUserData() == "ground" && contact.getFixtureB().getUserData() == "groundChecker" && contact.getFixtureB().getBody().getLinearVelocity().y > 0){
contact.setEnabled(false);
}
Here is a demo of the above solution:

Flash as3 class wont call ADDED_TO_STAGE event when using addChild()

I don't know why, but for some reason I can't get my InputEngine class to listen for ADDED_TO_STAGE.
package Input{
import flash.display.*;
import flash.events.*;
import flash.ui.Keyboard;
public class InputEngine extends Sprite{
public function InputEngine() {
addEventListener(Event.ADDED_TO_STAGE, stageAddHandler);
leftPressed = false;
rightPressed = false;
upPressed = false;
downPressed = false;
}
public function stageAddHandler(e:Event)
{
trace("worke");
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyIsPressed, false, 0, true);
stage.addEventListener(KeyboardEvent.KEY_UP, keyIsReleased, false, 0, true);
}
public function keyIsPressed(e:KeyboardEvent)
{
switch(e.keyCode)
{
case Keyboard.LEFT : leftPressed = true; break;
case Keyboard.RIGHT : rightPressed = true; break;
case Keyboard.UP : upPressed = true; break;
case Keyboard.DOWN : downPressed = true; break;
}
}
public function keyIsReleased(e:KeyboardEvent)
{
switch(e.keyCode)
{
case Keyboard.LEFT : leftPressed = false; break;
case Keyboard.RIGHT : rightPressed = false; break;
case Keyboard.UP : upPressed = false; break;
case Keyboard.DOWN : downPressed = false; break;
}
}
public var leftPressed:Boolean = new Boolean;
public var rightPressed:Boolean = new Boolean;
public var upPressed:Boolean = new Boolean;
public var downPressed:Boolean = new Boolean;
}
}
This is the main game file:
package {
import Input.InputEngine;
import flash.display.*;
import flash.events.*;
public class System extends Sprite{
public function System() {
trace("System created");
addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addChild(inputEngine);
// constructor code
}
public function gameLoop(e:Event)
{
if(inputEngine.leftPressed == true)
{
trace("Left pressed");
}
}
public var inputEngine:InputEngine = new InputEngine();
}
}
for some reason I cannot get InputEngine to initialize the keyboard listeners. What am I doing wrong here?
Your problem based on your comments of the error is that your instance of the System class has not been added to the display list. Without seeing all your code, it's hard to help you.
You didn't mention there was a runtime error in your question. But if we assume that you actually have an instance of inputEngine and things are happening as you 'expect' them to, the problem is that your instance of System class has not been added to the stage. Therefore... inputEngine is never attached to the display list of the stage.

NullPointerException in swing at actionPerformed

This is a login form for a slot machine game which will evoke a "NextPage" object. I don't think this LoginDemo.java code has to do anything with the error but I prefer to post the entire code. Thanks in advance..
//LoginDemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Login extends JFrame implements ActionListener
{
JButton SUBMIT;
JPanel panel;
JLabel label1,label2;
final JTextField text1,text2;
Login()
{
label1 = new JLabel();
label1.setText("Username:");
label1.setBounds(50,50,100,30);
text1 = new JTextField(15);
text1.setBounds(250,50,100,30);
label2 = new JLabel();
label2.setText("Password:");
label2.setBounds(50,250,100,30);
text2 = new JPasswordField(15);
text2.setBounds(250,250,100,30);
//this.setLayout(new BorderLayout());
SUBMIT=new JButton("SUBMIT");
SUBMIT.setBounds(350,350,100,30);
// panel=new JPanel(new GridLayout(3,1));
panel=new JPanel(null);
panel.setBounds(50,50,1000,1000);
// panel.setLayout(new FlowLayout());
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(SUBMIT);
add(panel,BorderLayout.CENTER);
SUBMIT.addActionListener(this);
setTitle("LOGIN FORM");
}
public void actionPerformed(ActionEvent ae)
{
String value1=text1.getText();
String value2=text2.getText();
if (value1.equals("a") && value2.equals("a"))
{
NextPage page=new NextPage();
page.setVisible(true);
//JLabel label = new JLabel("Welcome:"+value1);
// page.getContentPane().add(label);
setVisible(false);
}
else
{
//System.out.println("enter the valid username and password");
JOptionPane.showMessageDialog(this,"Incorrect login or password","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
class LoginDemo
{
public static void main(String arg[])
{
try
{
Login frame=new Login();
frame.setSize(1000,1000);
frame.setVisible(true);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
//NextPage.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.Random;
import java.sql.*;
import java.lang.*;
import java.awt.image.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class NextPage extends JFrame implements Runnable, ActionListener
{
BufferedImage img1,i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,star1;
JFrame f1;
Thread t1,t2,t3;
int x1,y1,i,j,k,l,m,n,r1,r2,r3;
JButton b1;
Random r=new Random();
TextField tf1;
JPanel p1;
NextPage()
{
setBounds(50,50,1000,1000);
p1=(JPanel)(getContentPane());
p1.setBounds(50,50,1000, 1000);
p1.setLayout(null);
//tf1=new TextField(20);
//tf1.setBounds(50,50,100,30);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Welcome");
b1=new JButton("START");
//p1.add(tf1);
b1.setBounds(150,400,100,30);
//try{
b1.addActionListener(this);
//}
/*catch(Exception e)
{
System.out.println(""+e);
}*/
add(b1);
setVisible(true);
try
{
i0=ImageIO.read(new File("tea.jpg"));
i1=ImageIO.read(new File("coffee.jpg"));
i2=ImageIO.read(new File("bhel.jpg"));
i3=ImageIO.read(new File("pizza.jpg"));
i4=ImageIO.read(new File("icecream.jpg"));
i5=ImageIO.read(new File("dosa.jpg"));
i6=ImageIO.read(new File("idli.jpg"));
i7=ImageIO.read(new File("panipuri.jpg"));
i8=ImageIO.read(new File("orange.jpg"));
i9=ImageIO.read(new File("watermelon.jpg"));
i10=ImageIO.read(new File("pavbhaji.jpg"));
i11=ImageIO.read(new File("noodles.jpg"));
i12=ImageIO.read(new File("sandwich.jpg"));
}
catch (IOException ie)
{
System.out.println("Error:"+ie.getMessage());
}
j=0; m=0; n=0;
r1= r.nextInt(13);
r2= r.nextInt(13);
r3= r.nextInt(13);
}
public void init()
{
t1=new Thread(this);
t2=new Thread(this);
t3=new Thread(this);
}
public void start()
{
t2.start();
t3.start();
}
public void run()
{
try
{
if(Thread.currentThread()==t1)
for(j=0; j<150; j++)
//for(i=0; i<=150; i+=20)
{
r1= r.nextInt(13);
repaint();
t1.sleep(10);
}
if(Thread.currentThread()==t2)
for(m=0; m<160; m++)
//for(k=0; k<=150; k+=20)
{
r2= r.nextInt(13);
repaint();
t2.sleep(10);
}
if(Thread.currentThread()==t3)
for(n=0; n<170; n++)
//for(l=0; l<=150; l+=20)
{
r3= r.nextInt(13);
repaint();
t3.sleep(10);
}
}
catch(Exception e)
{
System.out.println(""+e);
}
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawRect(50,300,150,80);
g.drawRect(200,300,150,80);
g.drawRect(350,300,150,80);
switch(r1)
{
case 0: g.drawImage(i0,65,300,this);
break;
case 1: g.drawImage(i1,65,300,this);
break;
case 2: g.drawImage(i2,65,300,this);
break;
case 3: g.drawImage(i3,65,300,this);
break;
case 4: g.drawImage(i4,65,300,this);
break;
case 5: g.drawImage(i5,65,300,this);
break;
case 6: g.drawImage(i6,65,300,this);
break;
case 7: g.drawImage(i7,65,300,this);
break;
case 8: g.drawImage(i8,65,300,this);
break;
case 9: g.drawImage(i9,65,300,this);
break;
case 10: g.drawImage(i10,65,300,this);
break;
case 11: g.drawImage(i11,65,300,this);
break;
case 12: g.drawImage(i12,65,300,this);
break;
}
switch(r2)
{
case 0: g.drawImage(i0,215,300,this);
break;
case 1: g.drawImage(i1,215,300,this);
break;
case 2: g.drawImage(i2,215,300,this);
break;
case 3: g.drawImage(i3,215,300,this);
break;
case 4: g.drawImage(i4,215,300,this);
break;
case 5: g.drawImage(i5,215,300,this);
break;
case 6: g.drawImage(i6,215,300,this);
break;
case 7: g.drawImage(i7,215,300,this);
break;
case 8: g.drawImage(i8,215,300,this);
break;
case 9: g.drawImage(i9,215,300,this);
break;
case 10: g.drawImage(i10,215,300,this);
break;
case 11: g.drawImage(i11,215,300,this);
break;
case 12: g.drawImage(i12,215,300,this);
break;
}
switch(r3)
{
case 0: g.drawImage(i0,365,300,this);
break;
case 1: g.drawImage(i1,365,300,this);
break;
case 2: g.drawImage(i2,365,300,this);
break;
case 3: g.drawImage(i3,365,300,this);
break;
case 4: g.drawImage(i4,365,300,this);
break;
case 5: g.drawImage(i5,365,300,this);
break;
case 6: g.drawImage(i6,365,300,this);
break;
case 7: g.drawImage(i7,365,300,this);
break;
case 8: g.drawImage(i8,365,300,this);
break;
case 9: g.drawImage(i9,365,300,this);
break;
case 10: g.drawImage(i10,365,300,this);
break;
case 11: g.drawImage(i11,365,300,this);
break;
case 12: g.drawImage(i12,365,300,this);
break;
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
t1.start();
}
/*public static void main(String args[])
{
NextPage o=new NextPage();
}*/
}
}
Here are the exceptions that I get-
F:\java\jdk\bin>java LoginDemo
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at NextPage.actionPerformed(NextPage.java:235)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
atjavax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6289)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6054)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4652)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:603)
at java.awt.EventQueue$1.run(EventQueue.java:601)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87
at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98
at java.awt.EventQueue$2.run(EventQueue.java:617)
at java.awt.EventQueue$2.run(EventQueue.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87
at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Can't get any solution.. I am a learner..please help..
You used the variable t1 to start the thread that should be assigned to this variable. How ever the function init() that creates the instance of the thread that is assigned to this variable is never called. There for t1 is null and calling any function on a null object causes the NullPointerException.
Simply call the init() function. I think the original idea was to call it within the constructor and you simply forgot to insert it.
For future question please consider only posting the lines close to the point where the StackTrace reports the error. To find that spots of interest look into the StackTrace and look for entries in classes you wrote. In this case NextPage.actionPerformed(NextPage.java:235) is a point of interest. In your question best mark those spots to get a good resolution quickly.
You do not call the init method, hence your t1 variable is still null when you enter the actionPerformed method.
This is rather obvious from the stacktrace (there is only one thing that can be null on that line), and if not obvious from the stacktrace a debugger would have shown this immediately. Way faster then creating a post with hundreds of lines of irrelevant code

Problem with switch

My problem is that I can't (don't know) make work my switch. Here in my first case, I input "hache", and it doesn't pass trough. Strangely, in my trace(traget); [Object hache] or [Object extincteur] (depending on wich mc I click on) comes out... Why does it don't go trough the first case? I have no clue. I tried removing the " ".
package cem
{
import flash.display.MovieClip;
public class actionObjets{
/*--inventaire--*/
private static var inventaireHache:Boolean = false;
private static var inventaireExtincteur:Boolean = false;
private var objetClique:MovieClip;
public function actionObjets(target) {
this.objetClique = target;
switch(objetClique){
case "hache":
inventaireHache = true;
ajouterInventaire(objetClique);
break;
case "extincteur":
inventaireExtincteur = true;
ajouterInventaire(objetClique);
break;
}
trace(target);
}
private function ajouterInventaire(objetEnlever):void{
objetClique.parent.removeChild(objetClique);
trace(inventaireHache + " - Hache");
trace(inventaireExtincteur + " - Extincteur");
}
}
}
btw, target is the movieClip I clicked on a.k.a. Object extincteur, or Object hache.
The problem is that objetClique isn't a string. You probably want to do something like switch (objetClique.name).
If you want to understand what's going on, rewrite the code this way:
if (objetClique == "hache") {
// ...
} else if (objetClique == "extincteur") {
// ...
}
I hope this illustrates more clearly why the switch doesn't work. objetClique couldn't be equal to the string "hache", because it's not a string. From the looks of it objetClique refers to a DisplayObject and they have a property called name, which is what you want to compare:
if (objetClique.name == "hache") {
// ...
} else if (objetClique.name == "extincteur") {
// ...
}
that code would work, and it's equivalent to a switch that looks like this:
switch (objetClique.name) {
case "hache":
// ...
break;
case "extincteur":
// ...
break;
}

ActionScript - Using "is" comparative in switch statement?

i have many objects of the same custom class, and another many objects of another custom class. i would like to create a switch statement to determine from which of the classes the object belongs. the following code doesn't compile, so i'm not sure if this is possible. is the only alternative to use if statements?
function mouseClickEventHandler(evt:MouseEvent):void
{
switch (evt.currentTarget)
{
case (is customClassA): trace("is instance of customClassA"); break
case (is customClassB): trace("is instance of customClassB");
}
}
This should work:
function mouseClickEventHandler ( evt:MouseEvent ):void
{
switch ( evt.currentTarget.constructor )
{
case CustomClassA:
trace("is instance of customClassA");
break;
case CustomClassB:
trace("is instance of customClassB");
break;
}
}
See Object.constructor.
function clickHandler (event:MouseEvent):void
{
var target:Object = event.currentTarget;
switch (true)
{
case (target is CustomClassA):
trace("is instance of customClassA");
break;
case (target is CustomClassB):
trace("is instance of customClassB");
break;
}
}
Not sure if braces are needed