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 Жыл бұрын
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 Жыл бұрын
Hii ..can you please tell me where you did mistake, cause mine also not working..that rectangle is not moving
@lucastraveldiaries9063 Жыл бұрын
@@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 Жыл бұрын
me toooooooooo it was just so suffering but it turned out to run successfully
@RaFIQYT-se5sl Жыл бұрын
I am having some problems too my square did'nt appear and i can't initialize keyhandler
@crackrokmccaib2 жыл бұрын
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.
@RyiSnow2 жыл бұрын
Thank you. That means a lot to me.
@user-vm1gg8ph8r2 жыл бұрын
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!
@RyiSnow2 жыл бұрын
I can relate to that!
@mlsgbbrasil9006 Жыл бұрын
I m loving the tutorial!
@pvmpalways5058 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
Dude you're such a lifesaver thank god you fixed so many problems bless you
@Anoski_Domain Жыл бұрын
thnks broski
@brendansherlock9512 Жыл бұрын
I had missed adding startGameThread to the Main class and it was driving me nuts. Thank you for the tip!
@RyiSnow2 жыл бұрын
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!
@normalduck39172 жыл бұрын
It took me a while to understand game loop
@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 Жыл бұрын
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
@klssneva7 ай бұрын
@@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);
@operatedowl41582 жыл бұрын
If KZfaq allowed to like a video multiple times then I would like every second of this video.
@whitebeartigtig2 жыл бұрын
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.
@RyiSnow2 жыл бұрын
Glad to hear that you liked it. Hope you enjoy developing your own game!
@firemonkey10153 ай бұрын
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
@ErroTheCube2 жыл бұрын
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!
@xConsoleCapturex Жыл бұрын
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
@amarboparai4159 Жыл бұрын
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. 🙌🙌
A very useful tutorial, thank you for your efforts. I'm looking forward to the following parts.
@RyiSnow2 жыл бұрын
It took a while to make this video so I'm very happy to hear that. Thank you for the comment!
@ghostek77922 жыл бұрын
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
@vmardones366 Жыл бұрын
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 Жыл бұрын
Man thank you so much :D🙏
@abovethemist1412 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
Thank you soooo much
@sakhiur11 ай бұрын
Thanks a lot.
@toinuiii3 ай бұрын
thank you soo much I was getting really worried
@devoiddude2 жыл бұрын
Thank you so much for this and all the effort you put into making this series.
@ramtejeshm93442 жыл бұрын
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.
@nathanwhite7044 күн бұрын
Ok, I rewrote everything from the beginning and now it magically decides to work.
@nestor-1627 күн бұрын
I am continuing with the course. I really like the way you explain things.
@misterdneh2 жыл бұрын
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!
@SajmonOfficalАй бұрын
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
@lilsquirt92482 жыл бұрын
Me:I am accomplished for creating a moving square! Notch:Heh cute. Epic Games:There's no build mode...
@Zoggi_2 жыл бұрын
you explained it really well, thank you for those videos!
@RyiSnow2 жыл бұрын
Glad to hear that!
@zixvirzjghamn7373 ай бұрын
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.
@dragonv12363 ай бұрын
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.
@yaredyohannes28032 жыл бұрын
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).
@user-ri2ms2mm7w2 жыл бұрын
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 kzfaq.info/sun/PLPqH38Ki1fy3EB-8xmShVqpbQw99Do2B- kzfaq.info/get/bejne/bcphaaahvNaRn58.html
@terencechia99862 жыл бұрын
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!
@kamisama17129 күн бұрын
excited to be doing this again
@SzymonGaming_15 ай бұрын
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)
@ortizjeison4 ай бұрын
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
@adoniszgks76412 жыл бұрын
you deserve 1.000.000 subscribers, so easy to understand and to learn!!!
@michaelhall46028 ай бұрын
This is so awesome. I've been looking for something like this for a while. Thank you so much!
@user-px5pj7ux5k11 ай бұрын
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❤❤❤
@zielony1212 Жыл бұрын
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 Жыл бұрын
Thanks! It was really helpful
@laz3664 Жыл бұрын
Thanks a lot, it was lagging for the first second of holding a key
@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
@expertblober4533 Жыл бұрын
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.
@noahbarger1 Жыл бұрын
I'd love to see a turn based RPG tutorial, like games like EarthBound/Mother or even Final Fantasy. That would be awesome! ありがとう!
@PaulO-ym5dm2 жыл бұрын
Sublime tutorial, very clear! Such good practice, big thanks!
@RyiSnow2 жыл бұрын
Glad you liked it and thank you so much for your kind support :D
@Venixx-72 Жыл бұрын
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.
@postulysses2 жыл бұрын
Ευχαριστούμε!
@RyiSnow2 жыл бұрын
Thank you for supporting this channel! Greatly appreciate it.
@Phil14902 жыл бұрын
Thank you for this! Very informative, well explained, and FUN!
@angusbotham2049 Жыл бұрын
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; }
@angusbotham2049 Жыл бұрын
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.
@LogicStudios_12 жыл бұрын
why is this tutorial so good
@xbeelzebub666x Жыл бұрын
Thanks man I don't know what I'd have done without this video.
@AddersOtter2 жыл бұрын
I just picked up programming again and this has been helping me out a lot.
@NikitaBomba112 Жыл бұрын
Thanks you so much for this video!
@megabassX5 ай бұрын
I love this series. Great job!
@stvnk1m Жыл бұрын
This is cool. I'm almost finish my Java bootcamp course. Definitely I want to learn.
@yashuchiha995 ай бұрын
i have started the playlist today , this is really awesome . Hopefully i stay consistent and reach the last video.
@saammyyeet2 жыл бұрын
tysm that Thread method is so much easier than using a Timer
@mamapuci2 жыл бұрын
Really helping with such amazing explanation. Really really thanks bro. I followed another parts
@user-pr1dh7eb7p Жыл бұрын
Thanks for you content you helped me a lot to understand the java environement!!
@Rohan-Prabhala Жыл бұрын
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.
@camilazcr19396 ай бұрын
I have the same issue, its white and not runnig well. Did u find any solution?
@Rohan-Prabhala5 ай бұрын
@@camilazcr1939 fixed it soon after i made the comment, and I completely forgot how lmao, sorry
@mohammadhosseinbadravandeh66374 ай бұрын
@@camilazcr1939 I had this problem too . Look at the ( super.paintcomponent(g) ) Perhaps you add a extra ‘s’ after paintcomponent
@nikissurprise6372 Жыл бұрын
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;".
@HansonJ2 жыл бұрын
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 Жыл бұрын
holy shit thank you for this ive been having the exact problem lmao
@dcwavie Жыл бұрын
😁❤
@ducganktem20110 ай бұрын
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; }
@akashmajji3595 ай бұрын
Still not working dude
@nonymousx Жыл бұрын
If anyone is having trouble with their rectangle not moving, make sure you assign the boolean value false to upPressed, downPressed, leftPressed and rightPressed :)
@ecernosoft309610 ай бұрын
I really appreciate this series!!!! :D Tysm!!
@agzainy99542 жыл бұрын
thank you so much this is life changing!!
@almusknowsbetter754711 ай бұрын
I just finished the first video and still on it this tutorial is something
@leonidas147754 ай бұрын
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.
@hatdog23882 жыл бұрын
Thank you for this, i am one step closer to program my own game
@henrikjohnsen95542 жыл бұрын
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 :/
@DravenFNM2 жыл бұрын
Thank you for these videos they’re really helpful
@yato3079 Жыл бұрын
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.
@Niclaas Жыл бұрын
did u fix it?
@benghazzi2 жыл бұрын
Thank you so much, very good Tutorial!
@enginanil5412 Жыл бұрын
bro thank you. you can really good explain things!
@quarkzyhn43912 жыл бұрын
I love you man! Thank you so much for the lessons ☺️
@ZenthmYT Жыл бұрын
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);
@kaylor872 жыл бұрын
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.
@AnnmusPnda2 жыл бұрын
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.
@lordofthelair67162 жыл бұрын
Nice video man!
@jarrodmcevoy2 жыл бұрын
Great explanation!!!😁
@RyiSnow2 жыл бұрын
Thanks! 😃
@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.
@rauk55516 ай бұрын
FPS Counter for the first gameloop: @Override public void run() { double frameInterval = 1000000000/fps; double nextFrameTime = System.nanoTime() + frameInterval; long frameCount = 0; long startTimer; long endTimer; long executionTime; long totalTimeExecution = 0; while(gameThread != null) { startTimer = System.nanoTime(); update(); repaint(); frameCount++; if(totalTimeExecution >= 1000) { System.out.println("FPS: "+ frameCount); frameCount = 0; totalTimeExecution = 0; } try { double remainingTime = nextFrameTime - System.nanoTime(); remainingTime = remainingTime/ 1000000; if(remainingTime < 0) { remainingTime = 0; } Thread.sleep((long) remainingTime); nextFrameTime += frameInterval; }catch (InterruptedException ex) {} endTimer = System.nanoTime(); executionTime = (endTimer - startTimer) / 1000000; //System.out.println("Tempo para executar frame: "+ executionTime +"ms"); totalTimeExecution += executionTime; } } You also will need to create a int fps = (any number, preferred 60 or 30) variable for your GamePanel.
@SlothfulSage2852 жыл бұрын
Thanks! Another great video!
@bruhidk33414 ай бұрын
bro is making shure my whole class gets to pass the grade and doesnt even realise it
@dorieta_gaming2 жыл бұрын
Literally my new hero.
@paskanttipuuro694202 жыл бұрын
why doesnt my movement work i mean i do everything correctly and nothing happens when i try to move.
@kogashinto21232 жыл бұрын
This helped me so much. Thank you.
@ceraks_1272 Жыл бұрын
thanks a lot!!! so nice reverb
@normalercarl Жыл бұрын
this tutorial was done very well 👍
@tomasmarta50282 жыл бұрын
I love this channel so much thank you
@giovannizotti85499 ай бұрын
If, before any keystroke, your rectangle goes up, outside from the frame, maybe you have used "=" instead of "==" in your update() method. Just check this and it works :-P
@joshhhhhhhhhhhhhh8 ай бұрын
thank you for making these. on to part threeeeeeee
@ksportalcraft Жыл бұрын
21:45 My tip is separate them via commas (with 3 rows of 3 3*3=9) then remove them.
@james34142 жыл бұрын
really enjoying this, ty a lot
@vistasinconnection96782 ай бұрын
I had typed "else if (keyH.rightPressed = true)" It took me a day to work out why it kept flying to the right.. lol this is really teaching me something. Thank-you
@Brx9skXD7 ай бұрын
I can understand☹️ how hard english is for japanese!! I appreciate that😭 ❤
@melicus8384 Жыл бұрын
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.
@naze89182 жыл бұрын
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
@RedlikMusic2 жыл бұрын
same problem here, any solution?
@boywonder_YT2 жыл бұрын
if the keys are not responding use this.requestFocusInWindow(); at the very end of your run method
@Aaron762 жыл бұрын
@@boywonder_YT thank you so much, it worked
@novaisss91612 жыл бұрын
@@boywonder_YT like? im having same problem, how can i code this?(where)
@user-jo5nm7mv5n Жыл бұрын
Thread.sleep() in a loop can cause busy-waiting, so wait/notify mechanisms should be used instead
@ikninja1hd2 жыл бұрын
Great video, thanks a lot!
@maivuduy82822 жыл бұрын
why rectangle can run out of screen when keyReleased is false? help
@ParalyticAngel5 ай бұрын
I have tested both FPS implementations, too. The sleep edition keeps my CPU 4 -5 degrees cooler, cause off the sleeps. But the rectangle does lag a bit. With the second edition the rectangle moves far more smoother. I'll go with the second one.^^ I also tried with changing the FPS to 64, because off the LRU should do RIGHT SHIFT 5. But I couldn't see a difference. Maybe because it is later divided by drawIntervall, which surely won't be a smooth binary number for SHIFTING.^^
@flow20352 ай бұрын
Thanks...you are a legend!
@user-ov1ps7go4m Жыл бұрын
Thankfully it worked! But unfortunately the Delta method was too difficult for me 😅
@sparklecharmer Жыл бұрын
Imagine that the Delta variable tracks the difference between the current time and last time, and when it reaches the draw interval we know enough time has passed so we run the updates. Now imagine you divide everything by the draw interval. The maximum value of Delta is now 1 (something divided by itself is 1), and the difference between the current time and last time is also a fraction of delta. Instead of Delta eventually adding up to that difference, it just adds up to 1 instead. As far as I can tell you can also implement the Delta method without the division. I hope this was helpful!
@user-ov1ps7go4m Жыл бұрын
@@sparklecharmerthank you very much for your input!
@konsi_baua2 жыл бұрын
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?
@rogevoliasim19262 жыл бұрын
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(((
@rogevoliasim19262 жыл бұрын
So when I start it, it shows just a black panel without anything
@wizco4443 Жыл бұрын
I have the same issue, where yo able to fix it?
@akatsukishark6309 Жыл бұрын
now i am in a good mood
@StefanNikic24072 жыл бұрын
Lost all progress up to the end of this video, the PC didin't shut down in the corect way, therefor the project didin't save...Here we go again, all I had to do was follow the damn train... (CJ) 🤣🤣 PS: Great tutorial btw 👍👍👍 Edit: Add this to your code so the sqare can go sideways: if ((keyH.upPressed && keyH.leftPressed) == true){ playerSpeed = 2; playerX -= playerSpeed; playerY -= playerSpeed; } else if ((keyH.upPressed && keyH.rightPressed) == true){ playerSpeed = 2; playerX += playerSpeed; playerY -= playerSpeed; } else if ((keyH.downPressed && keyH.leftPressed) == true){ playerSpeed = 2; playerX -= playerSpeed; playerY += playerSpeed; } else if ((keyH.downPressed && keyH.rightPressed) == true){ playerSpeed = 2; playerX += playerSpeed; playerY += playerSpeed; }
@lofipixel2 жыл бұрын
i dont know what i have done wrong but no matter what key i press the square moves up can you help? also great tutorial :)
@lofipixel2 жыл бұрын
my code: MAIN------------------- package main; 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("2D Adventure"); GamePanel gamePanel = new GamePanel(); window.add(gamePanel); window.pack(); window.setLocationRelativeTo(null); window.setVisible(true); gamePanel.startGameThread(); } } Game Panel---------------------------- package main; 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{ //SCREEN SETTINGS final int originalTileSize = 16; //16 x 16 tile final int scale = 3; final int tileSize = originalTileSize * scale;//48 x 48 tile final int maxScreenCol = 16; final int maxScreenRow = 12; final int screenWidth = tileSize * maxScreenCol; final int screenHieght = tileSize * maxScreenRow; //FPS int FPS = 60; KeyHandler keyH = new KeyHandler(); Thread gameThread; //players default position int playerX = 100; int playerY = 100; int playerSpeed = 4; public GamePanel() { this.setPreferredSize(new Dimension(screenWidth, screenHieght)); this.setBackground(Color.black); this.setDoubleBuffered(true); this.addKeyListener(keyH); this.setFocusable(true); } public void startGameThread() { gameThread = new Thread(this); gameThread.start(); } @Override // SLEEP METHOD -> // public void run() { // double drawInterval = 1000000000/FPS; // double nextDrawTime = System.nanoTime() + drawInterval; // while(gameThread != null) { //System.out.println(("Program Running")); // 1 UPDATE: update information such as the characters positions // update(); // 2 Draw: draw the screen with the updated information // repaint(); // try { // double remainingTime = nextDrawTime - System.nanoTime(); // remainingTime = remainingTime/1000000; // // if(remainingTime < 0) { // remainingTime = 0; // } // // Thread.sleep((long)remainingTime); // // nextDrawTime += drawInterval; // // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // DELTA METHOD-> public void run() { double drawInterval = 1000000000/FPS; double delta = 0; long lastTime = System.nanoTime(); long currentTime; long timer = 0; int drawCount = 0; while(gameThread != null) { currentTime = System.nanoTime(); delta += (currentTime - lastTime) / drawInterval; timer += (currentTime - lastTime); lastTime = currentTime; if(delta >= 1) { update(); repaint(); delta--; drawCount++; } if(timer >= 1000000000) { System.out.println("FPS:" + drawCount); drawCount = 0; } } } public void update() { if(keyH.upPressed == true) { playerY -= playerSpeed; System.out.println("up pressed"); } else if(keyH.downPressed == true) { playerY += playerSpeed; System.out.println("down pressed"); } else if(keyH.leftPressed == true) { playerX -= playerSpeed; System.out.println("left pressed"); } else if(keyH.rightPressed == true) { playerX += playerSpeed; System.out.println("right pressed"); } } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.white); g2.fillRect(playerX, playerY, tileSize, tileSize); g2.dispose(); } } KEY HANDLER------- package main; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class KeyHandler implements KeyListener{ public boolean upPressed, downPressed, leftPressed, rightPressed; @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if(code == KeyEvent.VK_W);{ upPressed = true; } if(code == KeyEvent.VK_S);{ downPressed = true; } if(code == KeyEvent.VK_A);{ leftPressed = true; } if(code == KeyEvent.VK_D);{ rightPressed = true; } } @Override public void keyReleased(KeyEvent e) { int code = e.getKeyCode(); if(code == KeyEvent.VK_W);{ upPressed = false; } if(code == KeyEvent.VK_S);{ downPressed = false; } if(code == KeyEvent.VK_A);{ leftPressed = false; } if(code == KeyEvent.VK_D);{ rightPressed = false; } } }
@RyiSnow2 жыл бұрын
Check your KeyHandler and make sure there is no unnecessary ; in the if statement.
@lofipixel2 жыл бұрын
@@RyiSnow it worked thank you so much ive been sitting here for like 4 hours lol
@rabomeister Жыл бұрын
@@lofipixel I do not have any difference in KeyHandler and still having the same problem.