2d旋转的应用
1 :条件1 (已知) 创建一个平面直角坐标系 左上角为(0,0),能够把一个加入了UIPanel组件的物体(名字叫Father)移至UIRoot左上角 Y和Z轴都旋转180度。这样你移动随便一个物体为Father的子物体到左上角 ,你会观察到子物体的坐标是(0,0,0)
条件2(已知) 物体当前运动点currentPosition 物体下一个运动点nextPosition 的位置(物体运动的点能够有N个)运动的路径能够为不论什么类型的线 直线 曲线都OK
求:让物体的方向始终对着下一个点,就是获得物体的旋转方向
以下是答案的代码
if (currentPosition.x - nextPosition.x != 0) { angle = Mathf.Rad2Deg * Mathf.Atan((currentPosition.y - nextPosition.y) / (currentPosition.x - nextPosition.x)); } else { angle = 0; } if (nextPosition.x >= currentPosition.x && nextPosition.y <= currentPosition.y) { nowAngle = 360f - angle;//1 } else if (nextPosition.x >= currentPosition.x && nextPosition.y >= currentPosition.y) { nowAngle = 90f - angle + 90f + 180f;//2 // print(angle); } else if (nextPosition.x <= currentPosition.x && nextPosition.y >= currentPosition.y) { nowAngle = 180f - angle; } else if (nextPosition.x <= currentPosition.x && nextPosition.y <= currentPosition.y) { nowAngle = 180f + (90f - angle) + 90f + 180f; } transform.rotation = Quaternion.Euler(new Vector3(0, 0, nowAngle));
代码原理
下图是整个界面的布置 曲线部分仅仅是当中的一条路径 只是能够通用(即能代表不同出发点的曲线)
再看以下的图(大家能够拿起笔画一画,把上图曲线中不同一时候刻的当前点和下一个点做一个连线,然后再把每个当前点放到以下图中的原点。下一个点依照连的线的方向放入以下图中的圆)
你是不是发现这样我就能把当前点和下一个点放到上图的坐标系中。然后依据切线获得角度了。
是不是非常有用的2D游戏算法呢
不谢 勿喷
欢迎进我的技术q群479853988一起装逼啊 。都是装逼界的等什么呢...