首页 > 解决方案 > 将 Vector 3D 旋转少量

问题描述

所以我有一个 3d 矢量(Javascript + Three.js,但这并不重要,因为这不依赖于语言),我想在随机方向上将它旋转少量。背景是,我想在 3d 射击游戏中散布随机武器,所以我有一个玩家瞄准的矢量,但需要在随机方向上稍微旋转一个最大角度。

标签: vector3drotation

解决方案


您可以在方向 ( )定义的平面中计算偏移矢量,将其添加到然后归一化以获得新方向。dirdir

如果你可以假设你的dir向量永远不会指向(假设y-up),你可以做这样的事情(一些功能是虚构的):

var yAxis = new THREE.Vector3(0.0, 1.0, 0.0);

var dir = new THREE.Vector3(...);
dir.normalize();

// Vectors defining the plane orthogonal to 'dir'.
var side = new THREE.Vector3();
var up = new THREE.Vector3();

// This will give a vector orthogonal to 'dir' and 'yAxis'.
side.crossVectors(dir, yAxis);
side.normalize();

// This will give a vector orthogonal both to 'dir' and 'side'.
// This represents the up direction with respect of 'dir'.
up.crossVectors(side, dir);
up.normalize();

// Maximum displacement angle.
var angle = rad(45.0);

// Create a random 2d vector representing the offset in the plane orthogonal
// to 'dir'.
// Alternatively you can draw a random angle 0/2pi and compute sin/cos.
var delta = new THREE.Vector2(rand(-1.0, 1.0), rand(-1.0, 1.0));
delta.normalize();
delta.multiplyScalar(Math.tan(angle));

// 'side' and 'up' define a plane orthogonal to 'dir', so here we're creating
// the 3d version of the offset vector.
side.multiplyScalar(delta.x);
up.multiplyScalar(delta.y);

// Define the new direction by offsetting 'dir' with the 2 vectors in the
// side/up plane.
var newDir = new THREE.Vector3(dir.x, dir.y, dir.z);
newDir.add(side);
newDir.add(up);
newDir.normalize();

// Just check that the angle between 'dir' and 'newDir' is the same as the
// chosen one.
console.log(Math.acos(dir.dot(newDir)) / Math.PI * 180.0);

如果dir还可以点起来,那么你需要单独生成sideup使用。dir

希望这可以帮助。


推荐阅读