gpt4 book ai didi

canvas - 将 Canvas 2D 映射到 Three.js Canvas

转载 作者:行者123 更新时间:2023-12-02 02:54:03 35 4
gpt4 key购买 nike

我正在使用 Three.js 构建一个简单的 2D 游戏。我只使用世界的 X 和 Y 位置来移动对象,将它们的 z 位置保留为零。我使用禁用旋转的 TrackballControls,以允许使用右键单击和使用鼠标滚轮缩放来进行摄像机的 2D 移动。我现在需要为这个游戏实现 war 迷雾。 After looking around , I've found使用带有 2D 上下文的第二个 Canvas 是最方便的方法。

这带来的挑战是,2D Canvas 必须以与 3D Canvas 移动相同的速率平移和缩放,才能将雾放置在正确的项目上。我已经设法通过取消原点投影来完成平移,但我不确定如何准确地复制缩放。

    var widthHalf = this.width / 2, heightHalf = this.height / 2;

var origin = new THREE.Vector3();
var projector = new THREE.Projector();
origin = projector.projectVector(new THREE.Vector3(0, 0, 0), this.camera);
origin.x = (origin.x * widthHalf) + widthHalf;
origin.y = -(origin.y * heightHalf) + heightHalf;

canvas2D.save();
canvas2D.translate(origin.x, origin.y); //This works great

canvas2D.scale(???,???); //Map to the zoom/position of the Three.js camera?

//Do fog drawing here...

//A 1x1 Rectangle for Scale - Should Map to a 1x1 square of Three.js space
canvas2D.fillStyle = "#FF0000";
canvas2D.fillRect(0, 0, 1, 1);

canvas2D.restore();
<小时/>

问:如何将 Three.js 相机的距离映射到 Canvas 2D 的比例,以便它们以相同的速率缩放?

<小时/>

最佳答案

找到了解决方案。答案是做一些数学计算来确定 1x1 方形 Three.js 空间的屏幕大小,并使用它来缩放 Canvas 。

this.WorldtoPixel = function(worldPos)
{
var widthHalf = this.width / 2, heightHalf = this.height / 2;

var position = new THREE.Vector3();
var projector = new THREE.Projector();
position = projector.projectVector(worldPos, this.camera);
position.x = (position.x * widthHalf) + widthHalf;
position.y = -(position.y * heightHalf) + heightHalf;

return position;
}

var origin = this.WorldtoPixel(new THREE.Vector3(0, 0, 0));
var onezero = this.WorldtoPixel(new THREE.Vector3(1, 0, 0));
var zeroone = this.WorldtoPixel(new THREE.Vector3(0, 1, 0));

var scaleX = onezero.x - origin.x;
var scaleY = origin.y - zeroone.y;
fogContext.scale(scaleX, scaleY);

关于canvas - 将 Canvas 2D 映射到 Three.js Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20318756/

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