Hit detection between 2 moving objects in CreateJS - javascript

We are using createJS and right now I am struggling with a hit test.
I get this error:
"ss.js:203 Uncaught TypeError: Cannot read property 'x' of undefined
at hitTest (ss.js:203)
at doCollisionChecking (ss.js:215)
at heartBeat (ss.js:238)
at Function.b._dispatchEvent (createjs-2015.11.26.min.js:12)
at Function.b.dispatchEvent (createjs-2015.11.26.min.js:12)
at Function.a._tick (createjs-2015.11.26.min.js:12)
at a._handleTimeout (createjs-2015.11.26.min.js:12)"
I think the problem has to the with the 2 objects x position, but one is a player controlled character and the other object have random x value.
All the hit test example i found always consist of a static object and a moving, but this time they are both moving and i have no idea what to do.
var stage, hero, queue, circle, coin;
var coins = [];
var Score, tekst1, tekst2;
var speed = 3;
var keys = {
u: false,
d: false,
l: false,
r: false
};
var settings = {
heroSpeed: 15
};
function preload() {
"use strict";
stage = new createjs.Stage("ss");
queue = new createjs.LoadQueue(true);
queue.installPlugin(createjs.Sound);
queue.loadManifest([
{
id: 'Vacuum',
src: "img/Vacuum.png"
},
{
id: 'Dust',
src: "img/dust.png"
},
{
id: 'Pickup',
src: "sounds/pickup.mp3"
},
{
id: 'Suger',
src: "sounds/suger.wav"
},
]);
queue.addEventListener('progress', function () {
console.log("hi mom, preloading");
});
queue.addEventListener('complete', setup);
}
function setup() {
"use strict";
window.addEventListener('keyup', fingerUp);
window.addEventListener('keydown', fingerDown);
circle = new createjs.Bitmap("img/Vacuum.png");
circle.width = 40;
circle.height = 90;
stage.addChild(circle);
circle.y = 570;
circle.x = 460;
Score = new createjs.Text("0", "25px Impact", "white");
Score.x = 900;
Score.y = 680;
Score.textBaseline = "alphabetic";
stage.addChild(Score);
tekst1 = new createjs.Text("Score", "25px Impact", "white");
tekst1.x = 740;
tekst1.y = 680;
tekst1.textBaseline = "alphabetic";
stage.addChild(tekst1);
tekst2 = new createjs.Text("Bombs fallin", "40px Impact", "white");
tekst2.x = 10;
tekst2.y = 50;
tekst2.textBaseline = "alphabetic";
stage.addChild(tekst2);
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener('tick', heartBeat)
}
function addCoins() {
coin = new createjs.Bitmap("img/dust.png");
coin.x = Math.random() * 900;
coin.width = 36;
coin.height = 50;
coins.push(coin);
stage.addChild(coin);
}
function moveCoins() {
for (var i = 0; i < coins.length; i++) {
coins[i].y += speed;
}
for (var j = 0; j < coins.length; j++) {
if (coins[j].y > 650) {
console.log("hejsa");
stage.removeChild(coins[j]);
coins.splice(j, 1);
}
}
}
function maybeAddCoin() {
var rand = Math.random() * 500;
if (rand < 5) {
addCoins();
}
}
function fingerUp(e) {
"use strict";
//createjs.Sound.stop("Suger")
switch (e.keyCode) {
case 37:
keys.l = false;
break;
case 38:
keys.u = false;
break;
case 39:
keys.r = false;
break;
case 40:
keys.d = false;
break;
}
}
function fingerDown(e) {
"use strict";
switch (e.keyCode) {
case 37:
keys.l = true;
break;
case 38:
keys.u = true;
break;
case 39:
keys.r = true;
break;
case 40:
keys.d = true;
break;
}
}
function moveSlime() {
"use strict";
if (keys.l) {
circle.x -= settings.heroSpeed;
if (circle.x < 0) {
circle.x = 0;
}
if (circle.currentDirection != "left") {
circle.currentDirection = "left";
//createjs.Sound.play("Suger");
keys.u = false;
keys.r = false;
keys.d = false;
}
}
if (keys.r) {
circle.x += settings.heroSpeed;
if (circle.x > 960) {
circle.x = 960;
}
if (circle.currentDirection != "right") {
circle.currentDirection = "right";
//createjs.Sound.play("Suger")
keys.u = false;
keys.l = false;
keys.d = false;
}
}
}
function hitTest(rect1, rect2) {
if (rect1.x >= rect2.x + rect2.width || rect1.x + rect1.width <= rect2.x ||
rect1.y >= rect2.y + rect2.height || rect1.y + rect1.height <= rect2.y)
{
return false;
}
return true;
}
function doCollisionChecking() {
for (var k = coins.length - 1; k >= 0; k--) {
if (hitTest(circle, coin[k])) {
console.log("ramt");
}
}
}
function scoreTimer() {
//Score.text = parseInt(Score.text + 10);
}
function heartBeat(e) {
"use strict";
doCollisionChecking()
maybeAddCoin()
//addCoins()
moveCoins()
scoreTimer()
moveSlime()
stage.update(e);
}
window.addEventListener('load', preload);

