将向量3D少量旋转

问题描述 投票:0回答:1

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

vector 3d rotation
1个回答
0
投票

您可以在您的方向(dir)定义的平面上计算offset向量,将其添加到dir,然后进行归一化以获取新方向。

如果您可以假设您的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也可以指向上方,则需要单独使用side来生成updir

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.