this might be really obvious, but I'm a complete coding beginner... can somebody tell me why this only executes the function with main(5)? And how could I change it so that main(2) executes after main(1), etc? Thanks!
for (var k = 1; k < 6; k++){
main(k);
}
edit: sorry, this is the definition of main! I'm trying to animate a bunch of squares using a canvas
var main = function (speed) {
Enemy.prototype.update = function () {
var tx = 650 - this.x;
var ty = 250 - this.y;
var dist = Math.sqrt(tx * tx + ty * ty);
this.velx = (tx / dist) * speed;
this.vely = (ty / dist) * speed;
if (dist > 0) {
this.x += this.velx;
this.y += this.vely;
}
};
Enemy.prototype.isOnEnemy = function (x, y) {
return (x >= this.x && x < this.x + 25 && // 25 = width
y >= this.y && y < this.y + 25); // 25 = height
};
Enemy.prototype.render = function () {
context.fillStyle = 'rgba(255,255,255,' + this.transparency + ')';
context.fillRect(this.x, this.y, 25, 25);
};
var enemies = [];
for (var i = 0; i < 10; i++) {
// random numbers from 0 (inclusive) to 100 (exclusive) for example:
var randomX = Math.random() * 896;
var randomY = Math.random() * 1303;
console.log(randomX);
console.log(randomY);
if (randomX > 100 && randomX < 1200) {
if (randomX % 2 === 0) {
randomX = 140;
} else {
randomX = 1281;
}
}
if (randomY > 100 && randomY < 75) {
if (randomY % 2 === 0) {
randomY = 15;
} else {
randomY = 560;
}
}
var enemy = new Enemy(randomX, randomY, 0, 0, 1);
enemies.push(enemy);
}
for (var i = 0; i < 15; i++) {
// random numbers from 0 (inclusive) to 100 (exclusive) for example:
var randomX = Math.random() * 200;
var randomY = Math.random() * 403;
console.log(randomX);
console.log(randomY);
if (randomX > 100 && randomX < 1200) {
if (randomX % 2 === 0) {
randomX = 140;
} else {
randomX = 1281;
}
}
if (randomY > 100 && randomY < 75) {
if (randomY % 2 === 0) {
randomY = 15;
} else {
randomY = 560;
}
}
var enemy = new Enemy(randomX, randomY, 0, 0, 1);
enemies.push(enemy);
}
context.canvas.onmousemove = function (e) {
var rect = this.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top,
i = 0;
for (; i < enemies.length; i++) {
if (enemies[i].isOnEnemy(x, y)) {
enemies[i].transparency = 0;
}
}
};
function render() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < enemies.length; i++) {
var one = enemies[i];
one.update();
one.render();
}
requestAnimationFrame(render);
}
render();
};
mainfunction, can you post the definition ofmain?Enemy.prototypecan only retain 1 each ofupdate,isOnEnemy, etc. Each call tomain()is redefining these, overriding and discarding any previous definitions, affecting all existingnew Enemy()instances. And, the last set of them knowsspeedto be5.