unity3d中的Quaternion.LookRotation

android开发范例中的第二个粒子,是摇杆操做游戏,模式相似于“迷你高尔”,僵尸包围类型的设计游戏。android

其中让我注意到这个函数的使用很是特别:Quaternion.LookRotationweb

游戏针对两个平台作了输入配置。c#

在pc平台上控制人物移动用正常的上下左右按键控制,然而人物的旋转就变成了鼠标位置。函数

正常状况咱们但愿东西可以根据指定目标方向移动其实用lookat这个函数就能够了。但这个地方用的方法原比lookat来的更加省事儿。测试

看看他是怎么得到这个角度的:url

1
2
3
4
5
6
7
8
9
10
//Find the center of the screen
             tempVector2 = new Vector3(Screen.width * 0.5f,0,Screen.height * 0.5f);
             //Get mouse position
             tempVector = Input.mousePosition;
             //Set tempVector z to tempVector.y
             tempVector.z = tempVector.y;
             //Set tempVector y to 0
             tempVector.y = 0;
             //Set lookDir to  tempVector - tempVector2
             lookDir = tempVector - tempVector2;

是的,先获得屏幕中央坐标,而后把鼠标坐标(因为是俯视类游戏,y轴坐标变为z轴)减去中央坐标,接着:spa

1
2
//Rotate player
         transform.rotation =     Quaternion.LookRotation(lookDir);

结束了,目标旋转了,并且经过测试,能够发现不管是不是俯视类游戏均可以正常旋转。回过头来想一想本身当初使用的方法:.net

1.得到鼠标位置,向地面发射射线。设计

2.将射线和地面的碰撞坐标记录。code

3.经过lookat旋转。

对于崎岖的山地个人方法彷佛就显得好笑了,呵呵。

Quaternion.LookRotation彷佛是用相似于向量的方法,在肯定圆心位置的状况下计算出相应位移所造成的角度。

有一位前辈的博客是这样描述的:http://blog.csdn.net/janpylx/article/details/7776465

事实上我看不懂,呵呵。

接着来看另外一处使用这个函数的地方,那就是在手机平台时使用摇杆,根据摇杆的方向旋转目标的方向。这里用的是官方提供的joystick脚本,js写的。看看它是如何获取并旋转的。

1
2
3
4
5
6
7
8
//Get right joystick x position
             float lX = rightJoystick.GetComponent<Joystick>().position.x;
             //Get right joystick y position
             float lY = rightJoystick.GetComponent<Joystick>().position.y;
//Set lookDir x to joystick x position and dir z joystick y position
                 lookDir = new Vector3(lX,0,lY);
//Rotate player
         transform.rotation = Quaternion.LookRotation(lookDir);

我本身一开始没有看明白,为何就是直接调用position的位置就能够旋转了,知道我看了joystick的代码:

1
2
3
// For a touchpad, let's just set the position directly based on distance from initial touchdown
                     position.x = Mathf.Clamp( ( touch.position.x - fingerDownPos.x ) / ( touchZone.width / 2 ), -1, 1 );
                     position.y = Mathf.Clamp( ( touch.position.y - fingerDownPos.y ) / ( touchZone.height / 2 ), -1, 1 );

是的,他用的是一样的原理,圆点坐标和当前坐标的差值。

因此关于Quaternion.LookRotation个人理解是旋转两个指定坐标间造成的夹角。

相关文章
相关标签/搜索