Jump to content

problem with rendering


thatguy

Recommended Posts

<!doctype html><meta charset="utf-8"><title>Blocking rectangles</title><h1>Use arrow keys to move around the screen.</h1><canvas width="1200" height="400" style="border: 1px dashed black"></canvas><script src="requestAnimationFramePolyfill.js"></script><script src="collision.js"></script><script>//Added some of the bounce handlers. Still need to fix glitch. Bounce for the cat to bounce off of the rectangle. Still need to create a code handler to make monster move left to right.//--- The sprite objectvar spriteObject ={  sourceX: 0,  sourceY: 0,  sourceWidth: 64,  sourceHeight: 64,  width: 64,  height: 64,  x: 0,  y: 0,  vx: 0,  vy: 0,    //Getters  centerX: function()  {    return this.x + (this.width / 2);  },  centerY: function()  {    return this.y + (this.height / 2);  },  halfWidth: function()  {    return this.width / 2;  },  halfHeight: function()  {    return this.height / 2;  }};//--- The main program//The canvas and its drawing surfacevar canvas = document.querySelector("canvas");var drawingSurface = canvas.getContext("2d");//Canvas text propertiesdrawingSurface.font = "normal bold 26px Helvetica";drawingSurface.fillStyle = "#000";drawingSurface.textBaseline = "top";var score = 0;var collisionHasOccured = false;var message = "";//An array to store the spritesvar sprites = [];//Create the box circlevar box = Object.create(spriteObject);box.sourceX = 65;box.sourceY = 65;box.x = 350;box.y = 300;box.width = 100;box.height = 100;sprites.push(box); //Create the cat circlevar cat = Object.create(spriteObject);cat.x = 150;cat.y = 350;sprites.push(cat);monsterObject = Object.create(spriteObject);var monster = Object.create(monsterObject);monster.sourceX = 64;monster.x = 40;monster.y = 336;sprites.push(monster);//The monster's allow speedmonsterObject.speed = 1;monsterObject.distanceCounter = 0;//Set the monster's intial velocitymonster.vx = monster.speed;monster.vy = 0;//Load the imagevar image = new Image();image.addEventListener("load", loadHandler, false);image.src = "collisionTileSheet02.png";var innerMeter = Object.create(spriteObject);innerMeter.sourceY = 142;innerMeter.sourceWidth = 128;innerMeter.sourceHeight = 14;innerMeter.width = 128;innerMeter.height = 14;innerMeter.x = 35;innerMeter.y = 20;sprites.push(innerMeter);var outerMeter = Object.create(spriteObject);outerMeter.sourceY = 128;outerMeter.sourceWidth = 128;outerMeter.sourceHeight = 14;outerMeter.width = 128;outerMeter.height = 14;outerMeter.x = innerMeter.x;outerMeter.y = innerMeter.y;sprites.push(outerMeter);//A variable to help test for a collisionvar message = "";//Arrow key codesvar UP = 38;var DOWN = 40;var RIGHT = 39;var LEFT = 37;//Directionsvar moveUp = false;var moveDown = false;var moveRight = false;var moveLeft = false;//Add keyboard listenerswindow.addEventListener("keydown", function(event){  switch(event.keyCode)  {    case UP:	    moveUp = true;	    break;	  	  case DOWN:	    moveDown = true;	    break;	    	  case LEFT:	    moveLeft = true;	    break;  	    	  case RIGHT:	    moveRight = true;	    break;   }}, false);window.addEventListener("keyup", function(event){  switch(event.keyCode)  {    case UP:	    moveUp = false;	    break;	  	  case DOWN:	    moveDown = false;	    break;	    	  case LEFT:	    moveLeft = false;	    break;  	    	  case RIGHT:	    moveRight = false;	    break;   }}, false);function loadHandler(){   update();}function update(){  //The animation loop  requestAnimationFrame(update, canvas);  //Up  if(moveUp && !moveDown)  {    cat.vy = -5;  }  //Down  if(moveDown && !moveUp)  {    cat.vy = 5;  }  //Left  if(moveLeft && !moveRight)  {    cat.vx = -5;  }  //Right  if(moveRight && !moveLeft)  {    cat.vx = 5;  }  //Set the cat's velocity to zero if none of the keys are being pressed  if(!moveUp && !moveDown)  {    cat.vy = 0;  }  if(!moveLeft && !moveRight)  {    cat.vx = 0;  }    if(innerMeter.width < 0)  {  		endGame();  }  if(hitTestRectangle(cat, monster))  {    if(innerMeter.width > 0)    {      innerMeter.width--;    }  }  if(innerMeter.width < 1)  {    message = "  !!Game Over!!";  }  //Move the cat   cat.x = Math.max(0, Math.min(cat.x + cat.vx, canvas.width - cat.width));  cat.y =  Math.max(0, Math.min(cat.y + cat.vy, canvas.height - cat.height));     monster.x += monster.vx;  monster.y += monster.vy;  monster.distanceCounter += monster.speed;    //Check whether the monster is at a grid cell corner  if(0, Math.min(monster.x + monster.vx, canvas.width - monster.width));  {     //If it is at a corner, change its direction    changeDirection(monster);  }    //Check the monster's screen boundaries  if(monster.x < 0)  {    monster.x = 0;    changeDirection(monster);  }  if(monster.y < 0)  {    monster.y = 0;    changeDirection(monster);  }  if(monster.x + monster.width > canvas.width)  {    monster.x = canvas.width - monster.width;    changeDirection(monster);  }  if(monster.y + monster.height > canvas.height)  {    monster.y = canvas.height - monster.height;    changeDirection(monster);  }}function changeDirection(monster){  var UP = 1;  var DOWN = 2;  var LEFT = 3;  var RIGHT = 4;    var direction = Math.ceil(Math.random() * 7);    if(direction < 5)  {    switch(direction)    {      case RIGHT:        monster.vx = monster.speed;        monster.vy = 0;        break;          case LEFT:        monster.vx = -monster.speed;        monster.vy = 0;        break;            case UP:        monster.vx = 0;        monster.vy = -monster.speed;        break;            case DOWN:        monster.vx = 0;        monster.vy = monster.speed;    }  }}    if(hitTestRectangle(cat, box) && score < 5)  {  		if(!collisionHasOccured)  		{  			score++;  			collisionHasOccured = true;  		}  }   else   	{   		collisionHasOccured = false;   	}   	   	if(score === 5)   	{   		message = "  !!You WIN!!";   	}      	   	   	  //Prevent the sprites from intersecting  //and copy the collisionSide into the game message  blockRectangle(cat, box);      //Copy the collisionSide into the game message  //(Make sure to disable or remove the method when you test this)  //message = blockRectangle(cat, box);    //Switch the order of the sprite arguments  //to let the cat push the box  //blockRectangle(box, cat); function blockRectangle(r1, r2, bounce){  //A variable to tell us which side the collision is occurring on  var collisionSide = "";      //BOUNCE    if(typeof bounce === "undefined")  {  	bounce = false;  }    if(bounce)  {  	r1.vx *= -1;  }      //Calculate the distance vector  var vx = r1.centerX() - r2.centerX();  var vy = r1.centerY() - r2.centerY();    //Figure out the combined half-widths and half-heights  var combinedHalfWidths = r1.halfWidth() + r2.halfWidth();  var combinedHalfHeights = r1.halfHeight() + r2.halfHeight();      //Check whether vx is less than the combined half-widths   if(Math.abs(vx) < combinedHalfWidths)   {    //A collision might be occurring!     //Check whether vy is less than the combined half-heights     if(Math.abs(vy) < combinedHalfHeights)    {          //A collision has occurred! This is good!       //Find out the size of the overlap on both the X and Y axes      var overlapX = combinedHalfWidths - Math.abs(vx);      var overlapY = combinedHalfHeights - Math.abs(vy);              //The collision has occurred on the axis with the      //*smallest* amount of overlap. Let's figure out which      //axis that is              if(overlapX >= overlapY)      {        //The collision is happening on the X axis         //But on which side? vy can tell us        if(vy > 0)        {          collisionSide = "top";                      //Move the rectangle out of the collision          r1.y = r1.y + overlapY;        }        else         {          collisionSide = "bottom";                    //Move the rectangle out of the collision          r1.y = r1.y - overlapY;        }      }       else       {        //The collision is happening on the Y axis         //But on which side? vx can tell us        if(vx > 0)        {          collisionSide = "left";                      //Move the rectangle out of the collision          r1.x = r1.x + overlapX;        }        else         {          collisionSide = "right";                      //Move the rectangle out of the collision          r1.x = r1.x - overlapX;        }                        //BOUNCE                if(bounce)       {       	r1.vx *= -1;       }      }     }    else     {      //No collision      collisionSide = "none";    }  }   else   {    //No collision    collisionSide = "none";  }    return collisionSide;}function hitTestRectangle(r1, r2){	var hit = false;					//Calculate the distance vector  var vx = r1.centerX() - r2.centerX();  var vy = r1.centerY() - r2.centerY();	var combinedHalfWidths = r1.halfWidth() + r2.halfWidth();	var combinedHalfHeights = r1.halfHeight() + r2.halfHeight();	var overlapX = combinedHalfWidths - Math.abs(vx);    var overlapY = combinedHalfHeights - Math.abs(vy);	//cat.x = cat.x - overlapX;	//cat.y = cat.y - overlapY;		if(Math.abs(vx) < combinedHalfWidths)   {      if(Math.abs(vy) < combinedHalfHeights)   {   	hit = true;	}	else	{		hit = false;	}}else	{		hit = false;	}	return hit;      //Render the sprites      render();}//still some glitches to work out with the end game function. find a way for the monster to move back and forth across the screen. Should be found with the hedgehog game in chapter 11 page 654 area. //find a way to block the rectangle of the score box.function endGame(){	}function render(event){   drawingSurface.clearRect(0, 0, canvas.width, canvas.height);    if(sprites.length !== 0)  {    for(var i = 0; i < sprites.length; i++)    {      var sprite = sprites[i];      drawingSurface.drawImage      (        image,         sprite.sourceX, sprite.sourceY,         sprite.sourceWidth, sprite.sourceHeight,        Math.floor(sprite.x), Math.floor(sprite.y),         sprite.width, sprite.height      );     }  }    //Display the message text above the box  drawingSurface.fillText(score + message, outerMeter.x + 180, outerMeter.y - 5);}</script>

I have created this game, and am trying to set the monster to move across the screen on the x-axis, but now that I added this new code it throws no errors, yet it doesn't render anything. I'm confused, any feedback would be appreciated. Sorry for the length, but I'm lost about where this problem could possibly be occuring. Thanks in advance!

Edited by thatguy
Link to comment
Share on other sites

Open your developer tools, go to the script tab and put a breakpoint on the line where things are drawn onto the canvas, which would be this line:

drawingSurface.drawImage

On that breakpoint, watch the values of all the variables that are being used in the function.

 

If the breakpoint is never reached then put breakpoints on the if() statements.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...