[转]Unity 3D旋转矢量方向及二维平面基于一点选择另一点(Rotate a Vector3 direction & Rotate a point about another point in 2D )

http://specialwolf.blog.163.com/blog/static/124466832201301332432766/

***********************************

极简单却又极坑的问题

以下代码用来实现: 已知某gameObject的方向, 由此得到此方向偏转某角度后的方向.

附: Transform.forward 和 Vector3.forward 不同.

Transform.forward是世界坐标系下物体的正方向,即编辑器中物体的蓝色轴。

Vector3.forward只不过是vector(0, 0, 1)的缩写

鄙视一下此类蛋疼的写法.

			
Vector3 dVector = playerObj.transform.forward;

Vector3 newVector;
				
if(i > maxCount/2)			
{				
     newVector = Quaternion.AngleAxis(-20*(maxCount -i), Vector3.up) * dVector;			
}			
else			
{				
     newVector = Quaternion.AngleAxis(20*i, Vector3.up) * dVector;			
}

  

附打印出来的几个 :

playerObj.transform.forward;

/*
正前 0 0 1
左30 -0.6 0 0.8
左 -1 0 0
左下 -0.6 0 -0.8
下 0 0 -1
*/

 ************************************

在使用Unity引擎时很多朋友都会遇到这样的问题,即关于方向(专业点说是矢量)的旋转问题。

Unity 3D旋转矢量方向及二维平面基于一点选择另一点(Rotate a Vector3 direction  Rotate a point about another point in 2D ) - Neo - 生命,本是修行

如左图中,很多朋友都会使用Vector3.forward来表示“前方”,具体到角色身上时就是transform.forward了,有时我们需要将该方向基于角色所在的位置旋转N度,对于新手、没有经过正规的游戏编程培训或数学不怎么好的朋友(这里其实说我自己),这里是有些恼人的,但在Unity官方论坛上有人给出了答案,我这里只是整理了一哈:

参考:http://answers.unity3d.com/questions/46770/rotate-a-vector3-direction.html

// 将角色或车轮向右旋转30度

Vector3 newVector = Quaternion.AngleAxis(30, Vector3.up) * Vector3.forward;

// 或者

Vector3 newVector = Quaternion.Euler(0,30,0) * Vector3.forward;

要注意的就是该运算是有顺序的,必须将四元数放在前面。

附带说明一下如何实现一个点围绕另外一个点旋转指定角度的问题(注意这里只是说明基于二维情况下的旋转),其实这纯粹是一个数学问题,只不过是如何在Unity中实现罢了。

可以先看一下解决思路:

http://www.siggraph.org/education/materials/HyperGraph/modeling/mod_tran/2drota.htm

这是高中的教材内容,可惜……

怎么用编程表示该内容呢?通用编程可以考虑这里:

http://stackoverflow.com/questions/2259476/rotating-a-point-about-another-point-2d

如果你也是使用Unity做为开发引擎,可以参考如下代码:如下代码是考虑基于Y轴旋转的,所以你可以将点(x,z)看做平面内的一个支点,angle表示要基于(x,z)点旋转的角度,point是要旋转的点,具体代码如下:

Vector3 RotatePoint(float x, float z, float angle, Vector3 point)

{

     // Translate point back to origin;

     Vector3 temp = new Vector3(point.x -= x, point.y, point.z -= z);

     // Roate the point

     float xNew = Mathf.Cos(angle * Mathf.Deg2Rad) * (point.x) - Mathf.Sin(angle * Mathf.Deg2Rad) * (point.z);

     float zNew = Mathf.Sin(angle * Mathf.Deg2Rad) * (point.x) + Mathf.Cos(angle * Mathf.Deg2Rad) * (point.z);

     temp.x = xNew + x;

     temp.z = zNew + z;

     return temp;

}

在三维空间中基于某点旋转特定角度可以参考:

http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html

http://blog.client9.com/2007/09/rotating-point-around-vector.html

 

Author : Neo

Date : 2013-01-13

Email : specialwolf.neo(at)gmail.com
原文地址:https://www.cnblogs.com/willbin/p/3446539.html