Game Loop and Key Input - How to Make a 2D Game in Java #2

Поділитися
Вставка
  • Опубліковано 24 гру 2024

КОМЕНТАРІ • 645

  • @lucastraveldiaries9063
    @lucastraveldiaries9063 2 роки тому +329

    I scanned my code for nearly an hour now, trying to understand why it isnt working. Turns out I forgot one line in my game loop. After I finally found it and the code worked, I almost cried out of pure joy that the fucking rectangle finally moves. Welcome to a developers life I guess...

    • @RyiSnow
      @RyiSnow  2 роки тому +66

      Good job! I can really relate to your comment. The feeling you get when you finally figure something out by yourself is truly special. Hope you'll keep enjoying coding.

    • @barsapriyadarshinijena2084
      @barsapriyadarshinijena2084 2 роки тому +6

      Hii ..can you please tell me where you did mistake, cause mine also not working..that rectangle is not moving

    • @lucastraveldiaries9063
      @lucastraveldiaries9063 2 роки тому +5

      @@barsapriyadarshinijena2084 Hey. There was one line of code that wasi
      missing in my game loop connecting everything together. It's pretty unlikely that you have exactly the same fault. I would recommend to check your code for errors (underlined in red etc.) and after that you compare your code line for line with the tutorial. It's gonna take a while but you are gonna find the problem I'm sure. Keep searching 😇

    • @ziqianzhao363
      @ziqianzhao363 2 роки тому +1

      me toooooooooo it was just so suffering but it turned out to run successfully

    • @RaFIQYT-se5sl
      @RaFIQYT-se5sl 2 роки тому +1

      I am having some problems too my square did'nt appear and i can't initialize keyhandler

  • @operatedowl4158
    @operatedowl4158 2 роки тому +38

    If UA-cam allowed to like a video multiple times then I would like every second of this video.

  • @RyiSnow
    @RyiSnow  3 роки тому +74

    It turned out to be a pretty long video so I prepared time stamps for your reference:
    0:00 Game loop outline
    5:30 Draw an object on the screen
    8:19 Get keyboard input
    17:50 About the system time
    21:08 Construct the first game loop (sleep)
    28:04 Construct the second game loop (delta)
    31:21 Display FPS
    I know this part 2 is an uneventful and a boring episode but this is also a very important one. A lot of people give up on 2D development because they didn't build up a decent game loop. So if you're not familiar with game loop, I'd recommend you to watch the whole (especially from 17:50) and understand its concept before moving onto the next part.
    Constructing a game loop is the first big hurdle in 2D game development. I also had a hard time understanding it at first.... but it is crucial because game loop is the engine of the game. Once it is created, we can put fuels (characters, tiles, objects etc.) into it and our game can run with them. I hope you get through this so we can move onto more fun stuff!

    • @normalduck3917
      @normalduck3917 3 роки тому

      It took me a while to understand game loop

    • @adhyyankumar501
      @adhyyankumar501 Рік тому

      Hey can you pls help with my code i can't get the rectangle to move..... Sorry for replying to a 2 year old vid.
      Also, I am using Vs code java package so i don't have to write package main at the top
      //Main.java
      import javax.swing.JFrame;
      public class Main {
      public static void main(String[] args) {
      JFrame window = new JFrame();
      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      window.setResizable(false);
      window.setTitle("GameXD");
      GamePanel gamePanel = new GamePanel();
      window.add(gamePanel);
      window.pack();
      window.setLocationRelativeTo(null);
      window.setVisible(true);
      gamePanel.startGameRun();
      }
      }
      //GamePanel.java
      import java.awt.Color;
      import java.awt.Dimension;
      import java.awt.Graphics;
      import java.awt.Graphics2D;
      import javax.swing.JPanel;
      public class GamePanel extends JPanel implements Runnable{
      final int originalTileSize = 16;
      final int scale = 3;
      final int tileSize = originalTileSize * scale;
      final int maxScreenCol = 16;
      final int maxScreenRow = 12;
      final int screenWidth = maxScreenCol * tileSize;
      final int screenHeight = maxScreenRow * tileSize;
      InputHandler inputManager = new InputHandler();
      Thread gameThread;
      int playerX = 100;
      int playerY = 100;
      int playerSpeed = 4;
      public GamePanel() {
      this.setPreferredSize(new Dimension(screenWidth,screenHeight));
      this.setBackground(Color.black);
      this.setDoubleBuffered(true);
      this.addKeyListener(inputManager);
      this.setFocusable(true);
      }
      public void startGameRun() {
      gameThread = new Thread();
      gameThread.start();
      }
      @Override
      public void run() {
      while(gameThread != null){
      long currentTime = System.nanoTime();
      System.out.println("Current Time:"+currentTime);
      update();
      repaint();
      }
      }
      public void update() {
      if(inputManager.upPressed == true) {
      playerY -= playerSpeed;
      }
      if(inputManager.downPressed == true) {
      playerY += playerSpeed;
      }
      if(inputManager.leftPressed == true) {
      playerX -= playerSpeed;
      }
      if(inputManager.rightPressed == true) {
      playerX += playerSpeed;
      }
      }
      public void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D)g;
      g2.setColor(Color.white);
      g2.fillRect(playerX, playerY, tileSize, tileSize);
      g2.dispose();
      }
      }
      //InputHandler.java
      import java.awt.event.KeyEvent;
      import java.awt.event.KeyListener;
      public class InputHandler implements KeyListener{
      public boolean upPressed = false;
      public boolean downPressed = false;
      public boolean leftPressed = false;
      public boolean rightPressed = false;
      @Override
      public void keyPressed(KeyEvent e) {
      int keyCode = e.getKeyCode();
      if(keyCode == KeyEvent.VK_W) {
      upPressed = true;
      }
      if(keyCode == KeyEvent.VK_S) {
      downPressed = true;
      }
      if(keyCode == KeyEvent.VK_A) {
      leftPressed = true;
      }
      if(keyCode == KeyEvent.VK_D) {
      rightPressed = true;
      }
      }
      @Override
      public void keyReleased(KeyEvent e) {
      int keyCode = e.getKeyCode();
      if(keyCode == KeyEvent.VK_W) {
      upPressed = false;
      }
      if(keyCode == KeyEvent.VK_S) {
      downPressed = false;
      }
      if(keyCode == KeyEvent.VK_A) {
      leftPressed = false;
      }
      if(keyCode == KeyEvent.VK_D) {
      rightPressed = false;
      }
      }
      @Override
      public void keyTyped(KeyEvent e) {
      //Don't use
      }
      }

    • @netidk
      @netidk Рік тому +3

      please dont cut things even if its something small as importing something. if this is for complete beginners, dont cut things out even if its something as importing

    • @klssnv
      @klssnv 11 місяців тому

      @@adhyyankumar501sorry for replying on 9 month old comment, hope you already solved it yourself, but if not then you can try this in startGameRun() method new Thread(this);

  • @crackrokmccaib
    @crackrokmccaib 2 роки тому +102

    Thank you so much for actually teaching as you go. Other people just type stuff and say what they're typing, but you explain how things actually work. I can't thank you enough for that.

    • @RyiSnow
      @RyiSnow  2 роки тому +21

      Thank you. That means a lot to me.

  • @pvmpalways5058
    @pvmpalways5058 Рік тому +89

    by around 16:38 in the video, if you cannot get the square to move at all no matter what key you press, make sure your main class looks like this:
    package main;
    import javax.swing.JFrame;
    public class Main {
    public static void main(String[] args) {

    JFrame window = new JFrame();
    GamePanel gp = new GamePanel();

    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setResizable(false);
    window.setTitle("Title");
    window.add(gp);
    window.pack();
    window.setLocationRelativeTo(null);
    window.setVisible(true);

    gp.startGameThread();

    }
    }
    The order of the window variables matters, specifically the pack, relative, and visible ones. After setting these this way, I was able to simply run the app and everything worked as in the video up to the point at 16:38
    If you're lazy like I was before googling for more info, just simply hit tab on your keyboard and that will focus your screen to the applet so you can use WASD

    • @samjesf
      @samjesf Рік тому +4

      Thank you for this! I initially tried grouping the relative & visible methods with the others at the top of the class for appearance sake and could not for the life of me figure out why keyListener sometimes worked but most of the time did not. This fixed it for me! Much appreciated!

    • @nickyecen
      @nickyecen Рік тому +3

      Oh my god, thank you so much. I was about to quit and decided to look at the comments before quitting. You're a hero.

    • @kingrulez5268
      @kingrulez5268 Рік тому +2

      Dude you're such a lifesaver thank god you fixed so many problems bless you

    • @Anoski_Domain
      @Anoski_Domain Рік тому +1

      thnks broski

    • @brendansherlock9512
      @brendansherlock9512 Рік тому +1

      I had missed adding startGameThread to the Main class and it was driving me nuts. Thank you for the tip!

  • @MidsoH
    @MidsoH 2 роки тому +4

    こんにちは!自分はアメリカ留学生でして、コンピューターサイエンスの授業で作ってるゲームのために貴方の動画を見始めました。調べた中初心者に対して一番丁寧で、一つ一つしっかり説明しながら教えてくれてるのが、とても助かります!喋り方やPC環境で日本人だと分かり、びっくりしました!素晴らしい動画シリーズ、ありがとうございます!応援してます!

    • @RyiSnow
      @RyiSnow  2 роки тому +4

      ありがとうございます! 学習の一助になったのであれば幸いです。日本人でコメントしてくださる方は少ないので非常に嬉しいです。異国での生活はなにかと大変なこともあるかと思いますが、どうぞ貴重な機会を存分にお楽しみください!

  • @xConsoleCapturex
    @xConsoleCapturex 2 роки тому +11

    I love that you're doing all this from scratch. I know libraries exist that can do all this by default but this really helps me understand the underlying mechanics, which I believe leads to a better game

  • @МартинЙонков-ж3п
    @МартинЙонков-ж3п 3 роки тому +123

    I know it's such a simple thing for a square to just move on a screen but I felt so happy when it worked and I knew how it worked thanks!

  • @ErroTheCube
    @ErroTheCube 2 роки тому +27

    A very well put together tutorial, it has a really nice pacing and feels like it's just the right difficulty for me. Thank you!

  • @PaulO-ym5dm
    @PaulO-ym5dm 2 роки тому +4

    Sublime tutorial, very clear! Such good practice, big thanks!

    • @RyiSnow
      @RyiSnow  2 роки тому +2

      Glad you liked it and thank you so much for your kind support :D

  • @whitebeartigtig
    @whitebeartigtig 2 роки тому +28

    These tutorials really do help. I do have basic java knowledge, but I wanted to go into game development to hopefully improve my knowledge of the language. The explanations are really helping with that. Eclipse being in dark mode is certainly a nice addition too, especially when working watching in the dark. I'm sure by the time I get to the end of the playlist, I will be much better at java development.

    • @RyiSnow
      @RyiSnow  2 роки тому +5

      Glad to hear that you liked it. Hope you enjoy developing your own game!

    • @firemonkey1015
      @firemonkey1015 7 місяців тому

      Same, I’m a computer science student and finished my first year with Java. Figured this would be a good project. Definitely helps if you know how classes, data types, methods, loops, etc works

  • @amarboparai4159
    @amarboparai4159 2 роки тому +4

    I really like his accent. Also, RyiSnow is the only channel on youtube teaching how to create a complex 2D game in Java. And every step is explained so briefly.
    Mad respect for you sir. 🙌🙌

  • @postulysses
    @postulysses 2 роки тому +4

    Ευχαριστούμε!

    • @RyiSnow
      @RyiSnow  2 роки тому +1

      Thank you for supporting this channel! Greatly appreciate it.

  • @ghostek7792
    @ghostek7792 2 роки тому +3

    I LOVE YOU ryi, i just started university for software engineering and i am completely green at coding. literally everything is 100% new to me, so this summer i'm working on little projects to continue improving and getting comfortable. the video is perfectly paced in my opinion because even the content I already know is getting engrained into my memory even better. I appreciate you taking your time to make this content for others

  • @Ango_tango
    @Ango_tango 2 роки тому +4

    For anyone who wants to be able to implement diagonal movement, it is very simple. The way that if else statements work is that if the first one is true, it will not check the other statements, meaning you can not be moving both upwards and sideways, because it wont check to move sideways. To do this, you need to make a separate if statement with the left and right movement, meaning you can move either up or down, and left or right. It should look like this:
    if(keyH.upPressed == true) {
    playerY = playerY - playerSpeed;
    }
    else if(keyH.downPressed == true) {
    playerY = playerY + playerSpeed;
    }
    if(keyH.leftPressed == true) {
    playerX = playerX - playerSpeed;
    }
    else if(keyH.rightPressed == true) {
    playerX = playerX + playerSpeed;
    }

    • @Ango_tango
      @Ango_tango 2 роки тому

      also, whichever part in the if else statement comes first will take priority, meaning if you are pressing W and S, you will go up because the code checks W first.

  • @ramtejeshm9344
    @ramtejeshm9344 3 роки тому +5

    Somehow fixed the problem, if anyones keyboard input isn't being recognised, these are the things that worked for me:
    1.Update your SDK, but at start after some time my input was't being recognized again, so
    2. Close the frame window and rerun the program again, but still some times I got the error back after some time
    3. try changing keyhandler variable name
    after repeating this process I got it to work.

  • @mega_city_one
    @mega_city_one 3 роки тому +17

    A very useful tutorial, thank you for your efforts.
    I'm looking forward to the following parts.

    • @RyiSnow
      @RyiSnow  3 роки тому +2

      It took a while to make this video so I'm very happy to hear that. Thank you for the comment!

  • @zielony1212
    @zielony1212 Рік тому +10

    Pro tip: put Toolkit.getDefaultToolkit().sync(); at starting of the GamePanel::paintComponent function, so the buffer is being synchronized every frame (note that when using canvas, Toolkit.getDefaultToolkit().sync() is being ran automatycally);
    If someone wonders, it fixes the "lagging" issue.

    • @ahmedel-gohary6000
      @ahmedel-gohary6000 Рік тому +3

      Thanks! It was really helpful

    • @laz3664
      @laz3664 Рік тому +1

      Thanks a lot, it was lagging for the first second of holding a key

    • @zielony1212
      @zielony1212 Рік тому

      btw it's better to use Canvas that is actually made for such things instead of JPanel that should actually be top container for the game display (Canvas), not the display itself. @@laz3664

    • @CB-ox6vu
      @CB-ox6vu 3 місяці тому

      Thnaks, this fixed the lag for me.

    • @unaidieguez7398
      @unaidieguez7398 3 місяці тому +1

      thanks a lot!

  • @devoiddude
    @devoiddude 3 роки тому +13

    Thank you so much for this and all the effort you put into making this series.

  • @droidlycodes
    @droidlycodes 2 роки тому +6

    This is amazing, I'm trying to remaster this for Android & learning a lot more than I thought in the last 7 years of coding Java!!! I'll let you know how it goes once I run the final project, so far I've made a flappy rectangle oh the possibilities!
    Subscribed & many likes to come keep this going PLEEEASE!

  • @SzymonGaming_1
    @SzymonGaming_1 9 місяців тому +1

    Your probbebly not going to see this but anyways. You are a fantastic youtuber and a great help im knew and just got into coding so your totourials really help me a lot keep up the good work man everyone apprcates it.(also I cant spell cause I type fast so i had to fix the code like 2million times)

  • @dragonv1236
    @dragonv1236 8 місяців тому

    AMAZING tutorial you're the best! At first I've tried sleep method and the square didn't move. So I checked all my code but don't find any errors. I scanned my code for like 2 HOURS! But then I tried the delta method and it works. The second the square move I feel so happy and stupid at the same time. Don't be like me.

  • @vmardones366
    @vmardones366 2 роки тому +13

    Thanks for the tutorial, well done!
    Just a side note if you're using linux or the game is a bit laggy for no reason: add System.setProperty("sun.java2d.opengl", "true"); to your main method, to force it to use OpenGL.
    Also, since we're not using the keyTyped() method, extending KeyAdapter instead of implementing KeyListener saves a few lines of code.

    • @alessandroercolani3524
      @alessandroercolani3524 Рік тому

      Man thank you so much :D🙏

    • @cosmefulanitto8527
      @cosmefulanitto8527 3 місяці тому

      Thank you, i was having the same issue on my linux desk

    • @wafflzplz7914
      @wafflzplz7914 26 днів тому

      Thank you so much, I have tried to fix that for about 2 hours now!

    • @Zckerby
      @Zckerby 19 днів тому

      Would a switch be better to use for the movement vs if statements?

    • @wafflzplz7914
      @wafflzplz7914 19 днів тому

      @@Zckerby I used one. Probably not noticably better for performance, but my main reason was, cause it is way more readable and looks better.

  • @Rohan-Prabhala
    @Rohan-Prabhala Рік тому +2

    Does anyone why the background for my JPanel window is white? I'm at 8:01 in the video, and when I click run, my square is white, but so is my window, even though I checked the line that is supposed to make it black, and it looks fine.

    • @camilazcr1939
      @camilazcr1939 10 місяців тому

      I have the same issue, its white and not runnig well. Did u find any solution?

    • @Rohan-Prabhala
      @Rohan-Prabhala 9 місяців тому

      @@camilazcr1939 fixed it soon after i made the comment, and I completely forgot how lmao, sorry

    • @mohammadhosseinbadravandeh6637
      @mohammadhosseinbadravandeh6637 9 місяців тому

      @@camilazcr1939 I had this problem too . Look at the ( super.paintcomponent(g) )
      Perhaps you add a extra ‘s’ after paintcomponent

    • @HimanshuKumar-dz6rc
      @HimanshuKumar-dz6rc Місяць тому

      use super.paintComponent(g); instead of super.paintComponents(g);

  • @adoniszgks7641
    @adoniszgks7641 3 роки тому +4

    you deserve 1.000.000 subscribers, so easy to understand and to learn!!!

  • @Zoggi_
    @Zoggi_ 3 роки тому +8

    you explained it really well, thank you for those videos!

    • @RyiSnow
      @RyiSnow  3 роки тому +1

      Glad to hear that!

  • @michaelhall4602
    @michaelhall4602 Рік тому +1

    This is so awesome. I've been looking for something like this for a while. Thank you so much!

  • @zixvirzjghamn737
    @zixvirzjghamn737 8 місяців тому

    even though I ended up creating my own systems (jpanel instead of graphics rectangle, speed inside the object, etc.), almost all of this video was useful, I started with just a moving square, and then added keyInput later once I managed to get higher FPS's move at the same speed as lower ones. Thank you for making this tutorial.

  • @SajmonOffical
    @SajmonOffical 5 місяців тому

    I rewrote the entire code exactly and it worked, I don't know what the problem was with the earlier code, but if the code doesn't work, I advise you to rewrite it

  • @LunaticEdit
    @LunaticEdit 13 днів тому

    7:58 Just FYI, don't call g2.dispose() here. You aren't allocating the object, so you shouldn't be disposing it. Best case it does nothing. Worst case it could cause a strange crash later on. A good rule of thumb is that you always (and only) dispose objects you have specifically created.

  • @ducganktem201
    @ducganktem201 Рік тому +3

    23:50 For those who are experiencing issues with character movement that keeps moving up automatically during debugging, make sure that you simplify it to:
    public void update(){
    if(keyH.upPressed){
    playerY -= playerSpeed;
    }

  • @ortizjeison
    @ortizjeison 8 місяців тому

    Youre awesome bro, i can finally understand the logic through the FPS concept, i always read about the "threads" but i didnt understand all the meaning, now i can realize the importance of this topic in the game development, so thanks for all

  • @yaredyohannes2803
    @yaredyohannes2803 2 роки тому +1

    This is one of the best java tutorials. I have done projects on my own, whether visual or not and never really implemented crazy ideas. This tutorial alone has shown me why I learned all those techniques in my java cs classes. Also any m1 max users confused on the delta fps showing up as 0, my MacBook has the same problem but it works on my windows desktop perfectly. Might be how the m1 computes or something, however it still works. (little cheat turn the drawCount =0; int drawCount = 60; i guess it displays the drawCount after converting it to 0 (i have the assignment after the out.print).

    • @الإسلامدينالحق-خ5ت
      @الإسلامدينالحق-خ5ت 2 роки тому

      My friends, search for your life purpose, why are we here?? I advise you to watch this series and this video 👇 as a beginning to know the purpose of your existence in this life ua-cam.com/play/PLPqH38Ki1fy3EB-8xmShVqpbQw99Do2B-.html ua-cam.com/video/7d16CpWp-ok/v-deo.html

  • @HansonJ
    @HansonJ 2 роки тому +4

    I had some problems with the sleep method for some reason in KeyHandler it would automatically head to KeyTyped instead of KeyPressed and KeyReleased (preventing any movement). Switching to the delta method worked as expected so if you are having the same issue, try Delta.

    • @marcv8154
      @marcv8154 2 роки тому

      holy shit thank you for this ive been having the exact problem lmao

    • @dcwavie
      @dcwavie Рік тому

      😁❤

  • @nestor-162
    @nestor-162 4 місяці тому

    I am continuing with the course. I really like the way you explain things.

  • @Soysauceeeeeeeee
    @Soysauceeeeeeeee Рік тому

    This video was really helpful to me. I love how to you took time to explain the concepts before moving on. Its really helpful knowing that there is someone who understands the basic elements of teaching.

  • @JehanSaren
    @JehanSaren Рік тому

    this is the real logic pattern and procedure if you are teaching. it is easy to understand unlike the others are very stingy to give. haysss. Thank you for this. You are the best❤❤❤

  • @terencechia9986
    @terencechia9986 2 роки тому +2

    Thank you very much for your explanation RyiSnow 🙏 I feel like I understand what each method is doing now. As many have already said, the pacing is perfect especially for beginners like myself!

  • @Lorenzo_Talpinum
    @Lorenzo_Talpinum Місяць тому

    Just so everyone else knows, I recommend using the Thread.sleep method instead of delta time, since letting the thread sleep uses way less cpu. On my laptop it made the java program go from 8% cpu usage to less than 1%

  • @Phil1490
    @Phil1490 2 роки тому +1

    Thank you for this! Very informative, well explained, and FUN!

  • @xbeelzebub666x
    @xbeelzebub666x Рік тому

    Thanks man I don't know what I'd have done without this video.

  • @neotericfossil
    @neotericfossil 12 днів тому

    Excellent, easy to understand explanations. Thanks!

  • @juanjosesalazarrodriguez8291

    Help please, minute 8:00, The white rectangle does not appear on my screen for some reason.

  • @LogicStudios_1
    @LogicStudios_1 2 роки тому +1

    why is this tutorial so good

  • @naze8918
    @naze8918 3 роки тому +5

    Sorry, I'm having a problem move the square, the key listener isn't even responding which is weird. I've used action listeners and they haven't done this in my other codes so I am a bit worried. I'm looking for solutions in other commnets

    • @RedlikMusic
      @RedlikMusic 2 роки тому

      same problem here, any solution?

    • @boywonder_YT
      @boywonder_YT 2 роки тому +3

      if the keys are not responding use
      this.requestFocusInWindow(); at the very end of your run method

    • @GETMEBL00DY
      @GETMEBL00DY 2 роки тому

      @@boywonder_YT thank you so much, it worked

    • @eldernovaisss
      @eldernovaisss 2 роки тому

      @@boywonder_YT like? im having same problem, how can i code this?(where)

  • @kaylor87
    @kaylor87 2 роки тому +3

    When I played along, I opted to leave the Sleep loop in my code that we already made initially, and instead just observed you build the Delta loop. But upon testing, my FPS with the sleep loop tends to bounce between 59 and 61fps, versus yours was a steady 60fps. Both are accurate enough to be functional, but it does seem like the Delta loop is more accurate.

    • @AnnmusPnda
      @AnnmusPnda 2 роки тому

      I believe the delta loop is FAR more accurate. After implementing the delta loop, using my 144hz monitor and setting the FPS attribute to 144 instead of 60, I noticed a MASSIVE difference between this and the sleep loop when it came to my red box's movement. Before it felt very jittery and almost looked like my monitor had ghosting issues, but after using the delta loop which had no influence on the concurrency of the program's thread, I can see my character moving as smoothly as any game I normally play on my computer.

  • @abovethemist1412
    @abovethemist1412 2 роки тому +6

    Tip: if you cant get the keyhandler to work, press *tab* . now i know it sounds ridiculous but its literally what i had to do
    EDIT: you need the program to be open

    • @milanSK1980
      @milanSK1980 2 роки тому

      Thankx! I could not figure out why my code did not work, but the TAB did the trick (probbably it is somehow needed to really focus on the panel)

    • @edboss36
      @edboss36 Рік тому

      Thank you soooo much

    • @sakhiur
      @sakhiur Рік тому

      Thanks a lot.

    • @toinuiii
      @toinuiii 7 місяців тому

      thank you soo much I was getting really worried

  • @johnsimon8158
    @johnsimon8158 2 місяці тому

    your teaching method is awesome thanks for this awesome content. Learning this way is fun

  • @AddersOtter
    @AddersOtter 3 роки тому

    I just picked up programming again and this has been helping me out a lot.

  • @AlvaroHenrique-bp8iz
    @AlvaroHenrique-bp8iz 3 місяці тому

    cara, testei o código em dois computadores diferentes, e na parte que você faz o programa rodar em 17:00, o seu player/retângulo sai da tela, mas nestes dois computadores que testei, o retângulo ficou parado, estático. Seria algo relacionado a atualizações do java? Tendo em vista que o seu vídeo tem 2 anos de vida.

  • @henrikjohnsen9554
    @henrikjohnsen9554 2 роки тому +5

    Anyone getting stuttering in the game loop? I have tried both with thread sleep and delta time, same problem. after adding sprites with animation from the next video I can see the animation freezes up to a second sometimes. I'm running it on Linux. Does anyone have an idea why this happens and or how to fix it?
    edit: For some reason the stuttering stopped after i loaded the text file for tile map in video 4 :/

  • @saammyyeet
    @saammyyeet 2 роки тому

    tysm that Thread method is so much easier than using a Timer

  • @amarboparai4159
    @amarboparai4159 2 роки тому

    Thanks!

    • @RyiSnow
      @RyiSnow  2 роки тому

      Thank you so much!

  • @ksportalcraft
    @ksportalcraft 2 роки тому

    21:45 My tip is separate them via commas (with 3 rows of 3 3*3=9) then remove them.

  • @lilsquirt9248
    @lilsquirt9248 3 роки тому +5

    Me:I am accomplished for creating a moving square!
    Notch:Heh cute.
    Epic Games:There's no build mode...

  • @noahbarger1
    @noahbarger1 2 роки тому +3

    I'd love to see a turn based RPG tutorial, like games like EarthBound/Mother or even Final Fantasy. That would be awesome!
    ありがとう!

  • @yato3079
    @yato3079 Рік тому +4

    Does someone also experience a weird problem in the movement commands?
    When the character moves right or left you can cancel that movement without letting the key go and immediately change the direction to top or down by pressing the respective key.
    But when he moves top or down you somehow cant cancel the movement but you have to let go your key to change direction.
    The movement would be much smoother if the direction change could happen without having to release any keys though.

  • @nikissurprise6372
    @nikissurprise6372 Рік тому +1

    FYI if anyone is having problems with their square moving up or down without any input I'd recommend to; inside of the Keyhandler method update() to change the logic to simplu if()Keyhand.pressed) without the "== true;".

  • @almusknowsbetter7547
    @almusknowsbetter7547 Рік тому

    I just finished the first video and still on it this tutorial is something

  • @pixustration
    @pixustration Рік тому +3

    Note: The Thread sleep method is, in fact, a bit off. About 5 out of 6 times, you will get 61 FPS. Clearly, this isn't a big problem, just wanted to put it out there.

  • @yashuchiha99
    @yashuchiha99 9 місяців тому

    i have started the playlist today , this is really awesome . Hopefully i stay consistent and reach the last video.

  • @seal-b1n
    @seal-b1n 3 місяці тому

    dude thank you so much for this playlist
    you are a great teacher

  • @eliatrotta4070
    @eliatrotta4070 Рік тому

    at minute 27:16 in the almost impossible case that the time ends when we enter the if, instead of setting the remainingTime to 0, can we increase it by 0.016s each time?

  • @maivuduy8282
    @maivuduy8282 2 роки тому +1

    why rectangle can run out of screen when keyReleased is false?
    help

  • @megabassX
    @megabassX 10 місяців тому

    I love this series. Great job!

  • @leonidas14775
    @leonidas14775 8 місяців тому

    Modern versions of Java allow underscores in numeric literals, like in Python.
    double drawInterval = 1_000_000_000/FPS;
    Also, if you use 4 regular if statements instead of "else if" in the update() method, you can move diagonally since an if-else block only allows one choice at a time.

  • @stvnk1m
    @stvnk1m 2 роки тому

    This is cool. I'm almost finish my Java bootcamp course. Definitely I want to learn.

  • @ZenthmYT
    @ZenthmYT 2 роки тому +1

    I prefer multiplying every movement-like happening on the screen by delta (e.g: animation, player movement, enemy movement, etc.).
    delta = (currentTime - lastTime) / 1_000_000_000;
    player.x += 50 * delta // moves 50 pixels every second
    You can also get the FPS easily with this method.
    System.out.println(1/delta);

  • @kurlies3094
    @kurlies3094 29 днів тому

    need some help, the thing is, the square moves but it just turns into kinda like a snake where when i move i still leave a trail and also my background changed to white even though i set the background color black

  • @mcpjal8961
    @mcpjal8961 2 роки тому +2

    I did everything you did( before the fps and stopping the thing for moving infinitely) and for some reason rhe player just doesn't move at all even though I added the keyListener and everything. I first this veideo a couple months ago and it was working then, but when I came back to coding a week ago it hasnt worked, I tried everything.

    • @mcpjal8961
      @mcpjal8961 2 роки тому

      I tested some things and found out that the gameThread isnt working it is not updating and repainting, I tested it by doing a system.out.println("test"); , so do you have any tips on bow to get it to workin?

    • @itzelCNE
      @itzelCNE 2 роки тому

      @@mcpjal8961 Check if all the threads are running, you can see how many are on with Thread.activeCount().
      Also check the Run method

    • @CVonKotzen
      @CVonKotzen 2 роки тому +1

      @@mcpjal8961 did you remember to add gamepanel.startNewThread(); in your Main class?

  • @AurélienTousch
    @AurélienTousch Рік тому

    Thanks for you content you helped me a lot to understand the java environement!!

  • @neemair9008
    @neemair9008 3 місяці тому

    Once again it brought me to the attention to the details of programming when i started again :D my rectangle didnt stop moving up, because i was not comparing the value of keyH.upPressed to the value of the boolean. "=" is different to "==" :) thanks for the reminder lol. great work go a new subscriber for sure

  • @melicus8384
    @melicus8384 Рік тому +3

    Just in case anyone's still using this tutorial and can't get their rectangle to move, make sure to set the focus on the right component. In your constructor, make sure to use this.setFocusable(true); and if that doesn't work you can create a mouseListener object to set the focus. Use:
    this.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
    requestFocusInWindow();
    }
    });
    after this.setFocusable(true);. That's the only thing that worked for me. I hope it helps someone out there.

    • @pascubidichu1890
      @pascubidichu1890 24 дні тому

      Thank you soo much, I really appreciate your comment, it really help me, I was looking at my code for almost 2 hours and couldn't find any errors and my rectangle just wouldn't move, I just added the line of code 'this.setFocusable(true);' and it solved the problem, thank you very much 🎉❤

  • @Bigz2006
    @Bigz2006 Рік тому

    didn't understand anything of what you did since 21:08. I will be happy if someome explains to me why do you need all of those confusing variables that don't make sense to me instead of just doing Thread.sleep(10) or something.

  • @mamapuci
    @mamapuci 2 роки тому

    Really helping with such amazing explanation. Really really thanks bro. I followed another parts

  • @konsi_baua
    @konsi_baua 2 роки тому +1

    Ik it is a old vid but if any1 can help me I have a small problem with the boolean down up rigth and leftpressed being all on true and not changing to false even if I state so in a Variable any ideas?

  • @mexd2242
    @mexd2242 Місяць тому

    12:10 i got error on this line i dont know how to fix it

    • @mexd2242
      @mexd2242 Місяць тому

      nvm rewrote it all and it somehow works now

  • @cameronskinner806
    @cameronskinner806 2 місяці тому

    if your white box wont show, check to make sure the paintComponent method is spelled correctly (no capital p)
    or else repaint() wont work

  • @rogevoliasim1926
    @rogevoliasim1926 2 роки тому +1

    repaint() method doesn't work. I don't know why, I did it exactly like on the video. I checked many times and I don't see any mistakes(((

    • @rogevoliasim1926
      @rogevoliasim1926 2 роки тому

      So when I start it, it shows just a black panel without anything

    • @wizco4443
      @wizco4443 2 роки тому

      I have the same issue, where yo able to fix it?

    • @tungstun-o1d
      @tungstun-o1d 3 місяці тому

      any fixes ?

  • @חנןאורנל
    @חנןאורנל 2 місяці тому

    Something else is wrong with mine... I literally removed every mention of the word "static" from my code, and it still says that the startGameThread method can't be reffered through a static context

  • @paskanttipuuro69420
    @paskanttipuuro69420 2 роки тому +1

    why doesnt my movement work i mean i do everything correctly and nothing happens when i try to move.

  • @christianthieme4455
    @christianthieme4455 Рік тому

    Great tutorial. I believe using the delta approach in the run method will utilize one CPU core constantly at 100%, might not be ideal for battery powered devices.

  • @RamRevivo
    @RamRevivo Рік тому +1

    this is great but I noticed something odd..
    my rectangle moves faster as the frames are higher
    in 30 fps my rectangle moves a certain speed but at 60 or 120 the rectangle moves way faster
    I was wondering why and how can I avoid this as this doesn't seem normal..

  • @nathanwhite704
    @nathanwhite704 4 місяці тому

    Ok, I rewrote everything from the beginning and now it magically decides to work.

  • @NikitaBomba112
    @NikitaBomba112 2 роки тому +1

    Thanks you so much for this video!

  • @ecernosoft3096
    @ecernosoft3096 Рік тому

    I really appreciate this series!!!! :D
    Tysm!!

  • @dominicnobleza1090
    @dominicnobleza1090 2 місяці тому

    i need help, i followed the steps in this video but no matter what i do my square only moves up when i press w,a,s,d

    • @eltodomensing
      @eltodomensing 2 місяці тому

      true, it's happening me and i don't know what is the problem

  • @yoraiyaniv1713
    @yoraiyaniv1713 2 роки тому +1

    my program dosent even get to the keyPressed event. why?

    • @edboss36
      @edboss36 Рік тому

      click on your game window and press the TAB key. Try that, it worked for me

  • @ІлляТкачов
    @ІлляТкачов 2 роки тому

    Thread.sleep() in a loop can cause busy-waiting, so wait/notify mechanisms should be used instead

  • @hatdog2388
    @hatdog2388 2 роки тому

    Thank you for this, i am one step closer to program my own game

  • @bluestreak711
    @bluestreak711 2 роки тому +1

    I made it to the 28m0s mark before having to leave to do errands, but my two questions so far are these:
    Why did we use else if statements instead of a switch statement for the keyH variables?
    How can we assign the arrow keys to move the character instead of wsad?

    • @RyiSnow
      @RyiSnow  2 роки тому

      You can use a switch too. Either way is fine. If you want to use arrow keys, you can type VK_UP, VK_DOWN, VK_LEFT, and VK_RIGHT.

  • @masterofgames5434
    @masterofgames5434 Рік тому +1

    why the triangle not apear, i dd everything same like you

  • @tamerbarraj
    @tamerbarraj Рік тому +1

    I didnt really understand the first game loop, can anyone explain it to me please?

    • @hrvojekozul4952
      @hrvojekozul4952 Рік тому +1

      Watching this for first time, so I'm not sure if I got it right, but here is how I understood it: you do the update() and repaint(). Then you figure out the remaining time, and Thread.sleep() just waits it out for example if you used 1 frame to update and repaint, thread.sleep will wait out remaining 59 frames and basically pause the program for a bit. Once sleep is over then program just extends next draw time for another 60 frames (+= drawInterval) and it starts from beginning of while loop. Not sure why try-catch has to be used but it is something sleep() doesn't work without. In rare case time is < 0 it will set time to 0 and sleep() will just wait for 0 seconds which makes sense instead waiting for negative seconds.
      Hopefully you understood me im like 70% sure that this is correct what I wrote above.

    • @tamerbarraj
      @tamerbarraj Рік тому

      @@hrvojekozul4952 thanks, I think I understand it more now thought its still a little unclear...

  • @kamisama1712
    @kamisama1712 4 місяці тому

    excited to be doing this again

  • @ProfDaniloSoares
    @ProfDaniloSoares 28 днів тому

    Delta method ends up using a lot more of the processor than Sleep method. How would one minimize the CPU overusage?

  • @seokje6400
    @seokje6400 Рік тому

    followed everything exactly but i cannot see the rectangle, using vs code if that helps

  • @AmarKumar-iy9by
    @AmarKumar-iy9by Рік тому +1

    Actually I am facing problem like rectangle isn't appearing where is this mistake I had done I unable to figure it out would anybody please 🙏 help me if possible please 🙏

  • @DaniloMotaSoares
    @DaniloMotaSoares 2 роки тому +2

    I presonally prefered the sleep() method because it lets the CPU rests a little. With the delta my CPU usage was 30%. With the sleep method is 5%;

    • @janmuller3290
      @janmuller3290 2 роки тому

      do u know how to display the fps with the sleep method?

    • @DaniloMotaSoares
      @DaniloMotaSoares 2 роки тому +1

      @@janmuller3290 No friend. I didn't cared much for displaying the FPS

  • @user-ov1ps7go4m
    @user-ov1ps7go4m Рік тому

    28:30
    Delta method

  • @AxajonOFFICIAL
    @AxajonOFFICIAL 10 місяців тому

    Hello. In the 'Main' file, when I type GamePanel.startGameThread(); it says this - Non-static method 'startGameThread()' cannot be referenced from a static context. Pls help.

    • @RyiSnow
      @RyiSnow  10 місяців тому

      You need to instantiate the class to call non-static methods. Check what I did in the video!

    • @AxajonOFFICIAL
      @AxajonOFFICIAL 10 місяців тому

      I can't understand how to do it. Please help. Instead of doing that I have written it in the constructor of the GamePanel. Is that fine?@@RyiSnow

    • @RyiSnow
      @RyiSnow  10 місяців тому

      Check the Part 1 video! That's where we instantiated the GamePanel class.