Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-12-2012, 11:48 AM   PM User | #1
JacobP
New to the CF scene

 
Join Date: Dec 2012
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
JacobP is an unknown quantity at this point
Collision detection

Hello, I am new to this forum and Javascript in general.

Me and my group have a school project in which we have to make some collision detect. But we have no idea how to make this happen.

We borrowed most of the code from our teacher, and changed the design. But we want title2 and bamse to collide and make the box dissappear.

Code:
<!DOCTYPE HTML>
<html>
	<head>
		<title>Bamses Julerejse</title>
		<link rel="stylesheet" href="styles/screen.css" type="text/css" />
        <meta name="keywords" content="bamses julekalender, spil med bamse, julerejse med bamse, find 				        gaverne, bamse spil gratis" />
        <link href="images/bamse.ico" rel="icon" type="image/x-icon" />


	</head>
	<body onload="initiate()">
	  <section id="animation">
		<div id="background"></div>
		<div id="clouds2"></div>
		<div id="clouds1"></div>
		<div id="ground-level2"></div>
	  	<div id="title" data-x="300" data-speed="10" class="item"></div>
        <div id="title2" data-x="1000" data-speed="10" class="item"></div>
		<div id="bamse"></div>
		<div id="ground-level1"></div>
		<div id="ground-level3"></div>
		<div id="ground-level4"></div>
		
	  </section>
	<script src="js/animate.js"></script>
	</body>
</html>
Code:
body {
		background:	#000;
		background-image: url(../images/stressed_linen.png);
		background-repeat: repeat;	
	}
section#animation {
		display: block;
		width: 80%;
		height: 780px;
		position: relative;
		overflow: hidden;
		margin: 0 auto;
		box-shadow: 10px 10px 5px #111;
		-moz-box-shadow: 10px 10px 5px #111;
		-webkit-box-shadow: 10px 10px 5px #111;
		border: 4px solid #ccc;
		opacity: 0;
		-webkit-transition: opacity 3000ms ease-out;
		-moz-transition: opacity 3000ms ease-out;
		-ms-transition: opacity 3000ms ease-out;
		-o-transition: opacity 3000ms ease-out;
		transition: opacity 3000ms ease-out;
	}

	#background {
		width:		100%;
		height:		100%;
		position:	absolute;
		left:		0px;
		background-image:url(../images/background.png);
		background-position: 0px 600px;
		z-index: -3;
	} 

	#bamse {
		position:	absolute;
		top:		350px;
		left:		50%;
		margin-left: -100px;
		width:		200px;
		height:		300px;
		background-image:url(../images/bamse.png);
		background-position: 0px 0px;
	}
	
	ground-level1 {
		position:	absolute;
		top:		450px;
		left:		0px;
		width:		100%;
		height:		300px;
		margin-top:	30px;
		background-image: url(../images/ground-level1.png);
		background-position: 0px 0px;
	}
	
	#ground-level2 {
		position:	absolute;
		top:		100px;
		left:		0px;
		width:		100%;
		height:		800px;
		background-image: url(../images/snelandskab.png);
		background-position: 0px 0px;
	}
	
	#ground-level3 {
		position:	absolute;
		top:		300px;
		left:		0px;
		width:		100%;
		height:		600px;
		background-image: url(../images/Sneforlandskab.png);
		background-position: 0px 0px;
		
	}
	
	ground-level4 {
		position:	absolute;
		top:		650px;
		left:		0px;
		width:		100%;
		height:		135px;
		background-image: url(../images/ground-level4.png);
		background-position: 0px 0px;
		
	}
	
	#clouds2 {
		position:	absolute;
		top:		150px;
		left:		0px;
		width:		100%;
		height:		400px;
		border: 0px solid red;
		background-image: url(../images/skyer.png);
		background-position: 0px 0px;
		background-repeat:repeat-x;	}
	
	#clouds1 {
		position:	absolute;
		top:		-30px;
		left:		0px;
		width:		100%;
		height:		400px;
		background-image: url(../images/skyer2.png);
		background-position: 0px 0px;
		background-repeat: repeat-x;
	}
	#title {
	position:	absolute;
	top:		100px;
	left:		0px;
	width:		100%;
	height:		518px;
	background-image: url(../images/title.png);
	background-position: 0px 60%;
	background-repeat: no-repeat;
	}
	
	#title2 {
	position:	absolute;
	top:		500px;
	left:		0px;
	width:		100%;
	height:		518px;
	background-image: url(../images/gave.png);
	background-position: 0px 60%;
	background-repeat: no-repeat;
	}
