vector - 将 Vector 3D 旋转少量
问题描述
所以我有一个 3d 矢量(Javascript + Three.js,但这并不重要,因为这不依赖于语言),我想在随机方向上将它旋转少量。背景是,我想在 3d 射击游戏中散布随机武器,所以我有一个玩家瞄准的矢量,但需要在随机方向上稍微旋转一个最大角度。
解决方案
您可以在方向 ( )定义的平面中计算偏移矢量,将其添加到然后归一化以获得新方向。dir
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
和up
使用。dir
希望这可以帮助。
推荐阅读
- d3.js - 使用比例查找最近的关键帧
- xaml - 如何将 Xamarin.Forms XAML UI 页面转换为 PDF 文件?
- python - 尝试将来自两个不同 csv 文件的列合并到 python 中的一个列表中
- facebook-graph-api - 我无法使用 facebook graph api v3.0 获取封面
- java - Java,带有python模块(numpy)的python脚本的ProcessBuilder
- windows - Phonegap条码插件只有一种格式
- c - 从文件中读取不存在的数字 - C
- python - Python / Flask / Ajax:从客户端向服务器发送字典键
- opencv - 如何获取 Hi3536 Mali GPU 的 openCL 库
- django - 基于条件的Django模板迭代/循环计数