Clearly one of your elements is undefined (either circle or coins[k]). I would start with figuring out which one.
Open your debugger.
Turn on "Pause on Exceptions" and re-run your code. When the error happens, your debugger will pause and you can inspect your code
Determine what is undefined. This should shed some light on what is causing the error
One important thing I noticed is that you are looking for rect.width when collision checking. EaselJS elements don't have a width property, so you should instead use getBounds(), which will work with Bitmaps once they are loaded.
// Example
var bounds = rect.getBounds();
var w = bounds.width, h = bounds.height;
Hope that helps!

Here's the problem:
function doCollisionChecking() {
for (var k = coins.length - 1; k >= 0; k--) {
if (hitTest(circle,
coin[k] // your array is coins, not coin
)) {
console.log("ramt");
}
}
}
It might help you in the future to pass arguments through the function instead of relying on global objects. They help you by keeping modifications to your data on tight track. With global variables, anything can modify coins from anywhere and you won't be able to tell what function it is if you have 50+ different functions editing that variable.

Related

How can I make this collision detection possible?

I'm using a number of boxes that are floating around the screen, I want for them to bounce away from each other when they collide and I am testing this by just changing their colours instead when they collide, for some reason their colour changes at the start(their starting colour is white and if they collide it should change to red but they start and stays red). Is there something I am doing wrong? I would also like for everything to be done within the constructor function. I am sorry for not commenting my code as yet.
function BoxSplash()
{
this.sample = [];
var test = false;
this.col = color(129)
this.changeColour = function()
{
this.col = color(random(0,255),random(0,128),random(0,255))
}
this.intersect = function(other)
{
for(var i = 0; i < numberss; i++)
{ var currentBox = this.sample[i]
var d = dist(currentBox.x,currentBox.y,other.x,other.y)
if(d < currentBox.width + other.width)
{
return true;
}
else
{
return false
}
}
noLoop()
}
this.draw = function()
{
stroke(255)
line(0,windowHeight/2,windowWidth,windowHeight/2)
stroke(0)
for(var i = 0; i < numberss; i++)
{
var box = {
x:random(0,windowWidth - 50),
y:random(windowHeight/2 ,windowHeight - 50),
width:50,
height:50,
speedX:random(1,5),
speedY:random(1,5)
}
this.sample.push(box)
}
//use numberss variable to work with gui
for(var i = 0; i < numberss; i++)
{
fill(this.col)
rect(this.sample[i].x,this.sample[i].y,50,50)
}
this.move()
}
this.move = function()
{
for(var i = 0; i < numberss; i++)
{
var shape = this.sample[i]
shape.x += shape.speedX
shape.y += shape.speedY
if(shape.x + shape.width >= windowWidth || shape.x <= 0 )
{
shape.speedX = -shape.speedX
}
if(shape.y + shape.height >= windowHeight || shape.y <= windowHeight/2)
{
shape.speedY = -shape.speedY;
}
for(var j = 0; j < numberss; j++)
{
var others = this.sample[j]
var d = dist(shape.x,shape.y,others.x,others.y)
if( i != j && d < shape.width + others.width)
{
test = true;
}
else
{
test = false
}
if(test)
{
this.col = color(255,0,0)
}
}
}
}
}
You should visit this link and transform their circles into your boxes.
1st: Calculate dist(object1.x, object.y, object2.x, object2.y) and save into a variable called d
2nd:
if (d < object1.h + object2.h) {
// Enter your code here
}

Disable keyboard in javascript

