I am trying to make an html canvas game.I currently have a blue player in the middle of the screen that shoots projectiles. when i have two projectiles shot at once, a polygon is drawn between them. this confuses me, I AM using context.clearRect. I have tried using context.clearRect twice and i have also tried using bullets.splice to take the bullet out of the array when it is off the screen. how do i fix this? my code:
html:
JavaScript
x
13
13
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<link rel='stylesheet' type='text/css' href='style.css'>
5
<title>Canvas Shooter Game!</title>
6
</head>
7
<body>
8
<canvas id='canvas'></canvas>
9
<script src='script.js'></script>
10
</body>
11
</html>
12
13
js:
JavaScript
1
65
65
1
const context = canvas.getContext('2d');
2
var timer = setInterval(update,5);
3
var height = window.innerHeight;
4
var width = window.innerWidth;
5
canvas.height = height;
6
canvas.width = width;
7
var bullets = [];
8
var player = new circle(width/2,height/2,80,'#1B03A3');
9
document.addEventListener('click', function(event){
10
var vs = calculate(event.clientX,event.clientY);
11
new bullet(width/2,height/2,10,'red',vs);
12
});
13
function bullet(x,y,r,color,velocity){
14
this.x = x;
15
this.y = y;
16
this.r = r;
17
this.color = color;
18
this.vx = velocity.x;
19
this.vy = velocity.y;
20
bullets.push({
21
x: this.x,
22
y: this.y,
23
r: this.r,
24
vx: this.vx,
25
vy: this.vy,
26
color: this.color
27
});
28
}
29
function circle(x,y,r,color){
30
this.x = x;
31
this.y = y;
32
this.r = r;
33
this.color = color;
34
this.update = function(){
35
context.beginPath();
36
context.fillStyle = this.color;
37
context.arc(this.x,this.y,this.r,0,Math.PI * 2, false);
38
context.fill();
39
}
40
}
41
function calculate(x,y){
42
var angle = Math.atan2(y - height / 2, x - width / 2);
43
vx = Math.cos(angle);
44
vy = Math.sin(angle);
45
var velocity = {
46
x:vx,
47
y:vy
48
}
49
return velocity;
50
}
51
function update(){
52
context.clearRect(0,0,width,height);
53
bullets.forEach(function(bullet){
54
bullet.x += bullet.vx * 3;
55
bullet.y += bullet.vy * 3;
56
context.fillStyle = bullet.color;
57
context.arc(bullet.x,bullet.y,bullet.r,0,Math.PI * 2, false);
58
context.fill();
59
if(bullet.x > width||bullet.x < 0||bullet.y > height||bullet.y < 0){
60
bullets.splice(bullet);
61
}
62
});
63
player.update();
64
}
65
css:
JavaScript
1
10
10
1
*{
2
margin:0;
3
padding:0;
4
}
5
#canvas{
6
background-color:black;
7
}
8
9
10
EDIT: video of what happens
Advertisement
Answer
In the update() function add
JavaScript
1
2
1
context.beginPath();
2
After this line
JavaScript
1
2
1
bullets.forEach(function(bullet){
2