threejs三种坐标(世界坐标,局部坐标,屏幕坐标)转换

三种坐标

  • 世界坐标转换(World Coordinate System):世界坐标是指对象相对于场景的位置。即物体在web3d中的位置
  • 局部坐标转换(Local Coordinate System):局部坐标是指对象相对于其父级对象的位置。
  • 屏幕坐标转换(Screen Coordinate System):屏幕坐标是指对象在屏幕上的位置。

转换代码

  • 当你需要将一个对象从世界坐标系转换到局部坐标系时,可以使用worldToLocal()方法。示例代码如下:
var worldPosition = new THREE.Vector3(); // 世界坐标
var localPosition = new THREE.Vector3(); // 局部坐标

// 将世界坐标转换为局部坐标
object.worldToLocal(worldPosition, localPosition);

  • 当你需要将一个对象从局部坐标系转换到世界坐标系时,可以使用localToWorld()方法。示例代码如下:
var localPosition = new THREE.Vector3(); // 局部坐标
var worldPosition = new THREE.Vector3(); // 世界坐标

// 将局部坐标转换为世界坐标
object.localToWorld(localPosition, worldPosition);

  • 当你需要将一个对象的屏幕坐标转换为三维场景中的坐标时,可以使用project()方法。示例代码如下:
var screenPosition = new THREE.Vector3(); // 屏幕坐标
var worldPosition = new THREE.Vector3(); // 世界坐标

// 将屏幕坐标转换为世界坐标
screenPosition.x = (screenPosition.x / window.innerWidth) * 2 - 1;
screenPosition.y = -(screenPosition.y / window.innerHeight) * 2 + 1;
screenPosition.z = 0.5; // 需要设置一个深度值,通常为0.5

screenPosition.unproject(camera); // 将屏幕坐标反投影到世界坐标
screenPosition.sub(camera.position).normalize(); // 获取方向向量
var distance = -camera.position.z / screenPosition.z; // 计算距离
worldPosition.copy(camera.position).add(screenPosition.multiplyScalar(distance)); // 计算世界坐标

应用示例:获取点击到的三维坐标图形,将其转化为屏幕坐标,获取其屏幕坐标的x,y值

//计算鼠标在屏幕上上的位置
const mouse = new THREE.Vector2();
	mouse.x = ((event.clientX - container.getBoundingClientRect().left) / container.offsetWidth) * 2 - 1;
	mouse.y = -((event.clientY - container.getBoundingClientRect().top) / container.offsetHeight) * 2 + 1;
	 // 创建一个射线投射器
const raycaster = new THREE.Raycaster();
	raycaster.setFromCamera(mouse, camera);
	 // 检测与射线相交的物体
	const intersects = raycaster.intersectObject(scene);
	// 获取物体的世界坐标
	const centerX = container.clientWidth / 2;
	const centerY = container.clientHeight / 2;
	const worldVector = new THREE.Vector3(
		intersects .position.x,
		intersects .position.y,
		intersects .position.z
	);
	//转化为屏幕坐标
	const standardVec = worldVector.project(camera);
	const screenX = Math.round(centerX * standardVec.x + centerX);
	const screenY = Math.round(-centerY * standardVec.y + centerY);
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

国服第三切图仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值