平移时重置/锁定html5画布位置,使其位于玩家的中心
我不知道怎么做。我同时翻译了角色和背景,但是如果有任何问题,角色的位置会滑出画布的可视区域,我需要画布的翻译基于玩家的位置(hero.x,hero.y) 目前我有平移时重置/锁定html5画布位置,使其位于玩家的中心,html,canvas,Html,Canvas,我不知道怎么做。我同时翻译了角色和背景,但是如果有任何问题,角色的位置会滑出画布的可视区域,我需要画布的翻译基于玩家的位置(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 keysD
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;
}
}
var canvas=document.createElement(“canvas”);
var ctx=canvas.getContext(“2d”);
画布宽度=640;
canvas.height=480;
//然后在我的更新函数中
如果(38 in keysDown&&hero.y>0){//UP键按下
平移(0,12);//平移背景位置+12y
hero.y-=hero.speed*modifier;//在背景图像上向上移动玩家
否则,如果按下(40 in keysDown&&hero.y<3750-64){//DOWN键
ctx.translate(0,-12);
hero.y+=hero.speed*修改器;
}
}
这会移动玩家和画布,但不能保证一起移动…如果它完全冻结,玩家就会偏离中心,甚至离开屏幕
可查看的画布区域为640x480,但可导航的背景图像为5000 x 3750
在web浏览器上,当它没有冻结时,它会按照我想要的方式工作,以与角色相同的速度移动播放器和背景
然而,在手机上同样的速度使玩家比屏幕上的速度快得多,这意味着玩家即使仍然移动背景,也会直接走出可视区域
如果我执行ctx.translate(hero.x,hero.y)并使用播放器的hero.x,hero.y坐标,或者使用它的某个变量减去偏移量,则每当我按下该键时,它都会按该测量值移动背景,而不是将其移动到该位置。
如何使所有内容都以玩家位置为条件,同时移动玩家和背景,或者自动调整下一次更新()以玩家为中心
如何使所有内容都以玩家的位置为条件,同时移动玩家和背景,或者自动调整next 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);
}
下面是一个使用鼠标上下移动的实例。移动的背景有一个大“太阳”,而“保持”矩形保持静止,因为它总是在同一个位置绘制:
啊,使用偏移量变量是有道理的,但现在实施起来会很痛苦,我是如何设置的。我有一个5000 x 3750的背景分成25个区域,当你进入每个不同的区域时,不同的怪物被激活。还有物体、建筑物和各种各样的物品,它们战略性地绘制在背景“层”上。但是看起来这可能是最好的办法,呃。。。