Code:
 // Declare global variables
var frameWidth 		=	200, 		// width of frame in sprite sheet 
	frameHeight 	=	300, 		// height of frame in sprite sheet 
	frame 			=	0, 			// current frame (1 - maxFrames)
	maxFrames 		= 	6, 			// max number of frames
	character, 						// the container for the animation
	speed, 							// the number of pixels the character moves each frame
	counter			=	1,			// incrementor that keeps track of counting the frames
	direction		=	"right",	// the direction the animation should be facing 
	hide			=	false,		// whether the ninja is hiding 
	aniBamse		=	null,		// holds the ninja animation
	aniBackground	=	null,		// holds the background animation
	aniItems		=	null,		// holds the items animation
	itemsList,						// array for the items that appears in the animation
	aniInitiated	=	false,		// Whether the animation items have been initiated
	stageFrame		=	1,			// Counts the number of frames walked across the "stage"
	hide2           =   false;

function initiate(){
	character = document.getElementById("bamse"); // get the character
	// start animation
	document.addEventListener('keydown', startAnimation, false);
	document.addEventListener('keyup', stopAnimation, false);
	
	// Set the opacity of the #animation div so that it will fade in
	document.getElementById('animation').style.opacity = 1;
	// set the background position on all div elements so that they can be accessed through js later on
	var divs = document.getElementsByTagName('div');
	for(var i=0; i<divs.length; i++) {
		divs[i].style.backgroundPosition = '0px 0px';
	}
	/*
	console.groupCollapsed('Initiation');
		console.info('animation initiated');
		console.info('event listener for "keydown" added');
		console.info('event listener for "keyup" added');
		console.info('Divs array: ', divs);
	console.groupEnd();
	*/
	// Initiate items, so that they are placed according to their data-x html attributes before being animated
	itemsList = document.getElementsByClassName('item'); // Populate the array with html elements that have the class "item"
	if (aniInitiated == false) { // only do this if not initiated before
		for(var i=0; i<itemsList.length; i++) { // run through all the elements
			var animent = itemsList[i]; // get individual element out
			animent.style.backgroundPositionX = animent.getAttribute('data-x')+"px"; // Set the background position to the value in the data-x attribute
			console.log(animent.getAttribute('data-x')+"px");
		}
		aniInitiated = true; // set to true to prevent code from executing again
	}

}	

function startAnimation(e) {
 	var keyCode = e.keyCode;
	//console.log(keyCode);
	// Animate Right
	if (keyCode == 39 && aniBamse == null) {
		runAnimation();
		direction = "right";
		character.style.backgroundPositionY = "0px";
	}
	// Animate Left
	if (keyCode == 37 && aniBamse == null) {
		runAnimation();	
		direction = "left";
		character.style.backgroundPositionY = frameHeight+"px";
	}
	// Animate hide (use arrow up or down to toggle hide ninja
	if (keyCode == 38 || keyCode == 40 && aniBamse == null) {
		if (hide==false) {
			character.style.top = "400px"; // default + 100
			hide = true;
		} 
		else {
			character.style.top = "350px"; // default position as set in css
			hide = false;
		}
	}
}

