1

我刚刚开始学习 THREE,并且一直在搞乱可控制 MD2 角色的 three.js 示例,试图将其塑造成第三人称射击游戏。我一直在尝试为敌人角色编写一个简单的算法,我很确定光线投射会是理想的。整个想法是敌人一旦面对玩家就应该停止旋转。但这是让我彻夜难眠的问题!:

比方说,敌人物体是射线施法者射线的原点。无论我为该光线的方向设置什么方向(甚至,例如 (1,0,0) - 正 x 轴),光线的方向始终指向场景的中心!!!

请帮忙!无法在网上找到任何用于光线投射器的示例(除了我目前真的不需要的碰撞检测)。

4

1 回答 1

1

If all you want is for enemies to stop rotating when they are looking at the player, I would consider just checking the direction between them, as it's a lot faster than casting a ray to see if it intersects:

// Assuming `enemy` is a THREE.Mesh
var targetDir = enemy.position.clone().sub(player.position).normalize();
var currentDir = (new THREE.Vector3()).applyMatrix4(enemy.matrixWorld).sub(enemy.position).normalize();
var amountToRotate = currentDir.sub(targetDir);
var offset = amountToRotate.length();

Then rotate each axis no more than the value for that axis in amountToRotate if offset is greater than some threshold.

That said, here is how you use a Raycaster, given the variables above:

var raycaster = new THREE.Raycaster(enemy.position, targetDir);
var intersections = raycaster.intersectObject(player);

Note that if you are running any of the above code in an animation loop, it will create a lot of garbage collection churn because you are constantly creating a bunch of new objects and then immediately throwing them away. A better pattern, which is used a lot in the library itself, is to initialize objects once, copy values to them if you need to, and then use those copies for computation. For example, you could create a function to do your raycasting for you like this:

var isEnemyLookingAtPlayer = (function() {
  var raycaster = new THREE.Raycaster();
  var pos = new THREE.Vector3();
  return function(enemy) {
    raycaster.ray.origin.copy(enemy.position);
    raycaster.ray.direction.copy(pos.copy(enemy.position).sub(player.position).normalize());
    return !!raycaster.intersectObject(player).length;
  };
})();
于 2013-09-06T05:27:02.063 回答