Unity实现绕任意轴任意角度旋转向量
程序员文章站
2023-02-20 20:11:24
本文实例为大家分享了unity实现绕任意轴任意角度旋转向量的具体代码,供大家参考,具体内容如下
游戏中有一需求,就是一个矩形或者cube绕着某一点旋转任意角度,现在给出下面算法。...
本文实例为大家分享了unity实现绕任意轴任意角度旋转向量的具体代码,供大家参考,具体内容如下
游戏中有一需求,就是一个矩形或者cube绕着某一点旋转任意角度,现在给出下面算法。
public static vector3 rotateround(vector3 position, vector3 center, vector3 axis, float angle) { vector3 point = quaternion.angleaxis(angle, axis) * (position - center); vector3 resultvec3 = center + point; return resultvec3; }
测试用例
using unityengine; using system.collections; public class rotatetest : monobehaviour { public linerenderer line1; public linerenderer line2; public float angle = 30f; private vector3 v0; private vector3 v1; private vector3 v2; private vector3 v3; private vector3 v4; private vector3 vcenter; void start() { v0 = new vector3(3f,0f,1f); v1 = new vector3(1f, 0f, 3f); v2 = new vector3(4f, 0f, 6f); v3 = new vector3(6f, 0f, 4f); vcenter = new vector3(2f, 0f, 2f); } // use this for initialization void update () { line1.setvertexcount(5); line1.setposition(0,v0); line1.setposition(1,v1); line1.setposition(2,v2); line1.setposition(3,v3); line1.setposition(4,v0); line2.setvertexcount(5); vector3 v01 = mathutils.rotateround(v0, vcenter, vector3.up, angle); vector3 v11 = mathutils.rotateround(v1, vcenter, vector3.up, angle); vector3 v21 = mathutils.rotateround(v2, vcenter, vector3.up, angle); vector3 v31 = mathutils.rotateround(v3, vcenter, vector3.up, angle); vector3 v41 = mathutils.rotateround(v4, vcenter, vector3.up, angle); line2.setposition(0, v01); line2.setposition(1, v11); line2.setposition(2, v21); line2.setposition(3, v31); line2.setposition(4, v01); } }
效果图
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。