Java Programming: Let’s Build a Game #3

[ad_1]
Produce your own Java game from scratch with this very simple, yet very powerful course available right now

Support my Patreon –

In this video we look at adding key input into our game and working with different objects. If you have any questions then be sure to leave a comment or contact me on twitter; realtutsgml. If you learned something then be sure to leave a like, comment, and favorite.

Have you ever wanted to create games? Have you ever gotten fed up with it being to difficult? Well now is the time to thank me and possibly subscribe because you have just found the channel for you! Game Maker Tutorials, Java Game Programming, Unity3D Tutorials, Batch, C++ and much much more! This is the channel for you, the one stop shop for an exploration of your hidden talent as a game developer. Unleash your potential and go wild with imagination when you finally figure out how to make any game you want!

Visit CodingMadeSimple for more exclusive tutorials and get the help you need to succeed as your very own indie game developer!

Follow me on twitter for exclusive content and interaction with me!

Follow me on Google+ to keep updated with all of my tutorials

Game Maker Studio: Programming
Game Maker Studio: Tutorial
Java Programming
Game Programming
Game Tutorial
Programming Tutorial


Posted

in

by

Tags:

Comments

35 responses to “Java Programming: Let’s Build a Game #3”

  1. David Joel Avatar

    Hi everything is working fine and all but when I move around pressing w and immediately press s there is a second delay where the character stops moving and same goes for if you are pressing a and immediately press d. PLZ HELP!!!

  2. Mixufixu Avatar

    How can you guys even manage to get the box moving???
    It gives me an error in this line:
    if (key == KeyEvent.VK_W) tempObject.setY(tempObject.getY() – 1);
    "getY (int) in GameObject cannot be applied to ()"

    the () after getY is with red scribbles and prevents the game from running (11:32)

  3. Hurricane Gaming Avatar

    For some reason when I have if(key==KeyEvent.VK_UP)tempObject.setY(tempObject.getY()-5);
    the square moves but when I change it to , if(key==KeyEvent.VK_UP)tempObject.setVelY(-5); nothing happens. I'm not getting any errors either.

  4. Kyle Pereira Avatar

    I find it easier to just pass a list of all pressed keys when ticking the gameobjects. That way, the game object in question can decide whether to move or stay in the same place by itself.

  5. DutchDragonGames Avatar

    Is it just me? or is the game really laggy?

  6. 00Fatal00_GameDev_ Avatar

    I know this is an old video but could someone please explain the following piece of code to me?

    if (key == KeyEvent.VK_W) tempObject.setY(tempObject.getY() – 1);

    I understand that if the 'W' key is pressed, 1 is subtracted off of the y axis of tempObject.
    However, how come the player moves up if you are subtracting from the y axis and not adding?

    I would appreciate anyone who takes time out of their day to answer my question. Thanks 🙂

  7. JenzTheEpicDuckGamer Avatar

    3:37 Looks at his screen: 2251 FPS
    Looks at my screen: 272 FPS… RIP me.

  8. ZyneBeatbox Avatar

    Hey can you please help me out man, my character moves, but then for a small period of time it isnt able to move, but then I am able to move.. and so on. Help please 🙁

  9. Justin Almassi Avatar

    Wow, I think I love you!

  10. Zorri Avatar

    My cube just disapear when i press a key :c

  11. Nikoloz Avatar

    to anyone who can help, a couple question sup to now?
    the widnow class constructor calls the start method from the game class. I suppose the run method call has something to do with initializing a thread given that "runnable" is implemented? if anyone can clarify this last bit…
    closing the window stops the game, but that needs "running" to be set false. how are these two related? i dont see any other way how the while loop in run() is stopped.
    my keypress doesn't print, but thats a different story

  12. Crowbox Avatar

    Hey, kind of a late question, but ye this guides sick but im stuck with 1 small thing
    everything works but i only added Player1 For start, and when i press the keys WSAD it moves but it doesent stop moving, anyone keen enough 2 tell me what i did wrong?

  13. Relic Zexide Avatar

    how do we stop ?!!

  14. Shachar Har-Shuv Avatar

    Hey I feel like I have to tell you that I'm not really happy with the architecture of you software regarding to key events handlings. First – in your solution the handler need to know what objects there are in the game, and worse than that, the game logic is INSIDE the handler. This is really bad because most of the handler code is good for various of games and I wish to use it in many games. The better solution in my opinion is the use polymorphism like you did in the ticking and rendering functions. for example – you can do a KeyPressed function in GameObject which does nothing, and then override it in every object as needed. than in handler you can just iterate through the list and invoke the right function (which get the key code as a parameter). This is also really good because it implements the idea of separated different "layers" of the softwares – so for example the input handling and the game logic is not in the same place – so it's easy to change one without affecting the other.
    I do not wish to be insulting or rude I just thought I might bring this up… Also – while on this subject – you should make a tutorial that explains how to take most of the code you did for the understructure of the game and make it a "game engine" that can be used in various games. I actually built it while listening to your videos. Thanks for the tutorials by the way.

  15. Shachar Har-Shuv Avatar

    btw – about the id – in cpp they had a function called "idtype" or something like that that could tell you the true type of an object, for example if you had a pointer to a base class it could tell you which superclass it is actually pointing to. and than you could check if idtype(pointer) == idtype(Player). don't they have something similar in java? if would save all the trouble of defining an Enum for each object.

  16. Shachar Har-Shuv Avatar

    The reason calling KeyInput(handler) worked when you put it before constructing handler is that the KeyInput's C'tor does not use the handler yet so java don't care if it's null.

  17. Shachar Har-Shuv Avatar

    "put the Handler constructor calling first" – I actually did get a null pointer exception when I was listening to the last video. Took me some time to figure out the problem than I realise that the Window C'tor actually calls "starts" which calls the thread "starts" which I believe calls "run" which calls "tick" which called the handler thick BUT – the handler wasn't yet created! thus the null pointer exception. It's not a "random bug", it's how oop behaves and I just don't know how could it work for you before you fixed this…

  18. Jay - 2b2t Avatar

    if you dont want to keep using system.out.println(), you can always make a statement to make your life eaiser. for instance I did

    public void print(Object o) {
    System.out.println(o);
    }

    Now, instead of doing "System.out.println("something");, you can do: print("something");
    it makes life easier. trust me xD

  19. ClockworkHex Avatar

    For some reason my code only works when I create the window last.

  20. Radu Teodorescu Avatar

    When I press W for the box to move up, it only moves up one space at a time, I have to spam the W key for it to move more than one space, I have the whole moving thing under keyPressed not keyReleased, any help?

  21. Arke1999 Avatar

    how is it possible that when i pres the button left and right fast after each other my player stands stil for a second and how do i fix it

  22. FireworkHair Avatar

    I FIXED A PROBLEM! If your white block disappears when you press W for example check the game loop in Lesson #1 and make sure you copied it down right! I just came back after hours of struggling and this is how i fixed it!

  23. Nicolas Bohnenberger Avatar

    so lets say I don't want to allow diagonal movement. Do I isolate the direction with else ifs?

  24. Cedric Sullivan Avatar

    8:00, you're probably not receiving an error due to the fact that you created an instance of handler in your keyinput class.

  25. chona bT Avatar

    When i run the application it pops up, but somehow i dont get the players, and nor does it show me any errors. Anyone help please :D?

  26. GizioGaming Avatar

    System.out.println("Best Tutorial Ever!");

  27. KusKusPL Avatar

    When I am trying to add keyboard input just like you did, I get a NullPointerException.

  28. Reece scott Avatar

    You are a great teacher!

  29. Garrett Lappe Avatar

    Please help! While I was able to move the Player object when I used the "setX" and "setY" methods, I can't get it to work when I set it to change the velocity to move the Player.
    Things I've tried:
    – setting frame and this to focusable
    – clicking on the window before pressing keys
    neither worked. Like I said, it works unless I try to use velocity, and I checked my code and spelling. I even made a print statement to show the x and y velocities when I press keys–it reads the press and updates velocity appropriately, but won't move the Player.
    Here is my code: (all necessary inputs present in code)
    public class Player extends GameObject{

    public Player(int x, int y, ID id){
    super(x, y, id);

    }

    public void tick(){
    x =+ velX;
    y =+ velY;
    }
    public void render(Graphics g){
    if(id == ID.Player){ g.setColor(Color.BLUE);}
    g.fillRect(x, y, 32, 32);
    }

    }
    public class Game extends Canvas implements Runnable {

    public static final int WIDTH = 880, HEIGHT = WIDTH / 9 * 6;

    private Thread thread;
    private boolean running = false;
    private Handler handler;

    public Game(){
    handler = new Handler();
    this.addKeyListener(new KeyInput(handler));
    this.setFocusable(true);
    new Window(WIDTH, HEIGHT, "Game Title", this);
    handler.addObject(new Player(200, 200, ID.Player));
    this.requestFocusInWindow();
    }

    public synchronized void start(){
    thread = new Thread(this);
    thread.start();
    running = true;
    }
    public synchronized void stop(){
    try {
    thread.join();
    running = false;
    }catch(Exception e){}
    }

    public void run(){
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0;
    while(running){
    long now = System.nanoTime();
    delta =+ (now – lastTime) / ns;
    lastTime = now;
    while(delta >= 1){
    tick();
    delta–;
    }
    if (running){
    render();
    }
    frames++;
    if (System.currentTimeMillis() – timer > 1000) {
    timer =+ 1000;
    //System.out.println("FPSL " + frames);
    frames = 0;
    }
    }
    stop();
    }
    private void tick(){
    handler.tick();
    }
    private void render(){
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null){
    this.createBufferStrategy(2);
    return;
    }
    Graphics g = bs.getDrawGraphics();

    g.setColor(Color.BLACK);
    g.fillRect(0,0,WIDTH,HEIGHT);

    handler.render(g);

    g.dispose();
    bs.show();
    }

    public static void main(String args[]){
    new Game();
    }
    }

    public class KeyInput extends KeyAdapter {

    private Handler handler;

    public KeyInput(Handler handler){
    this.handler = handler;
    }
    public void keyPressed(KeyEvent e){
    int key = e.getKeyCode();
    for (int i = 0; i < handler.object.size(); i++){
    GameObject tempObject = handler.object.get(i);

    if (tempObject.getId() == ID.Player){
    if (key == KeyEvent.VK_W){tempObject.setVelY(-1);}
    if (key == KeyEvent.VK_A){tempObject.setVelX(-1);}
    if (key == KeyEvent.VK_S){tempObject.setVelY(+1);}
    if (key == KeyEvent.VK_D){tempObject.setVelX(+1);}
    System.out.println("VelY: "+ tempObject.getVelY() + " VelX: " + tempObject.getVelX());
    }
    }
    }
    public void keyReleased(KeyEvent e){
    int key = e.getKeyCode();
    for (int i = 0; i < handler.object.size(); i++){
    GameObject tempObject = handler.object.get(i);

    if (tempObject.getId() == ID.Player){
    if (key == KeyEvent.VK_W){tempObject.setVelY(0);}
    if (key == KeyEvent.VK_A){tempObject.setVelX(0);}
    if (key == KeyEvent.VK_S){tempObject.setVelY(0);}
    if (key == KeyEvent.VK_D){tempObject.setVelX(0);}
    }
    }
    }
    }

  30. ⊆Roovy⊇ Avatar

    If anyone has the problems with lagging (like that the squares aren't moving really smoothly as in the video), here is a solution:
    Go to the render loop and create a BufferedImage as the additional buffer (in my case I didn't use a BufferStrategy but just a JFrame). Then you get a second Graphics object from the image. What you do now is change the code like that:
    Graphics panelGraphics = panel.getGraphics(); (in my case or in your case from a BufferStrategy)
    BuffereredImage bufferImage = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB);
    Graphics bufferGraphics = bufferImage.getGraphics();
    game.render( bufferGraphics ); ('game' is my class with the main method)
    panelGraphics.drawImage( bufferImage, 0, 0, null );
    It fixes the lag because the image here called 'bufferImage' already contains all rendered graphic objects (like the player) when itself gets rendered and so there is no tearing because the JPanel (or Canvas) doesn't refresh with only half the graphics done yet; a process we cannot control because it's embedded in AWTs core.

  31. Anmol Avatar

    I am getting the error "incompatible operand types void and id" on line
    if(tempObject.getId() == ID.Player)

    Please help

  32. Spencer Robinson Avatar

    I had a flashback to ChippyGaming's videos…
    "HELLO TERRARIA ENTHUSIASTS"

  33. Amidaes Bowinder Avatar

    FOR ALL THOSE IN THE FUTURE WHO WISH NOT READ FURTHER … ehehem

    java doesnt start the game focused naturally, so if everything is correctly coded and spelt, yet it wont work and has no errors.

    just click the screen

  34. Redstoner Craft Avatar

    hello i need some help

    the problem is when i press the w button the player1 box didn't move , same on player 2 when i press up button it didn't work
    worst problem : i can't fix it , i don't know how

    the code —-

    package com.myowngame.main;

    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;

    public class KeyInput extends KeyAdapter
    {
    private Handler handler;

    public void Input(Handler handler)
    {
    this.handler = handler;
    }

    public void keyPressed(KeyEvent e)
    {
    int key = e.getKeyCode();

    for(int i = 0; i < handler.object.size(); i++)
    {
    GameObject tempObject = handler.object.get(i);

    if(tempObject.getId() == ID.Player)
    {
    //key events for player 1

    if(key == KeyEvent.VK_W) tempObject.setY(tempObject.getY() – 1);
    }

    if(tempObject.getId() == ID.Player2)
    {
    //key events for player 2

    if(key == KeyEvent.VK_UP) tempObject.setY(tempObject.getY() – 1);
    }
    }
    }

    public void keyReleased(KeyEvent e)
    {
    int key = e.getKeyCode();
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *