我目前正在开发3D游戏,我想使用wasd键实现一种第一人称控制。
我下面的代码片段包括速度,位置和旋转,其中旋转表示0
和2*Math.PI
之间的值。
我的问题是如何更新我的代码,以使用w键基于当前旋转“直行”,而d键则无论我面对何处都返回,等等。
我相信您知道我的问题是什么-我需要某种方法来实现加速!
任何帮助将非常感激。
let speed = 0.01,
maxSpeed = 0.01,
friction = 0.91
let position = {
x: 0,
y: 0,
z: 0
},
velocity = {
x: 0,
y: 0,
z: 0
},
rotation = 0;
let update = () => {
if (keyPressed("w") && velocity.z > -maxSpeed) velocity.z -= speed
if (keyPressed("s") && velocity.z < maxSpeed) velocity.z += speed
if (keyPressed("a") && velocity.x > -maxSpeed) velocity.x -= speed
if (keyPressed("d") && velocity.x < maxSpeed) velocity.x += speed
velocity.z *= friction
velocity.x *= friction
position.z += velocity.z * Math.sin(rotation) // this is
position.x += velocity.x * Math.sin(rotation) // not working
}
最佳答案
这是固定版本:
position.z += velocity.z * Math.cos(rotation);
position.x += velocity.z * Math.sin(rotation);
position.z -= velocity.x * Math.sin(rotation);
position.x += velocity.x * Math.cos(rotation);
单击进入片段以转移焦点,然后使用
WSAD
键<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/104/three.min.js">
</script><script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75,innerWidth / innerHeight,0.01,1000);
camera.position.set(0, 3, 0);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
scene.add(new THREE.GridHelper(500, 100, 0x666666, 0x444444));
let speed = 0.1, maxSpeed = 0.1, friction = 0.91,
position = { x: 0, y: 0, z: 0 },
velocity = { x: 0, y: 0, z: 0 },
rotation = 0, keyPressed = {};
let update = () => {
if (keyPressed["w"] && velocity.z > -maxSpeed) velocity.z -= speed;
if (keyPressed["s"] && velocity.z < maxSpeed) velocity.z += speed;
if (keyPressed["a"] && velocity.x > -maxSpeed) velocity.x -= speed;
if (keyPressed["d"] && velocity.x < maxSpeed) velocity.x += speed;
velocity.z *= friction;
velocity.x *= friction;
position.z += velocity.z * Math.cos(rotation);
position.x += velocity.z * Math.sin(rotation);
position.z -= velocity.x * Math.sin(rotation);
position.x += velocity.x * Math.cos(rotation);
};
setInterval(update, 10);
requestAnimationFrame(render);
addEventListener('keydown', e => keyPressed[e.key] = true)
addEventListener('keyup', e => keyPressed[e.key] = false)
addEventListener('mousemove', e => rotation = e.x*Math.PI*2/innerWidth)
addEventListener('resize', e => renderer.setSize(innerWidth, innerHeight))
function render() {
camera.rotation.y = rotation;
camera.position.x = position.x;
camera.position.z = position.z;
requestAnimationFrame(render);
renderer.render(scene, camera);
}
</script>
<style>body,canvas{overflow:hidden;margin:0;}</style>
关于javascript - 第一人称WASD控件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57065027/