javascriptthree.jsphysics

What's the best way to restrict movement for the camera to a certain location in THREE js?


I'm making a game that includes gravity and I need to make it so when you hit a wall or something than you can't move. I was thinking something along the lines of just stopping the forward movement but then you can just turn around and go into it backwards. No such luck so far.

Here's my movement code:

document.onkeydown = function(e) {
    // e.preventDefault()
    if(e.keyCode == 87) {
        player.movement.w = true
    }
    if(e.keyCode == 65) {
        player.movement.a = true
    }
    if(e.keyCode == 83) {
        player.movement.s = true
    }
    if(e.keyCode == 68) {
        player.movement.d = true
    }
    if(e.keyCode == 69) {
        player.movement.e = true
    }
    if(e.keyCode == 81) {
        player.movement.q = true
    }
}
document.onkeyup = function(e) {
    if(e.keyCode == 87) {
        player.movement.w = false
    }
    if(e.keyCode == 65) {
        player.movement.a = false
    }
    if(e.keyCode == 83) {
        player.movement.s = false
    }
    if(e.keyCode == 68) {
        player.movement.d = false
    }
    if(e.keyCode == 69) {
        player.movement.e = false
    }
    if(e.keyCode == 81) {
        player.movement.q = false
    }
}

function loop() {
requestAnimationFrame(loop)

if(player.look.locked == true) {
        if(player.movement.w == true) {
            playerObj.translateZ(player.movement.speed / 100)
        }
        if(player.movement.a == true) {
            playerObj.translateX(player.movement.speed / 100)
        }
        if(player.movement.s == true) {
            playerObj.translateZ(player.movement.speed / 100 * -1)
        }
        if(player.movement.d == true) {
            playerObj.translateX(player.movement.speed / 100 * -1)
        }
        if(player.movement.e == true) {
            playerObj.translateY(player.movement.speed / 100 * -1)
        }
        if(player.movement.q == true) {
            playerObj.translateY(player.movement.speed / 50)
        }
    }
}
loop()

(I know event.keyCode is depreciated)


Solution

  • I was originally using this to make a 3D game with THREE.js but since I wasn't experienced with physics I thought that this would be an easy workaround. It wasn't.

    I would recommend using CANNON.js and instead moving the camera using camera.position.x += speed or camera.translateX(speed) set the camera to a box in CANNON.js and using a loop to set the camera position to the position of the box. Then using box.velocity.x = speed to move around. This has collision detection in it and you can use other CANNON.js shapes to make a scene.

    Also, I had this problem for some reason when I was starting with it so I thought I'd mention it: CANNON.js scene and THREE.js scene are completely separate worlds and then you combine the two.