I'm trying to figure out how to make the keyboard get disabled after the score equals five. with everything else I'm fine. I got everything else done that I need to get done I'm just having issues with the keyboard, if I could get some help on this it would greatly be appreciated. this is just giving me a hard time so I thought I would get some help.
//Arrow key codes
var UP = 38;
var DOWN = 40;
var RIGHT = 39;
var LEFT = 37;
//Directions
var moveUp = false;
var moveDown = false;
var moveRight = false;
var moveLeft = false;
//Add keyboard listeners
window.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;
}
//Move the cat
cat.x += cat.vx;
cat.y += cat.vy;
//Check for a collision between the cat and the monster
//and change the monster's score when they collide
if(hitTestRectangle(cat, monster) && score < 5)
{
if(!collisionHasOccured)
{
score++;
collisionHasOccured = true;
}
}
else
{
collisionHasOccured = false;
}
if(score === 5)
{
message = " - Game Over!";
}
//Render the sprites
render();
}
function hitTestRectangle(r1, r2)
{
//A variable to determine whether there's a collision
var hit = false;
//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 for a collision on the x axis
if(Math.abs(vx) < combinedHalfWidths)
{
//A collision might be occuring.
//Check for a collision on the y axis
if(Math.abs(vy) < combinedHalfHeights)
{
//There's definitely a collision happening
hit = true;
}
else
{
//There's no collision on the y axis
hit = false;
}
}
else
{
//There's no collision on the x axis
hit = false;
}
return hit;
}
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
);
}
}
drawingSurface.fillText(score + message, monster.x, monster.y - 40);
}
</script>
You just need to add an if statement to your event listeners. ( IF score == 5 ) then don't do anything. You can place the code right above the switch statements.
EDIT
#JasonEnts:
window.addEventListener("keydown", function(event)
{ if (score < 5) {
switch(event.keyCode)
{
case UP:
moveUp = true;
break;
case DOWN:
moveDown = true;
break;
case LEFT:
moveLeft = true;
break;
case RIGHT:
moveRight = true;
break;
}
}
}, false);

Checking if two points are touching in a hex grid

Some time ago I wrote this fun grid that is offset to look like a hexagonal grid. I added a feature to check if any two points are touching. I thought it was brilliant until I finally found a bug and am not sure how to correct it.
If you press (1,4) and (2,5) you will see that they are "touching" but they shouldn't be. What logic am I missing in the function isTouchingHex?
Found bugs so far..
(1,4) & (2,5)
(2,2) & (3,3)
(0,0) & (1,1)
CodePen
var $point1 = $('#point1');
var $point2 = $('#point2');
var $dx = $('#dx');
var $dy = $('#dy');
var $isTouching = $('#isTouching');
var $table = $('#hexTable');
var table = [];
var rows = 10;
var cols = 5;
var point1 = null;
var point2 = null;
var clickedCount = 0;
for (let y = 0; y < rows; y++) {
var $tr = $('<div class="hexagonRow"></div>')
var row = [];
for (let x = 0; x < cols; x++) {
var $col = $('<div class="hexagon"><div class="hexagonText">' + x + ',' + y + '</div></div>');
$col.click(function() {
if (clickPoint(x, y))
$(this).toggleClass('clicked');
});
$tr.append($col);
row.push(y);
}
$table.append($tr);
table.push(row);
}
function clickPoint(x, y) {
var clicked = true;
if (point1 && point1[0] === x && point1[1] === y) {
point1 = null;
clickedCount--;
} else if (point2 && point2[0] === x && point2[1] === y) {
point2 = null;
clickedCount--;
} else if (!point1 && clickedCount < 3) {
point1 = [x, y];
clickedCount++;
} else if (!point2 && clickedCount < 3) {
point2 = [x, y];
clickedCount++;
} else {
clicked = false;
}
updateDisplay();
return clicked;
}
function updateDisplay() {
if (point1)
$point1.html(point1[0] + ',' + point1[1])
else
$point1.html('');
if (point2)
$point2.html(point2[0] + ',' + point2[1])
else
$point2.html('');
if (point1 && point2) {
var touching = isTouchingHex(point1[0], point1[1], point2[0], point2[1]) ? 'true' : 'false';
$isTouching.html(touching)
} else {
$isTouching.html('');
}
}
function isTouchingHex(x1, y1, x2, y2) {
var deltaX = x1 - x2;
var deltaY = y1 - y2;
$dx.html(deltaX);
$dy.html(deltaY);
// check same x
if (deltaX === 0) {
switch (deltaY) {
// check bottom left
case -1:
// check bottom
case -2:
// check top right
case 1:
// check above
case 2:
return true;
break;
}
} else if (deltaX === 1) {
switch (deltaY) {
// check bottom left
case -1:
// check top left
case 1:
return true;
break;
}
}else if (deltaX === -1) {
switch (deltaY) {
// check bottom right
case -1:
return true;
break;
}
}
return false;
}

