# Thread: Collision detection with enemy

1. Registered User
Join Date
Mar 2015
Posts
3

## Collision detection with enemy

Hello,

I'm making a game but cannot figure out the collision. I have two scripts, a enemy script and a player script.

Code:
```// get a refrence to the canvas and its context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// newly spawned objects start at Y=25
var spawnLineY = 25;

// spawn a new object every 1500ms
var spawnRate = 2000;

// when was the last object spawned
var lastSpawn = -1;

// this array holds all spawned object
var objects = [];

// save the starting time (used to calc elapsed time)
var startTime = Date.now();

//enemy image
var images = [];
for (var i = 0; i < 5; i++)
{
images.push(new Image());
images[i].src = "enemy" + i + ".png";
}

var enemyStats = [
new Enemy(2),
new Enemy(4),
new Enemy(6),
new Enemy(8),
new Enemy(10),
];

function Enemy(speed)
{
this.speed = speed;
}

//valsnelheid
var spawnRateOfDescent = 0.50;

// start animating

{
animate();
}

function spawnRandomObject() {

// select a random type for this new object
var t;

// Math.random() generates a semi-random number
// between 0-1. So to randomly decide if the next object
// will be A or B, we say if the random# is 0-.49 we
// create A and if the random# is .50-1.00 we create B

// create the new object
function Entity()
{
// set this objects type
//type = t,
// set x randomly but at least 15px off the canvas edges
this.x = Math.random() * (canvas.width - 30) + 15;
// set y to start on the line where objects are spawned
this.y = spawnLineY;

// give random image
this.randomValue = Math.floor(Math.random()*images.length);
this.image = images[this.randomValue];
this.enemy = enemyStats[this.randomValue];
}

// add the new object to the objects[] array
objects.push(new Entity());
}

function animate() {

// get the elapsed time
var time = Date.now();

// see if its time to spawn a new object
if (time > (lastSpawn + spawnRate)) {
lastSpawn = time;
spawnRandomObject();
}

// request another animation frame
requestAnimationFrame(animate);

// clear the canvas so all objects can be
// redrawn in new positions

// draw the line where new objects are spawned
ctx.beginPath();
ctx.moveTo(0, spawnLineY);
ctx.lineTo(canvas.width, spawnLineY);
ctx.stroke();

// move each object down the canvas
for (var i = 0; i < objects.length; i++)
{
var object = objects[i];
object.y += object.enemy.speed;
ctx.drawImage(object.image, object.x, object.y, 30, 30);
}
}```
Code:
```var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var playerX = 0,  //initial x
playerY = 50,  // initial y
velY = 0,
velX = 0,
playerSpeed = 2, // max speed
friction = 0.98, // friction
keys = [];

var img = new Image();
img.src = "Player0.png";

function update() {

// check the keys and do the movement.
if (keys[38]) {
if (velY > -playerSpeed) {
velY--;
}
}

if (keys[40]) {
if (velY < playerSpeed) {
velY++;
}
}
if (keys[39]) {
if (velX < playerSpeed) {
velX++;
}
}
if (keys[37]) {
if (velX > -playerSpeed) {
velX--;
}
}

// apply some friction to y velocity.
velY *= friction;
playerY += velY;

// apply some friction to x velocity.
velX *= friction;
playerX += velX;

// bounds checking
if (playerX >= 200) {
playerX = 200;
} else if (playerX <= -200) {
playerX = -200;
}

if (playerY > 70) {
playerY = 70;
} else if (playerY <= -200) {
playerY = -200;
}
//console.log(playerY);

// do the drawing
ctx.clearRect(0, 0, 1000, 1000);
ctx.beginPath();
ctx.drawImage(img, playerX + 250, playerY + 500)

setTimeout(update, 10);
}

update();

// key events
keys[e.keyCode] = true;
});
keys[e.keyCode] = false;
});```
i'm kind of stuck how to do the collision, i hope someone can help me with this? I'm very new to javascript

2. Registered User
Join Date
Mar 2015
Posts
14

Code:
```    //console.log(playerY);

var playerOffsetX = 250;
var playerOffsetY = 500;

// loop objects to detect collision with player
for (var i in objects) {
var o = objects[i];

var cx = img.width / 2;
var cy = img.height / 2;

var pcx = (playerX + playerOffsetX) + (cx);
var pcy = (playerY + playerOffsetY) + (cy);

if ((pcx > (o.x - cx) && (pcx) < (o.x + cx)) &&
((pcy > (o.y - cy) && (pcy) < (o.y + cy))))
}

// do the drawing
ctx.clearRect(0, 0, 1000, 1000);
ctx.beginPath();
ctx.drawImage(img, playerX + playerOffsetX , playerY + playerOffsetY )```

3. Registered User
Join Date
Mar 2015
Posts
3
Originally Posted by nplus

Code:
```    //console.log(playerY);

var playerOffsetX = 250;
var playerOffsetY = 500;

// loop objects to detect collision with player
for (var i in objects) {
var o = objects[i];

var cx = img.width / 2;
var cy = img.height / 2;

var pcx = (playerX + playerOffsetX) + (cx);
var pcy = (playerY + playerOffsetY) + (cy);

if ((pcx > (o.x - cx) && (pcx) < (o.x + cx)) &&
((pcy > (o.y - cy) && (pcy) < (o.y + cy))))
}

// do the drawing
ctx.clearRect(0, 0, 1000, 1000);
ctx.beginPath();
ctx.drawImage(img, playerX + playerOffsetX , playerY + playerOffsetY )```
Hi nplus, thank you for taking the time to help me! I have a problem if I put that code in the script, it gives a error Uncaught ReferenceError: objects is not defined. Which is correct I guess because objects is not a var in the Player script. But I can't really find how I get access to this var in the enemy.js file. I hope someone can help me with that?

4. Registered User
Join Date
Mar 2015
Posts
3
Ow, I can't edit the post anymore it seems, I figured it out, just needed to change var I in objects to:

var I in window.objects.

Thank you very much for the quick response!