Sprites and Animation - How to Make a 2D Game in Java #3
Вставка
- Опубліковано 11 жов 2021
- In this video, we will import player sprites and display them on the screen. We also create a simple animation system so the player character looks like it's walking.
For IntelliJ users:
• Reading Resource Files...
If you want to use the player sprites in the video, here's the link:
drive.google.com/drive/folder...
Guidelines for using Blue Boy Adventure's code and assets:
docs.google.com/document/d/1q...
The website (Piskel) that I used to create the sprites:
www.piskelapp.com/p/create/sp...
If you have any questions, please leave a comment!
#javatutorial #javagamedevelopment #java2d #javaretrogame
To see how to read images in IntelliJ, please check this video:
ua-cam.com/video/Q9jtg0ocGgo/v-deo.html
It seems quite a few people are struggling with "java.lang.IllegalArgumentException: input == null!" error.
In case of this video, the error happens when the program fails to read sprite images.
First, *make sure to check if your res folder has been registered as a source folder*
Especially if you are not using Eclipse since the registration/resource reading process in other IDEs can be different from what I did in the video.
Also, check if your file names/paths are identical to what you typed in the getPlayerImage method. Check for any unnecessary space, underscore, or other characters. *The file names and paths need to be completely identical.* If you cannot find any discrepancy, try using the same sprites in the video (the link is in the description). If you could display the images, the issue was caused by your modification so you can narrow it down.
You can check if image loading is done properly or not by inserting these lines in the getPlayerImage method:
System.out.println("Image loading started");
// load sprite images....
// load sprite images....
System.out.println("Image loading ended");
The loading was done properly if the second text was printed on the console. If only the first text was printed out, something went wrong during the loading and the program stopped there.
In my case i am doing it on vs code. This error occurred. I solve it by changing the path, in my case the path is: "./../src/player/boy_right_2.png", for example.
@Jackson Hello man. Look my answer below, it could help you!
@@unity_with_timoteo did you type this "./../src/player/boy_right_2.png" only or not
@Jackson did you can compile it?
you should pin this comment, it was very helpfull.
for IntelliJ users:
1) create "res" folder:
- right mouse button on main project folder -> New -> Directory -> "res"
2) mark "res" folder as Sourses Root:
- right mouse button on "res" folder -> mark directory as -> Sources Root
3) create "player" folder inside "res" folder:
- right mouse button on "res" folder -> new -> Package -> "player"
4) paste images in "player" folder
5) you have to add .getClassLoader() between getClass() and .getResourceAsStream()
OLD:
up1 = ImageIO.read(getClass().getResourceAsStream("player/boy_up_1.png"));
NEW:
up1 = ImageIO.read(getClass().getClassLoader().getResourceAsStream("player/boy_up_1.png"));
This comment right here is pure gold, thank you so much ❤❤
THANK YOU SO MUCH!
I had to add a try catch to getPlayerImage()
try {
getPlayerImage();
}catch (Exception e){
System.out.println("getPlayerImage() is not working");
}
there's several solutions posted for IntelliJ, but somehow NOTHING works for me... always get NullPointerException
I give up
omg I just forgot to add
setDefaultValues();
getPlayerImage();"
I'm so annoyed at myself :((((
My son and I finished episode 3 of your series tonight. You do an excellent job explaining everything and teach at the perfect pace. We were both so excited when the little blue haired boy started walking around. Will continue the series tomorrow with episode 4. Thank you!
It warms my heart to hear that! I hope you and your son will keep enjoying coding :)
You deserve more viewers! I have learned so much from you
Glad it helped! Thank you for the comment.
Well most ppls don't play java games no more except for me
@@thenolife1957 minecraft is originally made in java
@@faced2404 except from that
Heheeee
I came across your tutorials just a few days ago, but they are helping tremendously with making a space invaders esque game. Thank you so much Ive been learning a LOT
This series is so good. I've been interested in making actual games for a long time, but I've had a lot of struggle learnign unity, and I was about ready to give up, but now I've this AMAZING series to help me use the language I'm really familiar with to make real games.
I've made some pretty cool console based games before, like this whole tower defense game which was displayed to the player exclusively in text, but games like that have obviously an incredibly niche appeal. That's why I'm so excited to really branch out like this.
Please keep making these amazing videos.
wut this aint unity lol
@@Ashokkumar31082 I am a little late but he probably meant that he struggled with Unity, but now he found this tutorial to NOT use Unity to create his games, so that he doesn't struggle so much with making games. I hope I could enlighten you.
I'm following along your tutorial, and I can say I'm having a lot of fun creating this game. Thank you for putting this together and for posting the resources needed to create the game. Your explanations are very easy to follow and does not take too long.
Man. you are actually a legend. You deserve like more than 1 mil subscribers. Youre the greatest!
Thank you for this tutorial. This has been very easy to follow and learn from! I'm a beginner and didn't know a thing before I started this series.
Glad it was helpful!
Thank you so much for making time to share this tutorial with us! I’m really grateful!
No problem :) I'm glad you liked it!
I love that you did this. you're really great at teaching it srsly dude don't underestimate your talent. I greatly appreciate your videos, I'm doing this as a summer project and I make edm so I'm going to be making full tracks for different settings and looking forward to drawing little characters
Your explanations are very clear and straight forward! Great video! (I subscribed).
thank you so much for the amazing help
Can i say it? YOU ARE A THE BEST TEACHER THAT I EVER HAD! Thank you very much, fantastic tutorial.
Thank you sir, I have always understood concepts of java but never really understood when to use them. Using your tutorial i was able to get a basic hold of 2d programming I hope you become a more popular teacher cause your teaching techniques are excellent and as always Thank You!
I'm just happy I got my sprite character to move, since started this tutorial 2 days ago its fun learning game dev again 😁 Thanks RyiSnow
Glad to hear that and welcome back to game dev :D
Your tutorials are amazing man, keep it up!!!
Thanks, will do!
Thank you so much. This has been really fun and very informative.
Enjoying this series a lot. Thank you.
You're so incredibly talented at what you do. I hope you have a job that appreciates your skill and pays you generously for what you can do. I hope to someday be even 1/4 the developer that you are.
I'm just a mediocre programmer. I'm sure you can catch up :)
You are doing a great job ! I will tell my friends about you !!!
Your art skills are great, spent a few hours last night messing around with converting your guide to Android so far I have an un animated sprite that can move around the screen smoothly. I'm going to see what I can learn tonight, I feel so new lol.
Also I enjoy that you explain things easily, plus everything makes sense from someone that does have java experience! With your permission I may do guides on this while I'm following along to convert to Android 😁
Thank you mate! This is the best series in UA-cam...keep going!!
If anyone is having issues where they are getting no errors but nothing is drawn be sure to add the getPlayerImage(); method to the player constructor in the Player class. (Just under setDefaultValues ();)
thx
@@easypeezy9142 Glad I could help 😄
I was stuck for 2 hours. Thank you very much!
@@sisonjeronimo2742 You're welcome 😄 I'm glad I could help!
TYSM!!!!
Бро, ты лучший❤
Ты единственный на кого я подписался не из вежливости, а из уважения к твоему труду и твоим знаниям!
You make awesome tutorials! Thank you!
Hello there. I just started learning a few days ago the beautiful language "java"..I am very glad I found your channel, a few video and already helped me understand more than just reading 📚.
You deserve more views for sure.
Keep up the good work. Wishing you a lot of success 🙌🏼
Thank you for your kind words!
thank you very much for these wonderful video tutorials. An excellent resource !
I now have ca. 3 or 4 years of programming experience in Java and Python. But sometimes I simply dont know how to implement somthing clean. Sure I could do it, but it will look like shit. You helped me a lot, how to implement all the stuff objectoriented. And a lot of times I think to abstract.
Also I like your tutorials because you write all the stuff from scratch, only with the default java libarys. There are a lot of youtubers out there that would simply download Unity for 2D game development - im ok with that. But its hard to find good tutorials how to programm a 2D game engine from scratch. Also a lot of people is hating on Java, I cant understand that.
Im intrested where you learned java.
Keep it up, really good work and videos.
Yes, I also feel nothing against using engines such as Unity. If making a game is your sole purpose, using engine or library is a lot easier. That said developing it from scratch gives you deeper understanding on how game programs work and programming itself. Also, creating from scratch is fun! I'm glad you liked the videos. Always good to meet a fellow Java developer!
Cool video , I learned a lot from you.Thanks
You are a great teacher man! Arigato!
Can't wait for the background tiles :)
Thanks, very informative video!
Thanks you so much for this video!
I’m an elementary student, this is very easy to understand, thanks!
Im here bro. Ehehe. Really, lot learning from you. Thanks again bro
Nice video, I really enjoy your content! I also like to develop 2D tile-based games in Java, this series seems to be a good resource for me!
Do you also use the entity component system (ECS) pattern for any of your games? I recently found out about it and I think it is a great way to structure code for this kind of games.
You are just so amazing !
I LOVE YOUR VIDEOS!. I made a few tweaks to this code, there I made use of arrays for my animation frames since i had 4 frames per walk cycle. I also made it so I could tweak the timing per frame more easily, and a few other things. its functionally the same but i love this engine your making and im learning a ton.
Nice video man!
Thanks!
3k like. Thanks for your tutorials man
I'm really enjoying this series so far. it's getting me back on my feet with a lot of my coding knowledge. i just noticed that you're putting a lot of your boolleans into your if statements with a equivalency check when boolleans are automatically true or false values. I just wanted to point out you could write it as "if(keyH.upPressed)" instead of "if(keyH.upPressed == true)" to save some space. I hope this can help someone out there. (Again, this only works for boollean variables.)
Great Tutorial! Ive been loving it so far! Please keep uploading!
For anyone who uses another IDE than RyiSnow and can't fix the "java.lang.IllegalArgumentException: input == null!" error here are solutions for VS Code and Intellij that worked for me:
For Intellij:
1. Create the "res" folder as a new package in the src folder/section
2. Create the player folder in res as player.res so that it is a package inside of the "res" package
3. Add /res to the file path in the getPlayerImage-method so that it becomes "/res/player/boy....."
4. enjoy
For VS Studio:
1. Create the "res" folder in the src folder/section
2. Create the "player" folder in the "res" folder
3. Add /res to the file path in the getPlayerImage-method so that it becomes "/res/player/boy....."
4. enjoy
The error most likely occurs because only the "src" folder is saved in the project source folder
THANKYOU SO MUCH
it happens to me in eclipse, i don't know why, could you please help me?
Thank you so much ryi
Not at all. It's been a while since I uploaded those 2D demo videos and you commented on them. They say being able to understand it and being able to explain it to others are different thing and that was so true haha. It took longer than I had expected and I appreciate your patience. I hope you're enjoying this series!
If your thinking led to the same question as mine : "Wait a minute, we already tested the upPressed, downPressed etc. Why test it again just to update the sprite?"
You can also just update the spritecounter in the if slot of the update method, like so :
public void update(){
if(keyH.upPressed) {
direction = "up";
y -= speed;
spriteCounter++;}
I just think it looks cleaner as a whole. Now it accomplishes the same thing with less nesting, see which you like better.
I sincerely hope I'm not offending the author with my suggestions. Thank you for the instructive series!
I have the solution for those of you, who are struggling with the error pinned in the comments and using VS Code (but you can give it a try in your IDE). I put the pictures in a single folder called player and then I moved the folder in the src folder. And then wrote this: File f1 = new File("./src/player/ninja_up_1.png");
File f2 = new File("./src/player/ninja_up_2.png");
File f3 = new File("./src/player/ninja_down_1.png");
File f4 = new File("./src/player/ninja_down_2.png");
File f5 = new File("./src/player/ninja_left_1.png");
File f6 = new File("./src/player/ninja_left_2.png");
File f7 = new File("./src/player/ninja_right_1.png");
File f8 = new File("./src/player/ninja_right_2.png");
up1 = ImageIO.read(f1);
up2 = ImageIO.read(f2);
down1 = ImageIO.read(f3);
down2 = ImageIO.read(f4);
left1 = ImageIO.read(f5);
left2 = ImageIO.read(f6);
right1 = ImageIO.read(f7);
right2 = ImageIO.read(f8);
I swear you are god in disguise. Thank you so much! I was going to give up since I didn’t know what to do.
Thank you so much! omg I literally spent HOURS looking for a solution the other way. LIFE SAVER!
it worked very well in intellij, thank you very much!
I use VSCode and this worked hella good. thank u very much
I've been trying to fix this error for like days. Thankkssss
Thank you RyiSnow!!
Amazing 👏🏻👏🏻👏🏻👏🏻👏🏻
bro's good at drawing, i cant
Hello from Russia!!! You deserve more viewers)
Awesome!!!
For any of those who is only getting one sprite character, make sure to add break at the end of each case in the switch statement
Thank youuu for the tutorial i really want to try making a game
subscribed immediately
Thanks!
I was trying to limit myself to one video a night, but I could not help it and decided to do another! :)
Wow, that's a really good and in depth tutorial, good job! I'm following the tutorial but im trying to do some things in "my way", for exemple, why dont you use entity as an abstract class?
Instead of the 4 if you used for sprite number, my spriteNum grows every 10 spriteCounter (like yours), but for select the image in the switch i use if(spriteNum%2==0) , i find it a bit more elegant.
Pls dont use keyHandler==true XD.
Good job again!
Incredible. What about storing the sprites inside an array?
And better, having one single sprite sheet file and changing the position? For performance/memory. I think I will add these if it's not done on the videos to my version on my repository.
Thanks a lot. Very fun tutorial.
Thank you Ryi
Thank you for your support!!! I hope you'll enjoy the series :)
I’ve been following your tutorials to the t so far, but when after shifting the key input stuff to the player class and after clicking run, the square doesn’t move at all, do you have any clue what the problem could be? no errors are popping up, it’s just not getting my key inputs for some reason
edit - never mind, I forgot to put the player update inside the game panel update
For anyone wondering how to resolve the error in VS code. Just right click on the res folder and select "add folder to java source path." this worked for me.
Dear Ryisnow, thank you for the immense work you are doing. I have recently started to follow your tutorials step by step. I’m having a great time and you’re very clear in your explanation.
I have a problem I can’t solve, can you help me?
When I press start, the character moves in the direction I have indicated. At some point, however, it freezes and does not move anymore despite me pressing the command on the keyboard. Shortly after it starts moving again and so on it stops again.
The FPS are fixed at 60, it seems to me that everything I marked on the KeyHandler is correct... what can it be? Thank you very much for your availability!
you can also use arrays to storage the images and then iterate through the values c:
How????? I am confused becasue we store BufferedImage objects, so we can create one 1 arrayList called images, that has all of the, but are we still creating up1, up2, down1, down2? or dont and just do image.add(ImageIO.read(getClass....etc ? But how do you get the string to change for "/player/boy_left1... or /player/boy_right2"????????
Can you show what you did?
@@Team6OWG @REDLIK share dude!! ((:
thanks
Hello, in class Player when you import Gamepanel and Keyhandler you get option to do main.Gamepanl etc i do not get these options when i type it in myself I get an error saying the import main cannot be resolved. any solutions, Thanks.
Hey I love your videos. But i got a question about the animation. The update method is based on the number of FPS. Which means that with the system you made, a person with 30 fps on the game will have 2x slower animation and a person with 120 fps 2x faster. Is there a way to have the same animation speed regardless of fps?
Yes, I think you can set the speed based on fps.
Example:
int speed = 240/FPS;
This returns 4 if fps is 60 and returns 8 if fps is 30 so the player speed stays the same.
That said if you set fps 241 or more, the speed becomes 0 (since int doesn't accept decimal) so player won't move at all in that case. So probably you'll need to change it to double and arrange the code a little bit. Like counting decimal behind the scene and when it hits 1, apply the movement or something.
@@RyiSnow Great idea! Thank you I will try it
Hi, I just realized that you were asking about the animation, not the player's movement speed. Maybe you've already figured it out but you can also set the sprite counter based on fps so the interval between sprite 1 and 2 stays the same.
hey ryi, not sure if you still check these comments but do you by any chance know how to register a source folder in bluej? i love these tutorials but this is really getting me stuck
is there a way to make another image animation (I want to add an idle animation when not pressing any keys)?
youre the best :))))))))))))))))))))))))))))))))))))))
my image 2 on the player is not equal in time to my image 1, so it looks like a glitchy image 1 bc it updates to image 2 and then immediately goes back. Any help is appreciated
I get to the 7:10 test and the rectangle no longer moves :( I left the old if loop location updater in the GamePanel class and that box still moves. But the new box will not budge. Advice? I've got the new loop in the Player class, as well as updated all the x's and y's.
What I recommend is what I did for idle animation which is a default on the switch case with a front facing sprite
is this code performed with the delta accumulator method? cuz it's showing too many errors using the sleep method!
note: I'm using IntelliJ
how can you add another source folder? There's no option for it on my Netbeans and it only adds another folder or package inside the "source package" folder.
Hey man! I'm trying to master java right now and I got a question. Were you just like messing around or is creating games your passion? Are you a game developer?
i dont know what is happening my player sprite is not showing its showing the white rectangle only even though i have cut out the code for it. please help.
this might be a little late but if i switch to bufferedimage, not even drawing the images, just assigning the pngs, my key binding seems to break, whenever i stop calling the method that assigns the pngs it goes back to normal, if i add any other functions with the images on they work just fine, but the key binding breaks, i'm not sure how keybinding focus works but it still seems quite awful
nevermind i'm leaving this comment here for people with the same problem, key binding's default focus is just as crappy as keylistener's, put JComponent.WHEN_IN_FOCUSED_WINDOW inside the getInputMap()'s parameter to fix this
I am having trouble with the movement(I have followed all the directions properly but I think that the movement logic is wrong in the tutorial)
-When I press right then while right is still pressed, I press up or down, the sprite will move up or down and when I let go of up or down (remember right is still pressed), the sprite will continue to go right.
- The problem is that this does not work for when I am going up and then I want to go left or right.
- There is something wrong with the if statements, we check for up before down,left and right so anything below in the if statement is overruled by everything above.
Is is there any way I can fix this bug?
I was listening while coding and didn't realize that when you said "player *dot* boy_up_1.png" you meant "player/boy_up_1.png"... I was so confused when nothing worked in eclipse, even changing the folder multiple times, I had to rewatch a third time to realize it!
Ah, so I see you are using 8 different images for the player sprite. Would you ever optimize the animation system to support reflections, such that you only use 4 unique sprites? Like "Boy_down_2" is just "Boy_down_1" but flipped on the y-axis, and left_1 and left_2 are just right_1 and right_2, but reflected over y, and so on.
That sounds like an interesting idea (never thought about it) but probably won't fit this game because not every character is symmetrical. For example, if a character is holding a sword on their right hand, flipping the sprite will produce a strange result (the character will be holding the sword with his left hand). So I think I will stick to the current system for the time being. Thank you for the suggestion though :)
@@RyiSnow Understandable. In that sword senario, that definitely wouldn't work, but I just figured that if you're going for a retro style graphics, that working within some artistical limitations like a limited color palette (or in this case a limited number of keyframes) might spark some creativity or just be a fun extra challenge. Ofcourse though it is your project, and I'll watch the series regardless!
crazy to think that Minecraft was made like this, wow
What do you mean that MC was made like that? Minecraft was made with LWJGL to be able to draw using OpenGL, this being a hardware representation. This tutorial uses Swing, and Swing uses software rendering. The difference between the two is that hardware rendering has countless benefits. But I'm not saying that learning Swing to make video games is bad, don't get me wrong. RyiSnow teaches us the basics of 2D game development, which is essential if you want to get into something deeper like OpenGL.
bro u mean the og legend of zelda bro.... dont get ur games mixed up.
I accidentally made my character sprites 32x32 pixels and its smaller when I draw it. Shouldnt it be bigger since it has more pixels? Also I have tried changing the "oiriginalTileSize" variable from 16 to 32 but it doesnt work very good.. I think i'll just start over and make a 16x16 character
Your character was rendered as 16x16 because we used the tileSize as their width and height when we draw images.
(this line)
g2.drawImage(image, x, y, gp.tileSize, gp.tileSize, null);
If you change the width and the height, the sprites will be rendered with the specified size.
I love these tutorials/walkthroughs so much! I just have one question though when using Netbeans I can't get the walking sprites to load and I am not getting any errors in my code. The normal standing in place sprites show but when I do the same code as shown in the video only the eight sprite will load in and everything else is a blank and it isn't even "walking"? I have no clue how to fix this issue. Any other Netbean users running into the same thing? Thank you!
solution: delete netbeans 👍😁 (like i did) cuz theres no source folder in it and switched to eclipse
I cannot use tileSize in the player class by just adding a public modifier in the GamePanel class. Why can you do it? I'm confused
Hi there, wouldn't it be better to make the Entity class an abstract class/ interface?
Can you please help me..
I got my character show up and move, but while moving, the character position got shifted to the left after an amount of time. It just keep shifting like that over and over while moving which is kinda frustrating me so much. One more thing that is I used 9 images for my character animation. I modified the code to adapt my character. There is just that one problem. I hope you understand my problem. :(
For some reason the character is leaving a trail of artifacts when being moved. Any help?
Hello, I have an error at 2:23 when you type -Player player = new Player(this.KeyH){}, here Player is at the beginning and Player after new I have an error and it says like this - Player cannot be resolved to a type , help me how can I fix it?
you have nice tutorial, but i need help.
for the character i have 3 pictures for up and down, and have 4 pictures for right and left. iam in 20:52 of the video and my character when he is gos de up and down show a moment when he dessapear because i have 4 spriteNumber and just 3 pictures for down and up. when hes go to the left or right hes looks normal but the problem is when hes go to up and down, hes disappear for a one frame!
How would I make it so that my character can walk diagonally like if I press W and D at the same time?
i have question
do you recomend some kind of books?
hello! is there any way to make a different sprite for "standing still"? like if you stop moving the sprite changes to a standing still figure? thank u for the tutorial!
I've answered that in the "Answering requests" video so please check it!
@@RyiSnow oh okay thanks!
I'm stuck in running with new images @sts (spring tool suite application), it's getting me null when read image or maybe my folder res structure.
Thank you and I'm sorry..
I have a question. Can I just make the player picture in a GIF format?
I change language because English is more comfortable for me.
Day1: I got to this part of the video today and the truth is it took me a bit... At least I'm understanding it.
*my sprites are not drawing to the screen, i used the same sprites from video description everything loads in without any error but the sprites won't load to screen please help*
Did you add the getPlayerImage(); method to the player constructor in the Player class? I had the same problem and this was my solution
i have a problem, the class KeyHander no works for some reason.. And I did it the same of the video... Any sugestions?
when you created the player, you passed this, here you don't accept it at all, it keeps asking for cast. I do it to later give an error of creating local variable.
Hey, the character only appearing when going D key, WAS keys won't show character? can you help me with that?
In case you haven't figured it out yet, you are probably missing some breaks in switch statement. It's such a stupid mistake but it slipped by me and hopefully its the same solution for you.
it doesnt give me the option to create a source folder.
Im on idea community edition, anyone knows what could be the problem?