Hi,
I have find this example who works good :
var UNITWIDTH = 90; // Width of a cubes in the maze
var UNITHEIGHT = 15; // Height of the cubes in the maze
var PLAYERSPEED = 600.0; // How fast the player moves
var PLAYERCOLLISIONDISTANCE = 20; // How far away the player can get from collidabel objects
var clock;
var loader = new THREE.JSONLoader();
var camera, controls, scene, renderer;
var mapSize;
var totalCubesWide;
var collidableObjects = [];
// Flag to determine if the player can move and look around
var controlsEnabled = false;
// Flags to determine which direction the player is moving
var moveForward = false;
var moveBackward = false;
var moveLeft = false;
var moveRight = false;
// Velocity vectors for the player and
var playerVelocity = new THREE.Vector3();
// HTML elements to be changed
var blocker = document.getElementById('blocker');
var instructions = document.getElementById('instructions');
// Take control of the mouse for controls
getPointerLock();
// Set up the game
init();
function getPointerLock() {
document.onclick = function () {
container.requestPointerLock();
}
document.addEventListener('pointerlockchange', lockChange, false);
}
function lockChange() {
if (document.pointerLockElement === container) {
blocker.style.display = "none";
controls.enabled = true;
} else {
blocker.style.display = "";
controls.enabled = false;
}
}
// Set up the game
function init() {
// Set clock to keep track of frames
clock = new THREE.Clock();
// Create the scene where everything will go
scene = new THREE.Scene();
// Set render settings
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(scene.fog.color);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
// Render to the container
var container = document.getElementById('container');
container.appendChild(renderer.domElement);
// Set camera position and view details
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.y = 20; // Height the camera will be looking from
camera.position.x = 0;
camera.position.z = 0;
// Add the camera to the controller, then add to the scene
controls = new THREE.PointerLockControls(camera);
scene.add(controls.getObject());
// Check to see if keys are being pressed to move the player
listenForPlayerMovement();
// Add ground plane
createGround();
// Add boundry walls that surround the maze
createPerimWalls();
// Call the animate function so that animation begins after the model is loaded
animate();
};
// Listen for if the window changes sizes
window.addEventListener('resize', onWindowResize, false);
// Add event listeners for player movement key presses
function listenForPlayerMovement() {
// Listen for when a key is pressed
// If it's a specified key, mark the direction as true since moving
var onKeyDown = function (event) {
switch (event.keyCode) {
case 38: // up
case 87: // w
moveForward = true;
break;
case 37: // left
case 65: // a
moveLeft = true;
break;
case 40: // down
case 83: // s
moveBackward = true;
break;
case 39: // right
case 68: // d
moveRight = true;
break;
}
};
// Listen for when a key is released
// If it's a specified key, mark the direction as false since no longer moving
var onKeyUp = function (event) {
switch (event.keyCode) {
case 38: // up
case 87: // w
moveForward = false;
break;
case 37: // left
case 65: // a
moveLeft = false;
break;
case 40: // down
case 83: // s
moveBackward = false;
break;
case 39: // right
case 68: // d
moveRight = false;
break;
}
};
// Add event listeners for when movement keys are pressed and released
document.addEventListener('keydown', onKeyDown, false);
document.addEventListener('keyup', onKeyUp, false);
}
// Create the ground plane that the maze sits on top of
function createGround() {
// Create the ground based on the map size the matrix/cube size produced
// mapSize = totalCubesWide * UNITWIDTH;
mapSize = 100
// ground
var groundGeo = new THREE.PlaneGeometry(mapSize, mapSize);
var groundMat = new THREE.MeshPhongMaterial({
color: 0xA0522D,
side: THREE.DoubleSide,
shading: THREE.FlatShading
});
var ground = new THREE.Mesh(groundGeo, groundMat);
ground.position.set(0, 1, 0);
ground.rotation.x = degreesToRadians(90);
scene.add(ground);
}
// Make the four perimeter walls for the maze
function createPerimWalls() {
var halfMap = mapSize / 2; // Half the size of the map
var sign = 1; // Used to make an amount positive or negative
// Loop through twice, making two perimeter walls at a time
for (var i = 0; i < 2; i++) {
var perimGeo = new THREE.PlaneGeometry(mapSize, UNITHEIGHT);
// Make the material double sided
var perimMat = new THREE.MeshPhongMaterial({
color: 0x464646,
transparent: true,
opacity: 0,
side: THREE.DoubleSide
});
// Make two walls
var perimWallLR = new THREE.Mesh(perimGeo, perimMat);
var perimWallFB = new THREE.Mesh(perimGeo, perimMat);
// Create left/right walls
perimWallLR.position.set(halfMap * sign, UNITHEIGHT / 2, 0);
perimWallLR.rotation.y = degreesToRadians(90);
scene.add(perimWallLR);
collidableObjects.push(perimWallLR);
// Create front/back walls
perimWallFB.position.set(0, UNITHEIGHT / 2, halfMap * sign);
scene.add(perimWallFB);
collidableObjects.push(perimWallFB);
sign = -1; // Swap to negative value
}
}
// Update the camera and renderer when the window changes size
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
render();
requestAnimationFrame(animate);
// Get the change in time between frames
var delta = clock.getDelta();
// Update our frames per second monitor
animatePlayer(delta);
}
// Render the scene
function render() {
renderer.render(scene, camera);
}
function animatePlayer(delta) {
// Gradual slowdown
playerVelocity.x -= playerVelocity.x * 10.0 * delta;
playerVelocity.z -= playerVelocity.z * 10.0 * delta;
// If no collision and a movement key is being pressed, apply movement velocity
if (detectPlayerCollision() == false) {
if (moveForward) {
playerVelocity.z -= PLAYERSPEED * delta;
}
if (moveBackward) {
playerVelocity.z += PLAYERSPEED * delta;
}
if (moveLeft) {
playerVelocity.x -= PLAYERSPEED * delta;
}
if (moveRight) {
playerVelocity.x += PLAYERSPEED * delta;
}
controls.getObject().translateX(playerVelocity.x * delta);
controls.getObject().translateZ(playerVelocity.z * delta);
} else {
// Collision or no movement key being pressed. Stop movememnt
playerVelocity.x = 0;
playerVelocity.z = 0;
}
}
// Determine if the player is colliding with a collidable object
function detectPlayerCollision() {
// The rotation matrix to apply to our direction vector
// Undefined by default to indicate ray should coming from front
var rotationMatrix;
// Get direction of camera
var cameraDirection = controls.getDirection(new THREE.Vector3(0, 0, 0)).clone();
console.log(cameraDirection, "cameraDirection")
// Check which direction we're moving (not looking)
// Flip matrix to that direction so that we can reposition the ray
if (moveBackward) {
rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationY(degreesToRadians(180));
}
else if (moveLeft) {
rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationY(degreesToRadians(90));
}
else if (moveRight) {
rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationY(degreesToRadians(270));
}
// Player is moving forward, no rotation matrix needed
if (rotationMatrix !== undefined) {
cameraDirection.applyMatrix4(rotationMatrix);
}
// Apply ray to player camera
var rayCaster = new THREE.Raycaster(controls.getObject().position, cameraDirection);
console.log(controls.getObject().position, "obejct ")
// If our ray hit a collidable object, return true
if (rayIntersect(rayCaster, PLAYERCOLLISIONDISTANCE)) {
return true;
} else {
return false;
}
}
function rayIntersect(ray, distance) {
var intersects = ray.intersectObjects(collidableObjects);
for (var i = 0; i < intersects.length; i++) {
if (intersects[i].distance < distance) {
return true;
}
}
return false;
}
// Converts degrees to radians
function degreesToRadians(degrees) {
return degrees * Math.PI / 180;
}
// Converts radians to degrees
function radiansToDegrees(radians) {
return radians * 180 / Math.PI;
}
I try to implement to my project.
The problem is only with this two variables :
`var cameraDirection = controls.getDirection(new THREE.Vector3(0, 0, 0)).clone();`
var rayCaster = new THREE.Raycaster(camera.getObject().position, cameraDirection);
these variables are implement with pointerlock controls in the first example and i don’t know how to transfer this with my example where the cube (mesh) is moving with controls ?
Could you help me ? And i think that this solution would be good for me…
I purposely commented this line in my codepen so as not to have any errors. The code therefore does not work for the moment to generate collisions with my peripheral walls.
// if (detectPlayerCollision() == false) {