Skip to content
Advertisement

how to stop polygons from drawing between two moving circles in javascript

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:

<!DOCTYPE html>
<html>
    <head>
        <link rel='stylesheet' type='text/css' href='style.css'>
        <title>Canvas Shooter Game!</title>
    </head>
    <body>
        <canvas id='canvas'></canvas>
        <script src='script.js'></script>
    </body>
</html> 

js:

const context = canvas.getContext('2d');
var timer = setInterval(update,5);
var height = window.innerHeight;
var width = window.innerWidth;
canvas.height = height;
canvas.width = width;
var bullets = [];
var player = new circle(width/2,height/2,80,'#1B03A3');
document.addEventListener('click', function(event){
    var vs = calculate(event.clientX,event.clientY);
    new bullet(width/2,height/2,10,'red',vs);
});
function bullet(x,y,r,color,velocity){
    this.x = x;
    this.y = y;
    this.r = r;
    this.color = color;
    this.vx = velocity.x;
    this.vy = velocity.y;
    bullets.push({
        x: this.x,
        y: this.y,
        r: this.r,
        vx: this.vx,
        vy: this.vy,
        color: this.color
    });
}
function circle(x,y,r,color){
    this.x = x;
    this.y = y;
    this.r = r;
    this.color = color;
    this.update = function(){
        context.beginPath();
        context.fillStyle = this.color;
        context.arc(this.x,this.y,this.r,0,Math.PI * 2, false);
        context.fill();
    }
}
function calculate(x,y){
    var angle = Math.atan2(y - height / 2, x - width / 2);
    vx = Math.cos(angle);
    vy = Math.sin(angle);
    var velocity = {
        x:vx,
        y:vy
    }
    return velocity;
}
function update(){
    context.clearRect(0,0,width,height);
    bullets.forEach(function(bullet){
        bullet.x += bullet.vx * 3;
        bullet.y += bullet.vy * 3;
        context.fillStyle = bullet.color;
        context.arc(bullet.x,bullet.y,bullet.r,0,Math.PI * 2, false);
        context.fill();
        if(bullet.x > width||bullet.x < 0||bullet.y > height||bullet.y < 0){
            bullets.splice(bullet);
        }
    });
    player.update();
} 

css:

*{
    margin:0;
    padding:0;
}
#canvas{
    background-color:black;
} 


EDIT: video of what happens

Advertisement

Answer

In the update() function add

context.beginPath();

After this line

bullets.forEach(function(bullet){
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement