我有一个简单的2D游戏,我用Three.js构建。我只使用世界的X和Y位置移动物体,使其z位置为零。我使用带旋转禁用功能的TrackballControls,使用鼠标滚轮右键单击和缩放,允许相机进行2D移动。我现在需要为这场比赛实施战争迷雾。使用带有2D上下文的第二个画布的After looking around,I've found是最方便的方法。
这带来的挑战是Canvas 2D必须以与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的比例,以便它们以相同的速率进行缩放?
答案 0 :(得分:1)
找到解决方案。答案是做一些数学运算来确定1x1平方的Three.js空间的屏幕尺寸,并使用它来缩放画布。
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);