我正在尝试用Javascript制作游戏,但目前我已达到停滞状态。我正在尝试检测按键并检查它们是否经常停机以移动角色。这是我正在使用的代码:
var THREE;
var keys;
var update;
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer();
var player_fov = 45;
var player_aspect = window.innerWidth / window.innerHeight;
var player_near = 0.1;
var player_far = 10000;
var player_camera = new THREE.PerspectiveCamera(player_fov, player_aspect, player_near, player_far);
var player_material = new THREE.MeshNormalMaterial({color: 0xd0bd4b});
var player_geometry = new THREE.BoxGeometry(1,1,1,1);
var player = new THREE.Mesh(player_geometry, player_material);
function INIT()
{
scene.add(player);
player_camera.position.z = 5;
window.addEventListener('keydown', function (e) {
keys.keys = (keys.keys || []);
keys.keys[e.keyCode] = true;
});
window.addEventListener('keyup', function (e){
keys.keys[e.keyCode] = false;
});
requestAnimationFrame(INIT);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, player_camera);
if(keys.keys && keys.keys[87]) //w
{
player.position.y += 1;
}
if(keys.keys && keys.keys[65]) //a
{
player.position.x -= 1;
}
if(keys.keys && keys.keys[83]) //s
{
player.position.y -= 1;
}
if(keys.keys && keys.keys[68]) //d
{
player.position.x += 1;
}
}
当我按任意键时,这不起作用。找一个更好的程序员应该是一个相当容易的错误。是对eventListeners或requestAnimationFrame的理解不好吗?如果是,请告诉我如何解决它。感谢。
答案 0 :(得分:0)
我在代码中看到了一些需要改进的地方:
requestAnimationFrame
。那里有很多代码,不必每帧都运行。function render(){...}
。渲染函数应该具有requestAnimationFrame(render)
这些事情是我认为最紧迫的事情。以下是一个工作示例。
var keys = {};
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer();
var player_fov = 45;
var player_aspect = window.innerWidth / window.innerHeight;
var player_near = 0.1;
var player_far = 10000;
var player_camera = new THREE.PerspectiveCamera(player_fov, player_aspect, player_near, player_far);
var player_material = new THREE.MeshNormalMaterial({color: 0xd0bd4b});
var player_geometry = new THREE.BoxGeometry(1,1,1,1);
var player = new THREE.Mesh(player_geometry, player_material);
INIT();
function INIT()
{
document.addEventListener('keydown', function (e) {
keys = (keys || {});
keys[e.keyCode] = true;
});
document.addEventListener('keyup', function (e){
keys[e.keyCode] = false;
});
scene.add(player);
player_camera.position.z = 5;
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
render();
}
function render(){
requestAnimationFrame(render);
if(keys && keys[87]) //w
{
player.position.y += 0.2;
}
if(keys && keys[65]) //a
{
player.position.x -= 0.2;
}
if(keys && keys[83]) //s
{
player.position.y -= 0.2;
}
if(keys && keys[68]) //d
{
player.position.x += 0.2;
}
renderer.render(scene, player_camera);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r75/three.min.js"></script>