I'm attempting to make a game, and I've got some sprites that will overlap each other. When clearing the sprite's area with clearRect
, any sprite behind it will disappear as if the foreground sprite wasn't transparent. However, if I try to save and restore the area behind the sprite using get/putImageData
, weird things start to happen. Part of the sprites in various places do not get "undrawn", other parts seem to be broken up and yards away, and other sprites get smeared. Here's a code chunk:
var anim = function()
{
if(gtiming < Date.now() % 1000)
timing = (Date.now() % 1000) - gtiming;
if(stage == 1)
{
ugcnt = ugcnt + timing;
if(mleft == true)
{
acc = acc - 0.25;
}
else if(mright == true)
{
acc = acc + 0.25;
}
else
{
if(acc < 0 || acc > 0) acc = acc / 1.1;
}
if(kyx < 0)
{
kyx = 0;
acc = -acc;
}
else if(kyx > 432)
{
kyx = 432;
acc = -acc;
}
if(kyblk != null)
xbios.putImageData(kyblk, kyx, 155);
kyblk = null;
kyx = kyx + acc;
kyblk = xbios.getImageData(kyx, 155, 208, 245);
xbios.drawImage(kyk[Math.floor(kyf)], 0, 0, 416, 490, kyx, 155, 208, 245);
if(ugcnt > mus[r][1] * 1000)
{
ugcnt = 0;
ugobj.push(new ugnaut(Math.floor(Math.random() * 640), -208, "L"));
}
ugobj.forEach(testug);
kyf = kyf + ((timing / 1000) * (mus[r][1] * 240));
if(kyf > 119)
kyf = kyf - 119;
}
gtiming = Date.now() % 1000;
if(stage > 0)
requestAnimationFrame(anim);
}
function ugnaut(x, y, f)
{
this.x = x;
this.y = y;
this.f = f;
this.fr = 0;
this.blk = null;
this.set=function()
{
if(this.blk != null)
xbios.putImageData(this.blk, this.x, this.y);
this.blk = null;
if(f == "L")
{
this.y++;
this.blk = xbios.getImageData(this.x, this.y, 179, 208);
xbios.drawImage(ugf[this.fr], 0, 0, 179, 208, this.x, this.y, 179, 208);
this.fr++;
if(this.fr > 44) this.fr = 0;
}
}
this.getx = function()
{
return this.x;
}
this.gety = function()
{
return this.y;
}
this.getf = function()
{
return this.f;
}
}
function testug(item, index)
{
if(item.getx() > -180 && item.getx() < 640 && item.gety() > -224 && item.gety() < 400)
{
item.set();
}
else
{
item = null;
ugobj.splice(index, 1);
}
}
For those wondering, yes, I did call the Canvas 2D Context xbios
. Just felt like a fun name at the time. Anyways, from my understanding having a this
inside the "object" ugnaut
the value it holds will be local to that object's instance, and so I assume each ugnaut
will hold its own background information in this.blk
, but am I wrong? What other methods should I use?