以坐标为中心制作画布精灵 [英] Making Canvas Sprites Centered on Coordinates

查看:50
本文介绍了以坐标为中心制作画布精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Vanilla JS开发HTML5 Canvas上的Canvas游戏.

I am working on a Canvas Game on HTML5 Canvas with Vanilla JS.

由于某种原因,我注意到当将播放器精灵设置为在x轴上的x = 0处绘制时,播放器会向右缩进.

For some reason I am noticing that when I set the player sprite to be drawn in at on the x-axis at x=0, the player appears indented to the right.

(这似乎干扰了我的碰撞检测)

(this appears to be disrupting my collision detection)

我使用piskel应用程序生成的其他精灵也存在相同的问题.我从另一个创作者那里使用的另一个精灵没有这个问题.

I have the same issue with other sprites I have generated with the piskel app. Another sprite I used from another creator didn't have this issue.

有人有什么建议吗?

这是我的游戏的链接: http://zcbuhler.github.io/spaceDrift

Here is a link to my game: http://zcbuhler.github.io/spaceDrift

播放器的起始点应该在x轴上为0,但是如您所见,似乎已被标记.

The player should be at 0 on the x-axis for the starting point, but as you can see appears to be tabbed over.

推荐答案

通用Sprite渲染

我使用以下功能渲染精灵.

General purpose sprite rendering

I render sprites with the following function.

// assumes ctx is scoped and is the rendering 2d context
function drawSprite(img, x, y, scale, rotate, alpha){
    var w = img.width;
    var h = img.height;
    ctx.setTransform(scale, 0, 0 ,scale, x, y);
    ctx.rotate(rotate);
    ctx.globalAlpha = alpha;
    ctx.drawImage(img, 0, 0, w, h, -w/2,-h/2, w, h);
}

绘制一个以x,y为中心的精灵.缩放并旋转它,并设置其Alpha.在普通笔记本电脑和Firefox上,它可以实时处理2000多个精灵.在chrome上,大约有1000 +

It draws the sprite with its center at x,y. It is scaled and and rotated and its alpha is set. On a average laptop and on firefox it can do 2000+ sprites in realtime. On chrome its about 1000+

要设置中心点,请使用

// assumes ctx is scoped and is the rendering 2d context
function drawSpriteCenter(img, x, y, cx, cy, scale, rotate, alpha){
    var w = img.width;
    var h = img.height;
    ctx.setTransform(scale, 0, 0 ,scale, x, y);
    ctx.rotate(rotate);
    ctx.globalAlpha = alpha;
    ctx.drawImage(img, 0, 0, w, h, -cx,-cy, w, h);
}

其中cx和cy是子画面的中心点.(它旋转的点)

where cx, and cy s the center point of the sprite. (the point around which it rotates)

绘制一个精灵,它的中心cx,cy在x,y处,并且缩放比例为x和y,并随alpha旋转.

To draw a sprite with a center cx,cy at x,y and a scale for x and y, rotated with alpha.

// assumes ctx is scoped and is the rendering 2d context
function drawSpriteFull(img, x, y, cx, cy, scaleX, scaleY, rotate, alpha){
    var w = img.width;
    var h = img.height;
    ctx.setTransform(scaleX, 0, 0 ,scaleY, x, y);
    ctx.rotate(rotate);
    ctx.globalAlpha = alpha;
    ctx.drawImage(img, 0, 0, w, h, -cx, -cy, w, h);
}

该函数修改当前的变换和alpha.渲染完精灵后,可以重置画布状态

The functions modify the current transform and alpha. To reset the canvas state once you are done rendering the sprites you can use

function resetCtx(){
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.globalAlpha = 1;
}

这篇关于以坐标为中心制作画布精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