【发布时间】:2016-04-24 14:14:23
【问题描述】:
我正在 React/html5/canvas 中做一个应用程序。在画布中,您作为用户可以通过鼠标点击在不同的房间中移动。这行得通,我已经对房间的所有墙壁进行了碰撞检测(视图是 2d 的,就像 RTS 游戏一样)。
现在问题来了:当我撞墙时,我设置了user.collision = true;,下一次鼠标点击将设置user.collision = false;,这将使我的角色再次移动。问题是,如果我再点击几次(它会穿过),我现在可以穿过墙壁。
已经考虑了这方面的逻辑,但我无法弄清楚,我的研究对我没有帮助。
这是我的碰撞检测功能:(所有的墙都在this.props.data)
collision: function(){
for (var i = 0; i < this.props.data.length; i++){
if (user.posX > this.props.data[i].x2 && user.posX < this.props.data[i].x1 &&
user.posY < this.props.data[i].y2 && user.posY > this.props.data[i].y1){
user.collision = true;
}
}
},
这是我的 handleMouseClick 函数:
handleMouseClick: function(event){
var rect = game.getBoundingClientRect();
mouseClick.y = event.nativeEvent.clientY - rect.top;
mouseClick.x = event.nativeEvent.clientX - rect.left;
distance = Math.sqrt(Math.pow(mouseClick.x - user.posX, 2) + Math.pow(mouseClick.y - user.posY,2));
user.directionX = (mouseClick.x - user.posX) / distance;
user.directionY = (mouseClick.y - user.posY) / distance;
if (user.collision = true){
user.collision = false;
}
},
这是我的更新功能:
update: function(){
context.canvas.height);
if (!user.collision){
if(user.moving === true){
user.posX += user.directionX * user.speed * elapsed;
user.posY += user.directionY * user.speed * elapsed;
this.collision();
if(user.posX >= mouseClick.x -5 && user.posX <= mouseClick.x + 5 && user.posY >= mouseClick.y -5 && user.posY <= mouseClick.y + 5){
user.moving = false;
}
}
}
this.drawUser();
this.drawWalls();
},
【问题讨论】:
-
除非您发布
React代码,否则我建议您删除React标记 - 这似乎是一个纯粹的 JS 逻辑问题。 -
我的代码 sn-ps 中有一些 React 代码,所有这些代码都在我的
类中。 -
让我们看看
drawUser和drawWalls做了什么 -
Matthew Herbst:要么写一些实际上与问题有关的东西,要么停止评论与问题无关的东西? @markE 谢谢,会检查一下,看看它是否对我有帮助。
标签: javascript reactjs html5-canvas