墙壁碰撞检测,通过墙壁堵塞

时间:2016-01-19 07:46:31

标签: javascript reactjs html5-canvas

我在React / html5 / canvas中正在做一个应用程序。在画布中,用户可以使用鼠标点击在不同的房间中移动。这是有效的,我已经对房间的所有墙壁进行了碰撞检测(视图是像RTS游戏一样的2d)。

现在问题是:当我碰到墙壁时,我设置了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();
    },

1 个答案:

答案 0 :(得分:1)

如果碰撞测试失败,如何恢复到之前的位置呢?

update: function(){
    context.canvas.height);
    var prevPosX = user.posX;
    var prevPosY = user.posY;
    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.collision ) { // ooops !
                user.posX = prevPosX;
                user.posY = prevPosY;                
            }
            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();
},

NB:错字在这里

if (user.collision = true){
相关问题