Javascript RPG Collsion Detection

January 27, 2011 at 12:34:00
Specs: Windows XP
What is wrong with this collision detection?

<html>
<head>
<title>Javascript RPG</title>
<script language="JavaScript">

function moveObj(Char, Xpix, Ypix) 
{    
   	obj = document.getElementById(Char);
	
	var px = parseInt(obj.style.left) + Xpix;		
	var py = parseInt(obj.style.top) + Ypix;
	var COL1 = parseInt(obj.style.left) = 32Xpix;
	var COL2 = parseInt(obj.style.top) = 32ypix;
	obj.style.left = px;
	obj.style.top = py;
	if(Obj.style.left = COL1 && obj.style.top = COL2)
	{
	alert('Collision alert!')
	}
}

function ProcessKeypress(e)
{
	var Char = "Character";
	var moveBy = 32;

	if (e.keyCode) keycode=e.keyCode;
	ch=String.fromCharCode(keycode);

	if(ch=='a')		moveObj(Char, -moveBy, 0);
	else if(ch=='d') 	moveObj(Char, moveBy, 0);
	else if(ch=='w') 	moveObj(Char, 0, -moveBy);
	else if(ch=='s') 	moveObj(Char, 0, moveBy);
}

</script>
</head>
<body onKeyPress="ProcessKeypress(event);">

<EMBED SRC="Sample Music.MID" LOOP="TRUE" HIDDEN="TRUE">

<img id="Level" style="left: 0px; top: 0px; position: absolute;" 
src="Level1-1.PNG">

<img id="Character" style="left: 32px; top: 32px; position: absolute;" 
src="Character.PNG">

</body>
</html>

Everything else is working. :)


See More: Javascript RPG Collsion Detection

Report •


#1
January 27, 2011 at 18:10:27
Hmm, well this doesn't fix it, but this code isn't valid -

var COL1 = parseInt(obj.style.left) = 32Xpix;
var COL2 = parseInt(obj.style.top) = 32ypix;
	

You're using two assignment operators - the second equals sign is invalid - should be an operator.

Also what is 32Xpix and 32ypix suppose to be? They're not defined...

if(Obj.style.left = COL1 && obj.style.top = COL2)

Obj should be lower case

Also, you're only assigning the value of obj.style.left to COL1 (it should be ==, not just =), this conditional statement will always return true (unless maybe you couldn't allocate memory to copy COL1 into obj.style.left ... )


ch=String.fromCharCode(keycode);

keycode is not defined - I guess you ment e.keyCode ... ?


And after all that...it still doesn't work. The bounds checking method doesn't identify the edges properly (at least in my test).


I would use a library. GameQuery has bounds checking & lets you concentrate more on the actual game development than low level things like collision detection. Check out the demos:

http://gamequery.onaluf.org/demos.php


Report •
Related Solutions


Ask Question