How to Shoot Bullets in JavaScript - Game Dev
Вставка
- Опубліковано 12 вер 2024
- In this exciting video we are going to learn how to shoot bullets in a 2D game using JavaScript and a HTML canvas. We will code everything from scratch starting with a blank canvas. The bullet engine that we are going to build will be highly configurable. That means you can change the speed, damage amount and even limit the number of bullets that are fired at a time.
If you enjoy this tutorial please subscribe , like and share.
Github LInk:
github.com/Cod...
Try it here:
codingwith-ada...
this is why I subscribed and liked. Simple and concise. Thank you so much for the tutorial.
Thank you for the subscribe and like 😀
I’m very happy that you enjoyed the tutorial you’re welcome!
Great videos gonna try and binge watch them all!
Thank you! I really appreciate the great feedback.
This is a great tutorial but I have a question. Why is the ctx passed into draw(ctx) instead of the constructor when the entity is created?
Thank you! Both approaches would be considered valid. If you think the canvas could change then passing into the draw method would be a good idea. Otherwise passing the ctx into the constructor could imply a stronger coupling between the entity and the ctx. At the end of the day I advise which ever you choose to lean towards creating a consistent architecture. It’s a very opinionated topic here is a posting on stack that expresses several different view points stackoverflow.com/questions/4367347/constructor-parameters-vs-method-parameters
Hey man, great video! Can you tell me why I have to use arrow functions in Player class -> "keydown = (e) => { ... }" instead of normal functions like keydown(e) { ... }? Cause when I use the normal ones, I can't move the player with the keyboard.
Thank you! That’s a great question. The reason we use an arrow function is that this will stay binded to the player class and we can access the properties of player using this.x etc. when you use a regular function javascript will bind this to who ever made the call for a keyboard event this might represent the window or document. I would have to check to make sure. To make a regular function work you have to call a special method to rebind the function to the player it’s much easier to use an arrow function. The this keyword can be complicated in JavaScript compared to other programming languages like Java or C#. I hope this helps. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Hi Adam, is there a way I can use a mouse event to aim the bullets with the cursor?
That’s a really fun idea. It’s possible but I have not tried it yet. Perhaps in a future video. Thanks for the suggestion.
отличный гайд
You’re welcome!
Very nice thanks so much bro👍❤️❤️❤️❤️
You’re welcome! Glad you enjoyed the video 😀
How do make sure that the player doesn't go out of the playarea?
You can check the boundary of the canvas. For an example checkout my intro to JavaScript game dev you can jump to the GitHub link the description. ua-cam.com/video/UUFPEgRKwf4/v-deo.html
please giev me the link of this websight or aapp
in whichyou script thsi jave code
I use vscode to code the app. For the project code you can find that in the description
Thanks for the videos. The characters are a little tiny (on smartphones), although readable. Maybe with space optimization you can find how to increase font size
You’re welcome! Thanks for the suggestion. I’ll look into that in the future.
Amazing tuto, well explained , clear instructions ! you're a cheefff
Please more videos
thank you sooooo much
love and support
Thank you! I really appreciate the feedback!Glad you enjoyed the tutorial 😁
@@CodingWithAdam
I have a question. How can you change the orientation of the bullets? I'm having trouble with it. The tutorial was straight forward by the way. Thanks!
You’re welcome. That would involve changing the velocity direction. Also the starting position of the bullet based on the sprite. In the space Invaders tutorial I created, the enemies shoot down and player shoots up. They both use the same bullet controller but provide different velocity direction. The code uses a modified version the bullet controller . I hope that helps. Glad you enjoyed the tutorial.
@@CodingWithAdam thanks
Hey man i love this tutorial so much, it helps me a lot with my project of remaking a captain claw copy cat, but now i need a new tutorial about making an inventory system that can pick and drop items like life potions for later.... please... please have mercy upon me , i will never forget your name !!!!
You’re welcome! Thank you for the suggestion! I’ve never played captain claw and will check that out. Excited to hear how your project comes along.
@@CodingWithAdam there is only one turotial for javascript inventory on yt from pothonprogramming, but it.s rushed to the end more of a walkthrough but not on the full code, he shared the github with the community but not building the project brick by brick makes this impossible for someone to replicate for one self needs, because understanding small concepts is the base, and pothon programming made a tutorial that has nice results, it picks and drops items, but it's useless to me, I already now that you will make a better job ! I thank you once again for your work and i m more happy today than yesterday because i know an inventory tutorial from you is on the way ! Greeting from Eastern Europe !
Great tutorial!! THX!!
Thank you! You’re welcome!
Amazing!
Thank you! 😁
Hey Adam, is there a way that I could generate an enemy after x seconds instead of manually putting enemies into the const enemies array? I would probably have to use setInterval right?
That’s an awesome idea. For sure you could spawn enemies based on a set interval or a timer variable that you count down from then at zero spawn an enemy on the screen. Stay tuned as next I hope to release a space invader tutorial that will have the bullet logic we learn in this game. Staring with set interval is a a great idea. If you use settimeout you could set a different random time every time you call settimeout to make the enemies appear at different times. However start with the easiest solution and then move to a more difficult one if needed. Let me know how it goes. You can also copy the enemies from the complete game on GitHub link in the description. 😀
It's a nice game, but it can be developed more, for example, the blocks may go down as time goes on, or there may be a level system, there may be more and different blocks or our character's life in each level.
Thanks! That’s right the game can be expanded to do more. In my latest video we expand on the bullet controller and use it to make space invaders! Make sure to check it out! 😀
Hi Adam! Do you think you could make a full detailed tutorial of how to open the white screen on the right in visual studio?
Hi Deke91, the white screen on the side is chrome. I used Macs split screen feature to put them side by side well I code. I might do a video on that thanks
@@CodingWithAdam I see, A video tutorial would be great if u find the time 👍
Instead of live server, as Adam explained on the vid, you can use another extension VScode Preview Server. It will give you two option:
- Launch on Browser which is open up in your default browser, or
- Preview on Side Panel, it will give you new screen on the right side of VScode, just like in Adam's Video.
That’s really cool Elisabeth!
I got stuck at around 7:30, the console says that i cant use the import statement outside a module, and the player wont load. Ö
Sounds like the script tag in index.html is missing type=“module”
@@CodingWithAdam thanks for answering, but now it shows two errors, first one: "Access to script at '(file location)' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https." and second one says that something failed to load.
Can you make tutorial about shooting bullets in selected direction?
Hi PatMin23, thanks for the suggestion. Do you mean shooting in the direction you are moving for example moving right shoot right moving down shoot down?
@@CodingWithAdam yes, something like that.
Thanks for the suggestion I might make a part 2!
Hey Adam I really like your Tutorial but how can I make this for mobiles I mean this will only work in laptop or PC please help
Glad you like the tutorials. For mobile you would need touch controls. I have not tried this yet but hopefully will in a future video. Thank you for the suggestion.
I have a tough one for you. I have two points with a left and top px position. How do I use those to determine how far the bullet travels horizontally and vertically per frame?
Hi Daniel. I’m not sure If I understand the question. The length of time between frames can change. You have to record the position in frame 1 and then the position in frame 2. From there you can determine the vertical and horizontal distance travelled. This can be different depending on if the game is 30fps or 60fps. I hope some of that helps
@@CodingWithAdam Thanks. I mean making it travel beyond the destination point. The answer seems to be Bresenham's line algorithm but I’m having trouble implementing it. Thanks for the response!
Very cool! I have never used that!
for some reason I'm getting an import error, in the console I'm getting the error
"Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)"
I've tried different import methods but nothing seems to be happening or changing :/
I linked the Player.js to the HTML file and removed the import statement in the index.js file and then it began working >:?
that only worked initially. now it still is not working
Sounds like you are missing the attribute on the script tag type=“module”
@@CodingWithAdam oh, which document does that go into? (and thanks for the swift reply)
Index.html on the script tag for index.js
3:18 why did he use the setInterval function with 1000/60 to call the gameLoop function
The set interval function will call the game loop 60 times every second which will update the screen. This was a choice to match most monitors refresh rate. There are other ways to do this as well such as requestAnimationFrane. Hope this helps
I couldn't move box upward my up key is not working when if i press
Could you help me??
I would suggest looking at the chrome dev tools to see if there is an error. If there is not one take a look at the code on GitHub there is a link in the description.
Hey sir, how can i shoot bullet from
Center to the top left or right corner ?? Please help
All you need to do is add a xVelocity for the bullet and it will shoot diagonally. The combo of X and Y velocity will move sprites diagonally.
@@CodingWithAdam thankyou ❤
hellooo! not sure if you're still answering.. but i was curious, console says this.x-=this.speed is NaN :( And mine does not work with that code! no idea to fix this....
Nan is short for not a number. Sounds like one of the values might not be initialized. The speed value might be null. Please check your code against the solution on GitHub. Also add a few console logs to check the value. I hope that helps.
When I imported my Bullet Controller everything went away except for my background and the header…
I would take a look at the developer console and see if there are any errors. Make sure the import has the js at the end as well
import BulletController from "./BulletController.js";
make sure the file name is he same as the text after form including the casing
I hope that helps
@@CodingWithAdam got it to work! Thanks.
Awesome!!!
Anybody is here can help me? How can I set arrow keys set on this game? What is methods?
how to run game?
Hello
Thank you always for the coding class.
I just started coding.
I'm working on a simple project..
I really need your help...😭
Can I ask you a question through email?
Sorry, I currently only answer questions on UA-cam