gpt4 book ai didi

javascript - Three.js 项目,在自上而下 View 中保持相机位于对象中心

转载 作者:行者123 更新时间:2023-12-03 00:40:51 26 4
gpt4 key购买 nike

我正在使用 Three.js 编写一个自上而下的游戏,具有单方 block 运动,如 Frogger 或其他经典街机游戏。当主 Angular 移动时,我很难将相机保持在主 Angular 的中心。现在我使用 MapControls.js 作为关键控件,但是平移会将相机移动一定数量的像素,并且 Angular 色通过在 zz 中设置其位置 +-10 来移动code> 或 x 方向,并且它们并不总是匹配,因此当您沿一个方向到达板的末端时, Angular 色几乎离开屏幕并且相机已经移动太远。我可以以某种方式连接相机向下看 y 轴,同时仍然保持移动效果吗?

最佳答案

为什么不直接将玩家的 x 和 z 复制到相机的 x 和 z 呢?或者,每帧复制一部分。

 camera.position.lerp(player.position, 0.03);

示例。运行它,单击它,然后使用箭头键

'use strict';

/* global THREE */

function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas: canvas});

const fov = 45;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 100;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
// make the camera look down
camera.position.set(0, 10, 0);
camera.up.set(0, 0, -1);
camera.lookAt(0, 0, 0);

const scene = new THREE.Scene();
scene.background = new THREE.Color('black');

scene.add(new THREE.GridHelper(40, 40));

let player;
{
const cubeSize = 1;
const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize);
const cubeMat = new THREE.MeshBasicMaterial({color: 'red'});
player = new THREE.Mesh(cubeGeo, cubeMat);
player.position.set(.5, .5, .5);
scene.add(player);
}

function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}

function render() {

if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}

camera.position.lerp(player.position, 0.03);
camera.position.y = 10; // keep the elevation;

renderer.render(scene, camera);

requestAnimationFrame(render);
}

requestAnimationFrame(render);

window.addEventListener('keydown', (e) => {
e.preventDefault();
switch (e.keyCode) {
case 38: // up
player.position.z -= 1;
break;
case 40: // down
player.position.z += 1;
break;
case 37: // left
player.position.x -= 1;
break;
case 39: // right
player.position.x += 1;
break;
}
});
}

main();
html, body {
margin: 0;
height: 100%;
}
#c {
width: 100%;
height: 100%;
display: block;
}
<canvas id="c"></canvas>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r98/three.min.js"></script>

将 0.03 增大到一个较大的数字,以使相机追得更快。

关于javascript - Three.js 项目,在自上而下 View 中保持相机位于对象中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53473529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com