function runAnimation() {
	aniBamse = setInterval(animateCharacter, 1000 / 10); // Animate the bamse
	aniBackground = setInterval(   // Animate the background
		function(){ // Anomynous function that performs the calls for animating the background
			animateBackground('clouds1',6); // Define which element to move and at which speed (pixels moved)
			animateBackground('clouds2',3);
			animateBackground('ground-level1',8);
			animateBackground('ground-level2',5);
			animateBackground('ground-level3',12);
			animateBackground('ground-level4',15);
		}, 1000 / 10);
		
	aniItems = setInterval(animateItems, 1000/10); // Animate the items that appear
}

function stopAnimation() {
	clearInterval(aniBamse);
	clearInterval(aniBackground);
	clearInterval(aniItems);
	aniBamse = null; // Set to null to signal that there is no longer an animation set for the ninja
}	

function animateCharacter() {
	character.style.backgroundPositionX = (frameWidth * frame)+"px"; // Change the background-position-x css property to animate the background
	frame += counter; // Keep track of which frame is displayed
	//console.log('Frame: '+ frame);
	if (frame == maxFrames) { // if at the last frame
		counter = -1;
	}
	if (frame == 1) { // if at the first frame
		counter = 1;
	}
	// Count the total of frames walked across the stage
	if (direction == "right") {
		stageFrame++;
	}
	else {
		stageFrame--;
	}
	console.log('StageFrame: '+stageFrame);
}

function animateBackground(element, speed) {
	//console.log('element: '+ element);
	var aniObject = document.getElementById(element); // Create a variable to hold the reference to the element
	//console.log('aniObject: '+ aniObject);
	var pos = aniObject.style.backgroundPositionX; // Assign the current position of the background x-value to pos
	//console.log('pos: '+ pos);
	pos = pos.replace("px",""); // Remove px from value of pos, e.g. "20px" -> "20"
	pos = parseInt(pos); // Make pos a number variable instead of a text string, i.e. "20" -> 20
	if (direction == "right") {
		pos = pos - speed; // the background has to move towards left, hence the negative x-value
	}
	else {
		pos = pos + speed; // move background to right, i.e. increase distance to left side
	}
	aniObject.style.backgroundPositionX = pos + "px"; // turn pos back into a text string with the added "px" and assign to element x-value
	
}

function animateItems() {
	for(var i=0; i<itemsList.length; i++) { // run through the list of animated elements
		animent = itemsList[i]; // Get the individual element
		var pos = stageFrame*(-parseInt(animent.getAttribute('data-speed'))); // Get speed, use negative modifier to move opposite direction of character
		pos = pos + parseInt(animent.getAttribute('data-x')); // Add the x-position offset
		animent.style.backgroundPositionX = pos+"px";
		console.log(pos+"px");
		//itemsList[i].style.backgroundPosition = '0px 0px';
	}

}
I hope I haven't posted too much code, but I felt it was necessary.
JacobP is offline   Reply With Quote
Old 12-12-2012, 10:39 PM   PM User | #2
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,579
Thanks: 62
Thanked 4,063 Times in 4,032 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Depends a lot on how accurate you need the detection to be and what the shapes colliding look like.

If the shapes are really irregular and you must detect the collision right down to the pixel level, then you don't have much choice but to do it basically pixel by pixel. Which is why some of us wish for the old Atari Computer 8-bit days, where they did collision detection in the hardware. <grin/>

But anyway:
http://lmgtfy.com/?q=collision+detection+2d+javascript
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 12-13-2012, 10:17 AM   PM User | #3
JacobP
New to the CF scene

 
Join Date: Dec 2012
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
JacobP is an unknown quantity at this point
Hey, thanks for the answer.

As you may or may not see from the code, our player object isn't moving, but rather, the backgrounds moves around him. And we placed a present at some point in the background, a certain stage frame, that will only show once, and then dissappears when you go past it. We want, when our player object hits that certain stage frame, to have the present dissappear, as if he picks it up.

It doesn't have to be precise, it could just be in his vincinity! I hope you can help me.

I looked at your link, but the explainings are very general, and for a newbie javascripter like me, it's hard to translate it to our problem.
JacobP is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 09:02 AM.


Advertisement
Log in to turn off these ads.