我正在尝试制作一个使用kineticjs制作多个圆形物体的游戏。
这是html:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="../css/style.css"/>
</head>
<body>
<!--<canvas id="canvasRegn" width="600" height="450" style="margin:100px;"></canvas>-->
<div id="container" style="width: auto; height: auto; background:#000; margin:auto; float:left;"></div>
<script src="../js/jquery.min.js"></script>
<script src="../js/kinetic-v5.0.0.min.js"></script>
<script type="text/javascript" src="../js/rain2.js"></script>
</body>
</html>
我在js中的逻辑是 - &gt; 我将“敌人”(圆形kineticjs对象)推入数组“enemyArmada”,这是在“createEnemy()”函数中完成的。
使用setInterval每35ms调用一次“draw”函数,其中所需的位置和速度被改变以创建移动效果。
这是js代码:
var x = 0;
var y = 0;
var noOfEnemies = 2;
var enemyArmada = new Array();
createEnemy();
var stage = new Kinetic.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
listening: true
});
var layer = new Kinetic.Layer({
listening: true
});
function createEnemy() {
for (var i = 0; i < noOfEnemies; i++) {
var enemy = new Kinetic.Circle({
x: Math.random() * 1200,
y: Math.random() * 5,
radius: 6,
fill: 'red',
stroke: 'black',
speed: 3 + Math.random() * 5
});
enemyArmada.push(enemy);
}
// setInterval(draw, 35);
draw();
}
function draw() {
for (var i = 0; i < noOfEnemies; i++)
{
console.log(enemyArmada[i].getPosition().x);
enemyArmada[i].setPosition({x:enemyArmada[i].getPosition().x + 10, y:enemyArmada[i].getPosition().y + 10});
console.log(enemyArmada[i].getPosition().x + " " + enemyArmada[i].getPosition().y + "" + enemyArmada[i].speed);
}
layer.add(enemyArmada);
layer.draw();
stage.add(layer);
}
这是css:
html {
color:#000;
background:#222222;
}
a {
cursor:pointer;
list-style: none;
}
html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
overflow: hidden;
}
html, body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td {
margin:0;
padding:0;
}
#container {
background:#000;
margin:auto;
cursor:none;
float:left;
width:auto;
height: auto;
}
我的最终目标是在这个游戏中制造敌人: http://www.sinuousgame.com/
这是小提琴: http://jsfiddle.net/R3p5s/3/
答案 0 :(得分:2)
您在创建图层对象之前调用createEnemy
,因此在调用layer
时未定义变量createEnemy
值。
var stage = new Kinetic.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
listening: true
});
var layer = new Kinetic.Layer({
listening: true
});
//need to call it after the layer is created
createEnemy();
演示:Fiddle
您还可以阅读hoisting