HTML5 Canvas / JavaScript(滚动背景/相机)

时间:2015-09-17 07:46:51

标签: javascript html5 canvas

编辑:2015年9月18日摆脱那个屏幕问题,但又带来了另一个更烦人的问题。屏幕不断闪烁运动。

function drawMap(){
    context.clearRect(0, 0,canvas.width, canvas.height);
    context.drawImage(map, 0, 0);
    context.drawImage(playerSprite, currentFrame * playerWidth, iconState * playerHeight,
    playerWidth, playerHeight,xPosition, yPosition,playerWidth, playerHeight);
}

function move(x, y){
    xPosition += x; yPosition += y;
    context.translate(-x, -y);
    context.save();
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.clearRect(0, 0,canvas.width, canvas.height);
    context.restore();
}

我的屏幕搞砸了,为什么T.T,我会在下面发布相关的代码片段。请帮我指出并解决这个问题。谢谢!

http://s14.postimg.org/9vwgy59gx/dafuq.png

var mapX = 0, mapY = 0, mapXOffset = 0, mapYOffset = 0;

function move(x, y){xPosition += x; yPosition += y; context.translate(-x, -y)}
//context.translate is referring to the map canvas

function drawMap(){
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(map, mapX + mapXOffset, mapY + mapYOffset);
}

单独功能的一部分:

    if(moving[38]) {faceDirection(38);move(0, -moveDistance); mapYOffset++}
    if(moving[40]) {faceDirection(40);move(0, moveDistance); mapYOffset--}  
    if(moving[39]) {faceDirection(39);move(moveDistance, 0);mapXOffset++}
    if(moving[37]) {faceDirection(37);move(-moveDistance,0);mapXOffset--}

这是我以任何方式/形状/形式改变地图的唯一时间。

1 个答案:

答案 0 :(得分:0)

这是我为平台游戏写的一个功能,我放弃了。我测试了它,它的工作原理。相机边距是相机滚动的距离。

function testForScrolling()
{
    var translateLeft = hero.x < leftCameraMargin
        && leftCameraMargin >= minCamX;
    var translateRight = hero.x + hero.width > rightCameraMargin
        && rightCameraMargin <= maxCamX;
    var translateUp = hero.y < topCameraMargin
        && topCameraMargin >= minCamY;
    var translateDown = hero.y + hero.width > bottomCameraMargin
        && bottomCameraMargin <= maxCamY;

    if (translateLeft)
    {
        leftCameraMargin -= hero.speed;
        rightCameraMargin -= hero.speed;
        translateCanvases(hero.speed, 0);
    }
    else if (translateRight)
    {
        leftCameraMargin += hero.speed;
        rightCameraMargin += hero.speed;
        translateCanvases(-1 * hero.speed, 0);
    }
    if (translateUp)
    {
        topCameraMargin -= hero.speed;
        bottomCameraMargin -= hero.speed;
        translateCanvases(0, hero.speed);
    }
    else if (translateDown)
    {
        topCameraMargin += hero.speed;
        bottomCameraMargin += hero.speed;
        translateCanvases(0, -1 * hero.speed);
    }
}