Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Unable to properly Implement KeyListener class

$
0
0
Hello everyone,

I am new to the site, and also to programming. I have been watching some tutorials and trying to research best i can on the java language for about a week, and believed i was getting the hang out of it. While making a 2d platformer I somehow got stuck on player movement, something i thought i understood well. I apologize for taking up time as i understand this is something that is very basic, and i assure you I have tried everything I can think of, and would be really appreciative if anyone would be able to tell me what I am doing wrong.

I am using 3 seperate classes total to create player's movement.

the main class "Component"

package me.Mac.Advent_Ture;


import java.applet.Applet;
import java.awt.*;
import javax.swing.JFrame;






public class Component extends Applet implements Runnable 
{
    public static boolean isMoving = false;

    private final long serialVersionUID = 1L; //compilation things
    private  static int pixelSize = 1; //has to be above the pixel dimension line
    
    
    public static double dir = 0;
    


    public static Dimension size = new Dimension(800,600); // game size
    public static Dimension pixel = new Dimension(size.width/pixelSize,size.height/pixelSize); //size of each pixel
    public static String name = "Advent Ture!";   //game title
    public static boolean isRunning = false;  //when true game will run
    public static Level level; // creates level
    public static double sX= 0,sY=0;
    public static Character character;
    
    
    
    
    
    //images
    
        private Image screen;
    
    //ints
    
  
        
        
    //Strings
    
    //booleans
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    public Component()
    {
        
        setPreferredSize(size);
        
        addKeyListener(new Listening());
        
        
        
        //allows keys to be read and used(calls Listening class)
    }
    
    public void start()
    {
       
        //Define objects
        new Tile(); //loading images
        level = new Level(); //calls Level Method
        character = new Character(Tile.tileSize,Tile.tileSize * 3); // size width and height of char
        
        
        //GameStart
        isRunning = true; // starts game loop
        new Thread(this).start();
    }
    
    public void stop()
    {
        isRunning = false;  // stops game
    }
    
    public static void main(String args[])
            
    {
        
        Component component = new Component();
        
        JFrame frame = new JFrame();
        frame.add(component); //adding component to frame
        frame.pack(); //setting the same size as the components on the frame
        frame.setResizable(true);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setTitle(name);
        frame.setFocusable(true);
        frame.requestFocus();
        
        
        
        
        component.start();
        
    }
    
    
    public void tick()     //moves enimeies and player
    {
        
      level.tick();
      character.tick();
      
    }
    
    public void render()   //draw on screen
    {
     Graphics g = screen.getGraphics();
     
     // draw shit
     g.setColor(Color.blue); //cane make your own with g.setColor(new Color.r,g,B)/>;
     g.fillRect(0, 0, pixel.width, pixel.height);
     
     //rendering
     level.render(g);
     character.render(g);
     
     g = getGraphics();
     
     g.drawImage(screen,0,0,size.width,size.height,0,0,pixel.width,pixel.height,null);
     
     g.dispose(); // disposes object after use
    }
    
    
    
    
    
    public void run()
    {
        screen = createVolatileImage(pixel.width,pixel.height); //loaded onto Graphics card ie less lag
        
        while(isRunning)
        {
            tick(); //tick before render
            render();
            
            
            try
            {
               Thread.sleep(5); 
            }catch(Exception e){}
        }
    }

    
    
}



the character class

package me.Mac.Advent_Ture;

import java.awt.*;



public class Character extends DoubleRectangle
{
    public double movementSpeed = 1.0;
    public double fallingSpeed = 1.3;
    
    
    
    
    
    
    
    
    
    public Character(int width, int height)
    
            
    {
        setBounds((Component.pixel.width/2)-(width/2),(Component.pixel.height/2)-(height/2),width,height);
        
    }
    
    public void tick()
            
   {
      
       
       
        if(!isCollidingWithBlock(new Point ((int)x,(int)(y + height)),new Point((int) (x+width), (int) (y + height))))
                {
                    
                y += fallingSpeed;
        Component.sY += fallingSpeed;
                }
        
        if(Component.isMoving)
        {
            x +=Component.dir;
            Component.sX += Component.dir;
            
        }
    }
    
    
    
    public boolean isCollidingWithBlock(Point pt1,Point pt2)
    {
        
        for(int x=(int) (this.x/Tile.tileSize);x<(int)(this.x/Tile.tileSize) + 3;x++) //hotbox width
        {
            for(int y=(int) (this.y/Tile.tileSize);y<(int)(this.y/Tile.tileSize) + 4;y++) //hitbox height
            {
                if(x >=0 && y >= 0 && x<Component.level.block.length && y< Component.level.block[0].length) {
                    if(Component.level.block[x][y].id != Tile.air)
                    {
                    if(Component.level.block[x][y].contains(pt1) || Component.level.block[x][y].contains(pt2))  //collision detection
                    {
                    return true;
               
                    }
                }
                }
            }
           
        }
        return false;
        
    }     
       

    public void render(Graphics g)                                                          //place in the arry(tileset) that the character is in
    {
        g.drawImage(Tile.tileset_char,(int)x-(int)Component.sX,(int)y-(int)Component.sY,(int)(x + width)-(int)Component.sX,(int)(y + height)-(int)Component.sY, Tile.character[0] * Tile.tileSize, Tile.character[1] * Tile.tileSize,Tile.character[0] * Tile.tileSize + (int)width, Tile.character[1] * Tile.tileSize + (int)height, null);
        
    }
 


}



and the Listening class, which has the keyListener in it

package me.Mac.Advent_Ture;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Listening implements KeyListener {
    
    public static int key;
    
    
    

    @Override
    public void keyTyped(KeyEvent ke) {
        
    }

    @Override
    public void keyPressed(KeyEvent ke) {
       key = ke.getKeyCode();
        
        switch(key)
        {
            case KeyEvent.VK_RIGHT:
                Component.isMoving = true;
                Component.dir = Component.character.movementSpeed;
                System.out.println("Right");
                 break;
                
            case KeyEvent.VK_LEFT:
                Component.isMoving = true;
                Component.dir = -Component.character.movementSpeed;
                System.out.println("Left");
                 break;
        }
    }

    @Override
    public void keyReleased(KeyEvent ke) {
        key = ke.getKeyCode();
        
        switch(key)
        {
            case KeyEvent.VK_RIGHT:
                if(Component.dir == Component.character.movementSpeed)
                {
                Component.isMoving = false;
                
                }
        break;
             case KeyEvent.VK_LEFT:
                if(Component.dir == -Component.character.movementSpeed)
                {
                Component.isMoving = false;
                }
                 break;
        }
    }
    
}




I apologize if the code is messy, as I previously said I am very new to this, also I have been trying a bunch of things for the past to days to try to solve it myself. I was able to get the player to move if I changed the if(Component.isMoving) to if(!Component.Moving) which is making me believe that the KeyListener is not working at all. I am using NetBeans and going off of a tutorial on youtube. I have paused that tutorial countless times to check my code vs theirs and everything seems the same except for things I have changed but know why.

I have also tried eliminating the Listening class and implementing the KeyListener in the Character and Component classes, but with no success. I understand it is probably something simple and stupid I am missing, but i have looked around and played with this code to the best of my abilities, and also to my wits end.

If anything else is needed from me to solve this please let me know, and thank you very much in advance.

MikeMac

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>