moving an object using Keydown Events

I'm trying to move a box in the canvas, all the functions work fine, but as soon as i press down on any of the 4 keys the box disappears, I can tell it is because i have a ctx.ClearRect after pressing any of the 4 keys, i managed to stop it from dispersing, the problem is now it does not move or disappear and the cosole does not show any errors so I am stuck again.
any help would be really really helpful, thank you.
function Player (row,col) {
this.isUpKey = false;
this.isRightKey = false;
this.isDownKey = false;
this.isLeftKey = false;
this.row = row;
this.col = col;
this.color = "#f00";
}
var players = new Array();
function drawPlayer() {
players[players.length] = new Player(2,2);
for (var p = 0; p < players.length; p++) {
ctxPlayer.fillStyle = players[p].color;
ctxPlayer.fillRect(players[p].row*25, players[p].col*25, 25, 25);
}
}
function doKeyDown(e){
if (e.keyCode == 87) {
ClearPlayer();
Player.isUpKey = true;
Player.col = Player.col - 1;
}
if (e.keyCode == 83) {
ClearPlayer();
Player.isDownKey = true;
Player.col = Player.col + 1;
}
if (e.keyCode == 65) {
ClearPlayer();
Player.isLeftKey = true;
Player.row = Player.row - 1;
}
if (e.keyCode == 68) {
ClearPlayer();
Player.isRightKey = true;
Player.row = Player.row + 1;
}
}
function ClearPlayer() {
ctxPlayer.clearRect(0,0,canvasWidth,canvasHeight);
}
I created a plnkr with an example of what I think you are trying to do:
// Code goes here
function Player(row, col) {
this.isUpKey = false;
this.isRightKey = false;
this.isDownKey = false;
this.isLeftKey = false;
this.row = row;
this.col = col;
this.color = "#f00";
}
var players = [];
var ctxPlayer;
var currentPlayer;
window.onload = function()
{
ctxPlayer = document.getElementById('c').getContext('2d');
currentPlayer = players[players.length] = new Player(2, 2);
setInterval(render, 25);
}
window.onkeypress = doKeyDown;
function render()
{
ClearPlayer();
drawPlayer();
}
function drawPlayer() {
for (var p = 0; p < players.length; p++) {
ctxPlayer.fillStyle = players[p].color;
ctxPlayer.fillRect(players[p].row * 25, players[p].col * 25, 25, 25);
}
}
function doKeyDown(e) {
console.log(e);
if (e.keyCode == 97) {
currentPlayer.isUpKey = true;
--currentPlayer.row;
}
if (e.keyCode == 100) {
currentPlayer.isDownKey = true;
++currentPlayer.row;
}
if (e.keyCode == 119) {
currentPlayer.isLeftKey = true;
--currentPlayer.col;
}
if (e.keyCode == 115) {
currentPlayer.isRightKey = true;
++currentPlayer.col;
}
}
function ClearPlayer() {
ctxPlayer.clearRect(0, 0, 600, 400);
}
http://plnkr.co/edit/XejZKCkshNiihdy8ui1u?p=preview
First I introduced a render function to call clear and draw. This render function will get called every 25 ms after the window has loaded.
Then you created a new Player every draw-call. I changed it so that one player is created onload. The key-events are respective to this player-object.
Last I changed the key-events for my testing purposes, but they should work with yours too.
Keep in mind that the plnkr is just a quick example on how it works. You probably need to adjust it to your needs.

Trying to create tetris, but can't

