Hey koobcoding, thanks for posting!
Check out the following CodePen I made a while back, it gives a good example of how a cannon is coded to shoot projectiles out of the end of it: https://codepen.io/chriscourses/pen/PzRABR
Basically, you're going to want to focus on the atan2
function, it determines the angle the cannon should be turned, and the angle the ball should be shot from so you always get the effect of a cannonball coming out of the cannon's barrel.
I believe I cover the function a bit in the beginner game course here: https://chriscourses.com/courses/javascript-games/videos/javascript-games-for-beginners
For loading images, you'll want to use the canvas' drawImage
function:
c.drawImage(image, x, y);
image
here is the URL to your image while x
and y
are your image's position. You'll need to load an image into JavaScript manually first for this to work:
const img = new Image()
img.src = './yourPath.png'
c.drawImage(img, 100, 100);
Hope that helps clear up at least a little bit, will have a course on loading images when the sidescroller game release comes out.
Thank you for the help Chris,
I'm still stuck on where to put those codes exactly, do they all go in js, or do I have to add a new line of code in Html?
and what codes should I replace them with? I did upload an image into my folder with the HTML and js?
Here is the code I try to put in, but it did not work by not letting me start the game.
class Player {
constructor(x, y, radius, color) {
this.x = x
this.y = y
this.radius = radius
this.color = color
}
draw(){
c.beginPath()
const img = new Image(cannon.PNG)
c.drawImage(image, x, y);
img.src ='./cannon.PNG'
}
}
old way when it worked, I'm not sure where to place the code to make the image appear as the white circle ball. Thanks again
class Player {
constructor(x, y, radius, color) {
this.x = x
this.y = y
this.radius = radius
this.color = color
}
draw(){
c.beginPath()
c.arc(this.x, this.y, this. radius, 0, Math.PI * 2, false)
c.fillStyle = this.color
c.fill()
}
}
Nevermind mind I was able to figure it out!
Thanks again Chris, GREAT Tutorial!
const canvas = document.querySelector('canvas');
const c = canvas.getContext ('2d')
const image = new Image() // new code, line 4
image.src = 'cannon.PNG'; // new code, line 5
draw(){
c.drawImage(image,
canvas.width / 2.03 - image.width / 2, // new code, line 25
canvas.height / 2 - image.height / 2.1 ); // new code, line 26
}
function drawImage () {
c.drawImage(image, x, y); // new function, line 109
}
No problem! Glad you were able to get it going, sticking with it and working it out is a surefire way to get those concepts engrained in deep memory.
Just let me know if you ever have any more questions on the forum, can't guarantee I'll get to them right away, but def will eventually.
Want to participate?
Create a free Chris Courses account to begin