在Javascript游戏引擎Turbulenz中启动一个新项目时,该网站的一个示例在index.html中包含在脚本标记中时运行正常。但是,我将该代码移动到外部.js文件的任何尝试都会导致移动的代码无法运行。
这是我的程序(运行的版本):
<!doctype html5>
<html>
<head>
<title>Blockhead</title>
<script src="jslib/debug.js"></script>
<script src="jslib/webgl/turbulenzengine.js"></script>
<script src="jslib/webgl/graphicsdevice.js"></script>
<script src="jslib/draw2d.js"></script>
</head>
<body>
<canvas id="canvas" width="400px" height="600px"/>
<script>
TurbulenzEngine = WebGLTurbulenzEngine.create ({canvas: document.getElementById("canvas")});
var graphicsDevice = TurbulenzEngine.createGraphicsDevice({});
var draw2D = Draw2D.create({graphicsDevice: graphicsDevice});
var r = 1.0, g = 1.0, b = 0.0, a = 1.0;
var bgColor = [r, g, b, a];
var x1 = 50;
var y1 = 50;
var x2 = graphicsDevice.width - 50;
var y2 = graphicsDevice.height - 50;
var rectangle = [x1, y1, x2, y2];
var drawObject =
{
color: [1.0, 0.0, 0.0, 1.0],
destinationRectangle: rectangle
};
var sprite = Draw2DSprite.create
({
width: 100,
height: 100,
x: graphicsDevice.width / 2,
y: graphicsDevice.height / 2,
color: [1.0, 1.0, 1.0, 1.0],
rotation: Math.PI / 4
});
var texture = graphicsDevice.createTexture
({
src: "particle_spark.png",
mipmaps: true,
onload: function (texture)
{
if (texture)
{
sprite.setTexture(texture);
sprite.setTextureRectangle([0, 0, texture.width, texture.height]);
}
}
});
var PI2 = Math.PI * 2;
var rotateAngle = Math.PI / 32;
function update ()
{
b += 0.01;
bgColor[2] = b % 1; // Clamp color between 0-1
sprite.rotation += rotateAngle;
sprite.rotation %= PI2; //Wrap rotation at PI * 2
if (graphicsDevice.beginFrame())
{
graphicsDevice.clear(bgColor, 1.0);
/* Rendering code goes here */
draw2D.begin(); // Opaque
draw2D.draw(drawObject);
draw2D.end();
draw2D.begin('additive'); // Additive
draw2D.drawSprite(sprite);
draw2D.end();
graphicsDevice.endFrame();
}
}
TurbulenzEngine.setInterval(update, 1000 / 60);
</script>
</body>
</html>
这是不运行的版本(唯一的变化是包含新的脚本标记以及将所有内部js移动到该文件):
<!doctype html5>
<html>
<head>
<title>Blockhead</title>
<script src="jslib/debug.js"></script>
<script src="jslib/webgl/turbulenzengine.js"></script>
<script src="jslib/webgl/graphicsdevice.js"></script>
<script src="jslib/draw2d.js"></script>
<script src="javascript/blockhead.js"></script>
</head>
<body>
<canvas id="canvas" width="400px" height="600px"/>
</body>
</html>
最后,这是他们网站上的演练来自的页面:
http://docs.turbulenz.com/starter/getting_started_guide.html
必须有一种方法将程序拆分为多个文件,否则项目将变得几乎无法管理。
答案 0 :(得分:2)
这应该有效:
<canvas id="canvas" width="400px" height="600px"/>
<script src="javascript/blockhead.js"></script>
</body>
由于
document.getElementById("canvas")
canvas元素在执行时不存在,必须在定义canvas元素后执行。
如果您在chrome中打开页面,可以按f12打开开发人员工具或使用带有firebug扩展名的Firefox。控制台应该显示错误,您可以设置断点或使用console.log检查某些变量