For some reason my code refuses to let me assign an x and y position to each block. Each block is 30 pixels wide and tall and will be colored according to which piece it is a part of. Gravity and a clear function haven't been implemented and the move left and move right function are so different because it wasn't working right and then recreated it as it is seen now in the left function and it works less...
Please help!
Edit: My apologies, i dont normally post anything. The part i cant get past now is function block/add block/typeSet/assigning the type. it assigns a random one pretty well but then when that type (such as square) goes to assign x and y values it gives an error.
<!DOCTYPE html>
<html>
<head>
<title>Tetris in Canvas</title>
<style type="text/css">
canvas {
border: solid 1px black;
margin: -8px;
}
</style>
<script type="text/javascript">
var canvas = null;
var ctx = null;
var blockArray = [];
var board = [];
var blockNum = 0;
for (var s = 0; s < 14; s++) {
board[s] = [27];
for (var t = 0; t < 27; t++) {
board[s][t] = -1;
}
}
document.onkeydown = function(event) {
var keyCode;
if(event == null)
keyCode = window.event.keyCode;
else
keyCode = event.keyCode;
switch(keyCode) {
case 37:
left(blockArray.length);
break;
case 38:
up(blockArray.length);
break;
case 39:
right(blockArray.length);
break;
case 40:
down(blockArray.length);
break;
default:
break;
}
}
window.onload = function init() {
canvas = document.getElementById('Canvas1');
ctx = canvas.getContext("2d");
blank();
addBlock();
animate();
}
function up(i) {
blank();
animate();
}
function down(i) {
var u = 0;
var p = 0;
while(u<4) {
if (blockArray[i].y[u] + 1 > 26) {
u = 10;
}
else if ((board[blockArray[i].x[u]][blockArray[i].y[u] + 1]) == -1) {
u++;
}
else {
p = u;
for (var g = 0; ((g < 4) && (p = u)); g++) {
if ((blockArray[i].x[u] == blockArray[i].x[g]) && (blockArray[i].y[u] + 1 == blockArray[i].y[g])) {
u++;
}
}
if (p == u)
u = 10;
}
}
if (u < 10) {
for (var j=0; j<4; j++) {
blockArray[i].y[j] +=1;
}
}
else
addBlock();
animate();
}
function right(i) {
var u = 0;
var p = 0;
while(u<4) {
if (blockArray[i].x[u] + 1 > 13) {
u = 10;
}
else if ((board[blockArray[i].x[u] + 1][blockArray[i].y[u]]) == -1)
u++;
else {
p = u;
for (var g = 0; ((g < 4) && (p = u)); g++) {
if ((blockArray[i].x[u] + 1 == blockArray[i].x[g]) && (blockArray[i].y[u] == blockArray[i].y[g]))
u++;
}
if (p == u)
u = 10;
}
}
if (u < 10) {
for (var j=0; j<4; j++) {
blockArray[i].x[j] +=1;
}
}
else
addBlock();
animate();
}
function left(i) {
var u;
var p = 14;
for (var w = 0; w<4; w++) {
if (blockArray[i].x[w] < p) {
p = blockArray[i].x[w];
u = w;
}
}
if (p > 0) {
if ((board[blockArray[i].x[u] - 1][blockArray[i].y[u]]) == -1) {
for (var j=0; j<4; j++) {
blockArray[i].x[j] -=1;
}
}
}
animate();
}
function block(x, y, type) {
blockNum += 1;
this.id = blockNum;
this.x = [];
this.y = [];
this.landed = false;
this.type = Math.floor(Math.random() * (6)) + 1;
typeSet(this.type);
}
function addBlock() {
blockArray[blockArray.length] = new block();
}
function typeSet(type) {
i = blockArray.length;
switch (type) {
case 1:
square(i);
break;
case 2:
elR(i);
break;
case 3:
elL(i);
break;
case 4:
line(i);
break;
case 5:
zeR(i);
break;
case 6:
zeL(i);
break;
default:
break;
}
}
function animate() {
fillBoard();
colorBoard();
}
function fillBoard() {
for (var i = 0; i < 14; i++) {
for (var q = 0; q < 27; q++) {
board[i][q] = -1;
}
}
for (var i=0; i<blockArray.length; i++) {
for (var q=0; q<4; q++) {
board[blockArray[i].x[q]][blockArray[i].y[q]] = blockArray[i].type;
}
}
}
function colorBoard() {
blank();
ctx.strokeStyle = "white";
for(var q=0; q<14; q++) {
for(var r=0; r<27; r++) {
switch (board[q][r]) {
case 1:
ctx.fillStyle = "green";
color(q,r);
break;
case 2:
ctx.fillStyle = "orange";
color(q,r);
break;
case 3:
ctx.fillStyle = "cyan";
color(q,r);
break;
case 4:
ctx.fillStyle = "black";
color(q,r);
break;
case 5:
ctx.fillStyle = "yellow";
color(q,r);
break;
case 6:
ctx.fillStyle = "brown";
color(q,r);
break;
default:
break;
}
}
}
}
function color(q,r) {
ctx.fillRect(q*30,(r-4)*30,30,30);
ctx.strokeRect(q*30,(r-4)*30,30,30);
}
function square(i) {
blockArray[i].x[0] = 7;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 1;
blockArray[i].x[2] = 8;
blockArray[i].y[2] = 0;
blockArray[i].x[3] = 8;
blockArray[i].y[3] = 1;
}
function elR(i) {
blockArray[i].x[0] = 7;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 1;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 2;
blockArray[i].x[3] = 8;
blockArray[i].y[3] = 2;
}
function elL(i) {
blockArray[i].x[0] = 7;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 1;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 2;
blockArray[i].x[3] = 6;
blockArray[i].y[3] = 2;
}
function line(i) {
blockArray[i].x[0] = 7;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 1;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 2;
blockArray[i].x[3] = 7;
blockArray[i].y[3] = 3;
}
function zeR(i) {
blockArray[i].x[0] = 6;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 0;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 1;
blockArray[i].x[3] = 8;
blockArray[i].y[3] = 1;
}
function zeL(i) {
blockArray[i].x[0] = 8;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 0;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 1;
blockArray[i].x[3] = 6;
blockArray[i].y[3] = 1;
}
function blank() {
ctx.restore();
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.save();
}
function blank2() {
ctx.restore();
ctx.fillStyle = "purple";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.save();
}
function rotateImgRight() {
for(d = 0; d < 180; d++) {
setTimeout(rotateImg, 50);
}
}
function rotateImgLeft() {
for(d = 0; d < 180; d++) {
setTimeout(rotateImg2, 50);
}
}
function rotateImg2() {
degrees = degrees - 0.5;
radian = (Math.PI / 180.0) * degrees;
blank();
ctx.translate(ctx.canvas.width/2, 700);
ctx.rotate(radian);
ctx.drawImage(srcImg, -srcImg.width/2,-srcImg.height/2);
slide = (degrees / 90) % 4;
}
function rotateImg(x,y) {
degrees = degrees + 0.5;
radian = (Math.PI / 180.0) * degrees;
ctx.translate(x,y);
ctx.rotate(radian);
ctx.drawImage(srcImg, -srcImg.width/2,-srcImg.height/2);
slide = (degrees / 90) % 4;
}
</script>
</head>
<body>
<div style="width: 100%; text-align:center">
<canvas id="Canvas1" width="421" height="690">Your browser does not support canvas.</canvas>
</div>
</body>
</html>
Your function addBlock looks like this:
function addBlock() {
blockArray[blockArray.length] = new block();
}
At any arbitrary point, your blockArray length could be anything. For now let's assume it's 25.
You're inserting a block to the 25th position in the array.
Let's have a look at the block function:
function block(x, y, type) {
blockNum += 1;
this.id = blockNum;
this.x = [];
this.y = [];
this.landed = false;
this.type = Math.floor(Math.random() * (6)) + 1;
typeSet(this.type);
}
What's this typeSet command? It doesn't look like it sets anything! Let's investigate:
function typeSet(type) {
i = blockArray.length;
switch (type) {
case 1:
square(i);
break;
// blah
}
}
AHA! I've found the problem, square() goes to the blockArray at position i, which doesn't even exist yet as block() hasn't finished executing, and assigns loads of x and y variables all over the place. When block() finishes executing, it overwrites all the values that typeSet() has just written.
You need to refactor your typeSet() method so that it takes in the actual block object and sets the x and y values on that rather than trying to access the element within the array (which doesn't even exist yet):
typeSet(this, this.type);
you can start by checking if the arrays actually contain the items you think they contain
for example, in your left method, instead of this:
for (var w = 0; w<4; w++) {
if (blockArray[i].x[w] < p) {
p = blockArray[i].x[w];
u = w;
}
}
do this:
for (var w = 0; w<4; w++) {
if ((blockArray[i]) && (blockArray[i].x[w])) {
if (blockArray[i].x[w] < p) {
p = blockArray[i].x[w];
u = w;
}
}
}
it seems as though the array is not fully populated and only done so at runtime, this can lead to undefined references.
PS: i have not fully read the code; only part of it, as it is a lot to work through.

Categories