JavaScript Collision Function Help

Hello everyone, I am new to coding and this is my first semester in college for computer science.
My final project requires me to make a game with javascript and I am having trouble with a collision
function for my game. The game has objects dropping from the top of the canvas down to a player controlled rectangle. It should disappear one it makes contact with the top of the player. But right not the objects instantly appear at the bottom. Help ! ! 1

The below is my current code.

var speed = 400;
var bombing = [];
var x = 370;
var y = 720;

window.onload = function(){
	c = document.getElementById("battlefield");
	ctx = c.getContext("2d");
	addEventListener("keydown", move);
	setInterval(create,1000/0.5);
	gMan();
	update();
}

function update(){
	setInterval(function(){
		ctx.clearRect(0, 0, 800, 800);
		for(let i = 0; i < bombing.length; i++){
			bombing[i].drop += 0.8;
			bombing[i].make();
			defuse();
		}		
		gMan();
	}, 1000/speed);

}

function gMan(){
	ctx.fillRect(x, y, 60, 60);
	
}

function move(){
	if(event.keyCode == 37){//left
		ctx.clearRect(0, 0, 800, 800);
		if(x > 10){
			x -= 20;
		}
	}
	if(event.keyCode == 39){ //right
		ctx.clearRect(0, 0, 800, 800);
		if(x < 730){
			x += 20;
		}
	}
}

function grenade(){	
	this.drop = 0;
	this.placement = Math.floor(Math.random() * 770);
	
	this.make = function(){
		ctx.fillRect(this.placement, this.drop, 60, 60);
	}
}

function create(){
	var explosive = new grenade();
	explosive.make();
	bombing.push(explosive);
}

function defuse(){
	if(bombing[i].drop = y){
		bombing[i].splice;
	}
}

I can’t test this so hopefully others can help. but i do see a potential typo; if(bombing[i].drop = y) should be === ?

1 Like

I tried the code in test window and what I got were ‘bombs’ falling. I played with your last function and saw a few things:

  1. = thing noted from previous post
  2. console.log of bombing[0].drop … it’s not an integer (needs a floor or round)
  3. y-60 to make it ‘explode’ before it hits the ground. offset for box height (gMan also needs an offset :wink: )
  4. .splice method needs arguments. where to start and how many.

1 Like