【问题标题】:Reset/lock html5 canvas position to center on player when panning平移时重置/锁定 html5 画布位置以在播放器上居中
【发布时间】:2012-01-09 03:14:20
【问题描述】:

我不知道该怎么做。我正在同时翻译角色和背景,但如果有任何问题,角色位置会滑出画布的可视区域,我需要根据玩家的位置进行画布翻译(hero.x , hero.y)。

目前我有

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 480;

//then in my update function
if (38 in keysDown && hero.y > 0){ //UP KEY PRESSED KEY
ctx.translate(0,12);   //translate background position +12y
hero.y -= hero.speed * modifier; //move player up on the background image

else if (40 in keysDown && hero.y < 3750-64){ //DOWN KEY PRESSED
ctx.translate(0, -12); 
hero.y += hero.speed * modifier;    
}
}

这会移动播放器和画布,但不能保证一起移动...如果它完全冻结,则播放器偏离中心甚至不在屏幕上。

可视画布区域为 640x480,但您可以在其上导航的背景图像为 5,000 x 3750。

在网络浏览器上,当它没有冻结时,它会按照我的意愿运行,以与角色相同的速度移动播放器和背景。

但是,手机上的相同速率使玩家比屏幕转换的速度要快得多,这意味着玩家会直接走出可视区域,即使它仍然会移动背景。

如果我执行 ctx.translate(hero.x, hero.y) 并使用玩家的 hero.x, hero.y 坐标,或者它的一些变化减去偏移量,它会移动背景 BY 每次我按下键而不是移动它那个位置时进行那个测量。

我怎样才能使一切都以玩家的位置为条件来移动玩家和背景,但是一起移动,或者自动调整下一个 update() 以使玩家居中....?????

【问题讨论】:

    标签: html canvas


    【解决方案1】:

    如何使所有内容都以玩家位置为条件以同时移动玩家和背景,但同时移动,或者自动调整下一个 update() 以使玩家居中

    嗯,最简单的方法就是始终将玩家画在中间!换句话说,永远不要改变或翻译他或她的坐标。而不是担心翻译与此相关的所有其他内容。

    由于您希望播放器始终位于中心,因此您应该始终将播放器绘制在画布的中心(640/2 x 480/2 适合您)

    然后您要做的是为 X 和 Y 保留画布偏移并使用该偏移绘制所有内容(背景等),然后重置转换并在普通的旧中心绘制英雄。

    所以你的绘图函数可能看起来像这样:

    function draw() {
        ctx.clearRect(0,0,500,500);
        // Save the default transformation matrix
        ctx.save();
        // Translate by the background's offset
        ctx.translate(xoffset, yoffset);
        // Draw the background (and maybe other things) translated
        ctx.fillStyle = backgroundGradient; 
        ctx.fillRect(0,0,500,500);  
        // We restore to the default transformation
        // This will draw the hero not translated at all
        // That means we can always draw the hero in the center!
        ctx.restore();
        // hero is a black rectangle
        ctx.fillRect(240, 240, 20, 20);
    }
    

    这是一个使用鼠标上下操作的实时示例。移动的背景有一个大“太阳”,而“保持”矩形保持静止,因为它实际上总是绘制在同一个地方:

    http://jsfiddle.net/3CfFE/

    【讨论】:

    • 啊,使用偏移变量是有道理的,但是现在实现起来会很痛苦,我是如何设置的。我有一个 5000 x 3750 背景分为 25 个区域,当你进入每个不同的区域时会激活不同的怪物。在背景“关卡”中还策略性地绘制了物体、建筑物和各种物品。但是看起来这可能是最好的方法,呃......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2014-09-14
    • 1970-01-01
    • 2013-03-29
    • 2017-09-24
    相关资源
    最近更新 更多