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.
Related
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
}
My code is as follows:
var map = [];
document.body.onkeydown = document.body.onkeyup = function(e){
e = e || event; // to deal with IE
map[e.key] = e.type == 'keydown';
console.log(map)
if (map["ArrowLeft"]) {move("left")}
if (map["ArrowRight"]) {move("right")}
if (map["Spacebar"] || map[" "]) {jump()};
However if i hold down the right arrow key and then press space the character jumps without changing the x pos.
My jumping code is:
async function jump() {
var jh = j;
var i;
for (i = jh * 2; i > -Math.abs(jh) * 2 - 0.5; i -= 0.5) {
rem_rect(70, py, 30, 30)
py -= i
rect(70, py, 30, 30)
await sleep(15)
}
}
My moving code is:
async function move(d) {
var i;
for (i = 0; i < p.length; i++) {
if (d === "right") {
var j;
for (j = 0; j <= 5; j++) {
rem_rect(p[i][0], p[i][1], p[i][2], p[i][3]);
p[i][0] -= ms / 5;
rect(p[i][0], p[i][1], p[i][2], p[i][3])
await sleep(0)
}
}
else if (d === "left") {
var j;
for (j = 0; j <= 5; j++) {
rem_rect(p[i][0], p[i][1], p[i][2], p[i][3]);
p[i][0] += ms / 5;
rect(p[i][0], p[i][1], p[i][2], p[i][3])
await sleep(0)
}
}
}
}
I'm trying to code a game and I want to make it so that when you click a button, it increases the number. My game is like a mining game and you click to get ores and at the top right is a box which tells you what you are mining and you can see what you are mining, except when I click the mine button, it comes with the error which says ReferenceError: hello is not defined. The function hello is the function which gives you the ores.
I have tried fixing up some other functions which give you helpers in exchange for help but it didn't change anything, also I checked on stack overflow, but there wasn't anything that could help me. (Keep in mind I am 10 years old)
HTML:
<div class="mwrapper">
<button id="minebutton" onclick="hello()">Mine!</button>
</div>
JavaScript:
//defining the vars.
var stonei = 0;
var deepness = 0;
var stone = 0;
var silveri = 0;
var silver = 0;
var goldi = 0;
var gold = 0;
var platinumi = 0;
var platinum = 0;
var diamondi = 0;
var diamond = 0;
var alexandritei = 0;
var alexandrite = 0;
var amethysti = 0;
var amethyst = 0;
var unobtaniumi = 0;
var unobtanium = 0;
var emeraldi = 0;
var emerald = 0;
var tubi = 0;
var tub = 0;
var blockN;
var block = 0;
var money = 0;
var stoneSold = 0;
var silverSold = 0;
var goldSold = 0;
var clickers = 0;
var moneyEver = 0;
var BpS = 0;
//defining element to shorten code later
var blockEl = document.getElementById("block");
var btxtEL = document.getElementById("btxt");
var moneyEl = document.getElementById("money");
//changing what the 'Block you are mining' says
var findBlock = function(b) {
if (b === 0) {
blockEl.style.backgroundColor = "grey";
btxt.innerHTML = "Stone";
blockN = "stone";
}
else if (b === 1) {
blockEl.style.backgroundColor = "silver";
btxt.innerHTML = "Silver";
blockN = "silver";
}
else if (b === 2) {
blockEl.style.backgroundColor = "gold";
btxt.innerHTML = "Gold";
blockN = "gold";
}
else if (b === 3) {
blockEl.style.backgroundColor = "rgb(90, 89, 89)";
btxt.innerHTML = "Platinum"
blockN = "platinum";
}
else if (b === 4) {
blockEl.style.backgroundColor = "rgb(185, 242, 255)";
btxt.innerHTML = "Diamond"
blockN = "diamond";
}
else if (b <= 10) {
btxt.innerHTML = "Not coded yet";
}
//hehe
else {
btxt.innerHTML = "WHAAAA?????????";
}
}
//adds materials to the left sidebar
var createBlock = function(b) {
if (b === 0) {
stonei += 1;
stone += 1;
document.getElementById("stonei").innerHTML = stonei;
document.getElementById("stone").innerHTML = stone;
}
else if (b === 1) {
silveri += 1;
silver += 1;
document.getElementById("silveri").innerHTML = silveri;
document.getElementById("silver").innerHTML = silver;
}
else if (b === 2) {
goldi += 1;
gold += 1;
document.getElementById("goldi").innerHTML = goldi;
document.getElementById("gold").innerHTML = gold;
}
else if (b === 3) {
platinumi += 1;
platinum += 1;
document.getElementById("platinumi").innerHTML = platinumi;
document.getElementById("platinum").innerHTML = platinum;
}
else if (b === 4) {
diamondi += 1;
diamond += 1;
document.getElementById("diamondi").innerHTML = diamondi;
document.getElementById("diamond").innerHTML = diamond;
}
//not coded rest
}
//From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
//for finding the block when you mine
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
//when you click the mine button it does this
var hello = function() {
if (deepness === stone + silver + gold + platinum + diamond && stone >= stonei && silver >= silveri && gold >= goldi && platinum >= platinumi && diamond >= diamondi && stoneSold == stone - stonei && moneyEver == money + clickers &&typeof hsjsahjkd === 'undefined' || hsjsahjkd === null) {
if (deepness <= 50) {
block = 0;
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 50, deepness < 150) {
block = getRandomInt(0, 2);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 150, deepness < 250) {
block = getRandomInt(0, 3);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 250, deepness < 350) {
block = getRandomInt(0, 4);
findBlock(block);
deepness += 1;
createBlock(block)
}
else if (deepness >= 350) {
block = getRandomInt(0, 5);
findBlock(block);
deepness += 1;
createBlock(block)
}
}
else {
btxt.innerHTML = "Cheater.";
stonei = 0;
deepness = 0;
stone = 0;
silveri = 0;
silver = 0;
goldi = 0;
gold = 0;
platinumi = 0;
platinum = 0;
diamondi = 0;
diamond = 0;
alexandritei = 0;
alexandrite = 0;
amethysti = 0;
amethyst = 0;
unobtaniumi = 0;
unobtanium = 0;
emeraldi = 0;
emerald = 0;
tubi = 0;
tub = 0;
stoneSold = 0;
silverSold = 0;
goldSold = 0;
clickers = 0;
moneyEver = 0;
BpS = 0;
console.log("You cheated. The game restarted.")
if (typeof hsjsahjkd == 'undefined') {
var hsjsahjkd = 1;
}
else {
hsjsahjkd += 1;
}
document.getElementById("cheat").innerHTML = hsjsahjkd;
}
}
Sorry, but the functions needed are quite long. If you want to see the whole code, go to megagames.me/games/mining.html
I expected the out put of hello() to increment some of the ores, but it gave ReferenceError: hello is not defined.
Make sure your JavaScript is linked in the head tag or above the button. Otherwise you'll be calling a function that doesn't exist yet. An easy way to remember is to think of it as a book, you read from top to bottom the same way JavaScript executes top to bottom.
Also, try using Let and Const instead of Var and try using Switch Cases instead of if else all over. :-)
Yesterday, I had asked for help in printing out a Fractal tree. That question was answered, but now I am trying to implement one more rule into my code. And while implementing it in my code, it is printing the tree, but not at the right coordinates. Here is a link to my previous question. I would like to print both the trees side-by-side instead of on top of each other. So my question is how do I achieve that? Thanks for all the help.
Here is the new code:
var sentence = "F";
var sentence2 = "F";
var sentence3 = "X";
var rules = [];
rules[0] = {
a: "F",
b: "F[+F]F[-F]F"
}
var rulesB = [];
rulesB[0] = {
a: "F",
b: "FF-[-F+F+F]+[+F-F-F]"
}
/*
var rulesC = [];
rulesC[0] = {
a: "F",
b: "FF"
}
rulesC[1] = {
a: "X",
b: "F-[[X]+X]+F[+FX]-X"
}
*/
var x = 50; // starting x
var y = 400; // starting y
var y_stack = []; // save & restore don't handle coordinates
var y_stack2 = []
draw();
function turtle(sentence, context){
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
if (current == "F") {
y -= 20;
context.lineTo(x, y);
context.stroke();
} else if (current == "+") {
context.translate(x, y);
context.rotate((20 * Math.PI) / 180);
context.translate(-x, -y);
} else if (current == "-") {
context.translate(x, y);
context.rotate((-20 * Math.PI) / 180);
context.translate(-x, -y);
} else if (current == "[") {
context.save();
y_stack.push(y);
} else if (current == "]") {
context.restore();
y = y_stack.pop();
context.moveTo(x, y)
}
}
}
function generate(sentence){
var nextSentence = "";
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
var found = false;
for (var j = 0; j < rules.length; j++ ) {
if (current == rules[j].a) {
found = true;
nextSentence += rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
return nextSentence;
}
function turtle2(sentence2, context){
for (var i = 0; i < sentence2.length; i++) {
var current = sentence2.charAt(i);
if (current == "F") {
y -= 20;
context.lineTo(x, y);
context.stroke();
} else if (current == "+") {
context.translate(x, y);
context.rotate((22.5 * Math.PI) / 180);
context.translate(-x, -y);
} else if (current == "-") {
context.translate(x, y);
context.rotate((-22.5 * Math.PI) / 180);
context.translate(-x, -y);
} else if (current == "[") {
context.save();
y_stack2.push(y);
} else if (current == "]") {
context.restore();
y = y_stack2.pop();
context.moveTo(x, y)
}
}
}
function generate2(sentence2){
var nextsentence2 = "";
for (var i = 0; i < sentence2.length; i++) {
var current = sentence2.charAt(i);
var found = false;
for (var j = 0; j < rulesB.length; j++ ) {
if (current == rulesB[j].a) {
found = true;
nextsentence2 += rulesB[j].b;
break;
}
}
if (!found) {
nextsentence2 += current;
}
}
return nextsentence2;
}
function draw() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
// context.moveTo(x, y);
for (i = 0; i < 2; i++) {
sentence = generate(sentence);
}
console.log(sentence);
turtle(sentence, context);
//context.moveTo(100,400);
for(i = 0; i < 2; i++) {
sentence2 = generate2(sentence2);
}
console.log(sentence2);
turtle2(sentence2, context);
}
/*
function turtle3(){
//resetMatrix();
context.translate(width/6, height);
for (var n = 0; n < sentence3.length; n++){
var current = sentence3.charAt(n);
if (current == "F"){
context.stroke("#28b232");
context.lineTo(0, -len3);
context.translate(0, -len3);
}else if (current == "X"){
context.stroke("#024d08");
context.lineTo(-len3, 0);
context.translate(0, -len3);
}else if (current == "+"){
context.rotate(angle2);
}else if (current == "-"){
context.rotate(-angle2);
}else if (current == "["){
save();
}else if (current == "]"){
restore();
}
}
}
*/
/*
function generate3(){
len2 *= .5;
var nextSentence3 = "";
for (var i = 0; i < sentence3.length; i++){
var current3 = sentence3.charAt(i);
var found3 = false;
for (var j = 0; j < rulesC.length; j++ ){
if (current3 == rulesC[j].a){
found3 = true;
nextSentence3 += rulesC[j].b;
break;
}
}
if (!found3){
nextSentence3 += current3;
}
}
sentence3 = nextSentence3;
turtle3();
}*/
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.