# 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

window.onload = function()
{
animate();
}

function spawnRandomObject() {

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

// About Math.random()
// 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
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
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
How about... (in player script)

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))))
alert('hit');
}

// 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
How about... (in player script)

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))))
alert('hit');
}

// 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!

#### Thread Information

##### Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

"

"

## X vBulletin 4.2.2 Debug Information

• Page Generation 0.12432 seconds
• Memory Usage 2,880KB
• Queries Executed 15 (?)
More Information
Template Usage (34):
• (1)SHOWTHREAD
• (1)ad_footer_end
• (1)ad_footer_start
• (1)ad_global_above_footer
• (1)ad_global_below_navbar
• (1)ad_global_header1
• (1)ad_global_header2
• (1)ad_navbar_below
• (1)ad_showthread_firstpost_sig
• (1)ad_showthread_firstpost_start
• (1)ad_thread_first_post_content
• (1)ad_thread_last_post_content
• (4)bbcode_code
• (1)bbcode_quote
• (1)footer
• (1)forumjump
• (1)forumrules
• (1)gobutton
• (1)header
• (1)headinclude
• (1)headinclude_bottom
• (4)memberaction_dropdown
• (1)navbar
• (4)navbar_link
• (1)navbar_moderation
• (1)navbar_noticebit
• (1)navbar_tabs
• (2)option
• (4)postbit
• (4)postbit_onlinestatus
• (4)postbit_wrapper
• (1)spacer_close
• (1)spacer_open
• (1)tagbit_wrapper

Phrase Groups Available (6):
• global
• inlinemod
• postbit
• posting
• reputationlevel
• showthread
Included Files (26):
• ./showthread.php
• ./global.php
• ./includes/class_bootstrap.php
• ./includes/init.php
• ./includes/class_core.php
• ./includes/config.php
• ./includes/functions.php
• ./includes/functions_navigation.php
• ./includes/class_friendly_url.php
• ./includes/class_hook.php
• ./includes/class_bootstrap_framework.php
• ./vb/vb.php
• ./vb/phrase.php
• ./includes/functions_facebook.php
• ./includes/functions_calendar.php
• ./includes/functions_bigthree.php
• ./includes/class_postbit.php
• ./includes/class_bbcode.php
• ./includes/functions_reputation.php
• ./includes/functions_notice.php
• ./packages/vbattach/attach.php
• ./vb/types.php
• ./vb/cache.php
• ./vb/cache/db.php
• ./vb/cache/observer/db.php
• ./vb/cache/observer.php

Hooks Called (70):
• init_startup
• friendlyurl_resolve_class
• init_startup_session_setup_start
• database_pre_fetch_array
• database_post_fetch_array
• init_startup_session_setup_complete
• global_bootstrap_init_start
• global_bootstrap_init_complete
• cache_permissions
• fetch_threadinfo_query
• fetch_threadinfo
• fetch_foruminfo
• load_show_variables
• load_forum_show_variables
• global_state_check
• global_bootstrap_complete
• global_start
• style_fetch
• global_setup_complete
• showthread_start
• showthread_getinfo
• strip_bbcode
• friendlyurl_clean_fragment
• friendlyurl_geturl
• forumjump
• cache_templates
• cache_templates_process
• template_register_var
• template_render_output
• fetch_template_start
• fetch_template_complete
• parse_templates
• fetch_musername
• notices_check_start
• notices_noticebit
• process_templates_complete
• friendlyurl_redirect_canonical
• showthread_post_start
• showthread_query_postids
• showthread_query
• bbcode_fetch_tags
• bbcode_create
• showthread_postbit_create
• postbit_factory
• postbit_display_start
• postbit_imicons
• bbcode_parse_start
• bbcode_parse_complete_precache
• bbcode_parse_complete
• postbit_display_complete
• memberaction_dropdown
• tag_fetchbit_complete
• forumrules
• navbits
• navbits_complete
• build_navigation_data
• build_navigation_array
• check_navigation_permission
• process_navigation_links_start
• process_navigation_links_complete
• set_navigation_menu_element
• build_navigation_menudata
• build_navigation_listdata
• build_navigation_list
• set_navigation_tab_main
• set_navigation_tab_fallback
• navigation_tab_complete
• fb_like_button
• showthread_complete
• page_templates