"背景”;使用javascript和html5的游戏动画
"Background" Game animations with javascript and html5
假设我的基类如下:
function Tile(obj) {
//defaults (alot of variables here like colors and opacity)
}
Tile.prototype.Draw = function () {
ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," + this.Opacity + ")";
ctx.fillRect(this.X, this.Y, this.Width, this.Height);
};
从Tile类继承的我的类
Apple.prototype = new Tile();
Apple.prototype.constructor = Apple;
function Apple(obj) {
Tile.apply(this, arguments);
}
所以我想对我的苹果对象做的是让它的不透明度在0和1之间波动,这样它就可以不断地淡入和淡出,但我希望这与"游戏循环"无关。(这样无论游戏速度如何,渐变动画都是平滑的)
function StartGameLoop() {
console.log("*** Starting Game ***");
gameLoop = setInterval(Game, gameSpeed);
}
function Game() {
if (!IS_GAME_ON) { // Did the game end?
EndGame();
} else if (!PAUSE) { // Is the game not paused?
console.log("Tick");
Logic(); // do any math
}
}
我无法理解如何做到这一点,但我曾想过在Apple构造函数中放入一个setInterval,它会反复调用draw函数,但我无法让它发挥作用。像这样:
Apple.prototype = new Tile();
Apple.prototype.constructor = Apple;
function Apple(obj) {
var AnimationDirection;
var animate = setInterval(this.Draw, 50);
Tile.apply(this, arguments);
}
Apple.prototype.Draw = function () {
ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," + this.Opacity + ")";
ctx.fillRect(this.X, this.Y, this.Width, this.Height);
if (this.Opacity <= 0) {
this.AnimationDirection = 0.1;
}
else if (this.Opacity >= 1) {
this.AnimationDirection = -0.1;
}
this.Opacity += this.AnimationDirection;
};
当第一个苹果出现时,它的工作原理正如你所期望的那样。Draw()被调用,但来自setInterval的调用无法正常工作。有什么想法吗?
(附言:此外,Draw函数中的两条ctx线在Tile和Apple类中都重复,我有没有办法把它踢到Tile父级进行填充,而不是重复代码?)
我认为原因是当Draw()
函数作为setInterval
调用的一部分触发时,this
并不是你想象的那样。
相反,当this
引用创建的Apple对象时,请在构造函数中使用一个变量来存储其值,并为setInterval()
使用一个匿名函数,以便能够引用该新变量并正确调用其上的Draw()
函数,例如:
function Apple(obj) {
var AnimationDirection, me = this;
var animate = setInterval(function() {
me.Draw();
}, 50);
Tile.apply(this, arguments);
}
由于您现在正在Apple
对象(而不是全局窗口)上调用Draw()
方法,因此this
将正确引用该对象。
相关文章:
- 下载HTML5/Javascript MOBILE应用程序中的PDF文件
- 是否可以使用HTML5/javascript播放此流
- 条形图元素的HTML5 JavaScript锚点
- Teechart HTML5/Javascript价值股票代码将保留在Tee.Line系列上
- 如果按下两个不同的键,如何使事件发生(HTML5 Javascript)
- HTML5/JavaScript图像点击事件
- 对象数组上的html5 javascript冲突
- 显示/隐藏 选择 HTML5 JavaScript
- HTML5 & Javascript
- Windows 8 HTML5 JavaScript 应用程序中向左滑动的事件名称是什么
- HTML5/JavaScript.使用索引数据库时无法插入数据
- 如何在HTML5 / javascript中查找十六进制值的特定位或数字
- 当以表单形式提交时,是否可以在PHP中访问新的数据* HTML5 / Javascript值?
- HTML5 Javascript播放/暂停按钮
- 如何使用HTML5/JavaScript检查连接类型(WiFi/LAN/WWAN)
- HTML5/Javascript验证复选框提交URL重定向
- 如何防止使用HTML5/Javascript在长触摸/点击时选择画布
- HTML5/JavaScript游戏-编辑JS代码以更改AJAX请求
- HTML5+Javascript音频在音频播放的特定时间触发事件
- html5 javascript,全局变量