I am writing a canvas-based game which involves many sprites on the canvas at one time. In some cases the sprites are not visible and to save render cycles I do not render them to the canvas if the player will not see them. This works great for sprites that are not rotated but as soon as they become rotated (especially rectangles) I can no longer accurately determine if they are still within the visible canvas.
Here is what I am doing so far as part of my main render loop:
if (image !== null) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation * Math.PI/180);
ctx.drawImage(image, 0,0, this.width, this.height);
ctx.restore();
}
开发者_如何转开发Before I render the sprite using the above code I determine if it is visible using this code:
// Only draw sprite sthat are visible to the player.
if (sprite.x + boundingBox >= 0 && sprite.y + boundingBox >= 0 && sprite.x <= this.width && sprite.y <= this.height) {
sprite.draw(this.gameConsole.ctx);
}
What happens is that once I rotate a nonuniform sprite for example a rectangle the width and height are no longer correct because they assume they are in an nonrotated state. How would you approach this problem?
the rotation says that where point P is a corner-point (one of the 4) of the nonuniform sprite resulting in R after Rotation
a = this.rotation * (PI/180)
with the help of a rotation matrix
Rx = Px * cos(a) + Py * -sin(a)
Ry = Px * sin(a) + Py * cos(a)
so you could test if R is inside the canvas.
if you use ctx.setTransform instead of rotate you can do it all at once, that is test first, render if needed ;)
You could calculate the diagonal and use that to determine whether the sprite is visible
var diagonal = Math.sqrt(boundingBox * boundingBox * 2);
if (sprite.x + diagonal >= 0 && sprite.y + diagonal >= 0 && sprite.x <= this.width && sprite.y <= this.height) {
sprite.draw(this.gameConsole.ctx);
}
精彩评论