我正在使用此功能为我的粒子系统创建一个粒子:
function particle()
{
this.speed = {x: -1.5+Math.random()*3, y: -12+Math.random()*12};
this.location = {x: 50, y: 150};
this.radius = 5+Math.random()*8;
this.life = 4+Math.random()*8;
this.remaining_life = this.life;
this.r = 255;
this.g = 140;
this.b = 30;
}
我正在使用此功能在动画过程中更新粒子特征:
particle.prototype.updateparticle = function()
{
this.remaining_life--;
this.radius--;
this.location.x += this.speed.x;
this.location.y += this.speed.y;
if(this.remaining_life < 0 || this.radius < 0)
{
this.speed = {x: -1.5+Math.random()*3, y: -12+Math.random()*12};
this.location = {x: 50, y: 150};
this.radius = 5+Math.random()*8;
this.life = 4+Math.random()*8;
this.remaining_life = this.life;
this.r = 255;
this.g = 140;
this.b = 30;
}
}
有没有办法可以避免冗余代码?
此外,我尝试使用this = new particle()
,但它无效。我想不出它为什么不起作用的原因。为什么不呢?
在一个完全不相关的说明中,Firefox无法处理粒子动画吗? Chrome使用了我CPU的5%。 Firefox使用大约30个而且仍然滞后!我有一个i5 2500k所以这应该不是问题。我正在运行两者的最新版本。
答案 0 :(得分:2)
Apply函数,将当前对象作为this
参数传递:
particle.prototype.updateparticle = function()
{
this.remaining_life--;
this.radius--;
this.location.x += this.speed.x;
this.location.y += this.speed.y;
if(this.remaining_life < 0 || this.radius < 0)
{
particle.apply(this);
}
}
答案 1 :(得分:2)
创建原型函数以初始化值
function particle() {
this.init();
}
particle.prototype.init = function(){
this.speed = {x: -1.5+Math.random()*3, y: -12+Math.random()*12};
this.location = {x: 50, y: 150};
this.radius = 5+Math.random()*8;
this.life = 4+Math.random()*8;
this.remaining_life = this.life;
this.r = 255;
this.g = 140;
this.b = 30;
}
particle.prototype.updateparticle = function() {
this.remaining_life--;
this.radius--;
this.location.x += this.speed.x;
this.location.y += this.speed.y;
if(this.remaining_life < 0 || this.radius < 0) {
this.init();
}
}
答案 2 :(得分:2)
您可以将其设为另一个功能,并在需要时调用。
function particle()
{
this.initialize();
}
particle.prototype.initialize = function(){
this.speed = {x: -1.5+Math.random()*3, y: -12+Math.random()*12};
this.location = {x: 50, y: 150};
this.radius = 5+Math.random()*8;
this.life = 4+Math.random()*8;
this.remaining_life = this.life;
this.r = 255;
this.g = 140;
this.b = 30;
}
particle.prototype.updateparticle = function()
{
this.remaining_life--;
this.radius--;
this.location.x += this.speed.x;
this.location.y += this.speed.y;
if(this.remaining_life < 0 || this.radius < 0)
{
this.initialize();
}
}
答案 3 :(得分:0)
function particle(x, y, r, g, b) {
this.location = {x: x, y: y};
this.r = r;
this.g = g;
this.b = b;
// Group everything that randomises in update()
this.update = function() {
this.speed = {x: -1.5+Math.random()*3, y: -12+Math.random()*12};
this.radius = 5+Math.random()*8;
this.life = 4+Math.random()*8;
this.remaining_life = this.life;
}
this.update();
}
particle.prototype.updateparticle = function() {
this.remaining_life--;
this.radius--;
this.location.x += this.speed.x;
this.location.y += this.speed.y;
if(this.remaining_life < 0 || this.radius < 0) {
this.update();
}
}
//Instantiation
var p1 = new particle(50, 150, 255, 140, 30);