多语言展示
当前在线:965今日阅读:23今日分享:31

Unity 实用教程 之 2D中UI随鼠标旋转朝向鼠标

Unity 实用教程 之 2D中UI随鼠标旋转朝向鼠标。本节介绍,2D游戏开发中,UI物体跟随鼠标旋转,始终朝向鼠标的简单案例,具体如下
工具/原料
1

Unity

2

UGUI

知识要点
1

RectTransformUtility.ScreenPointToWorldPointInRectangle:1)函数public static bool ScreenPointToWorldPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector3worldPoint);2)参数解释rect:The RectTransform to find a point inside.cam:The camera associated with the screen space position.screenPoint:Screen space position.worldPoint:Point in world space.3)返回值bool Returns true if the plane of the RectTransform is hit, regardless of whether the point is inside the rectangle.4)功能简述Transform a screen space point to a position in world space that is on the plane of the given RectTransform.The cam parameter should be the camera associated with the screen point. For a RectTransform in a Canvas set to Screen Space - Overlay mode, the cam parameter should be nullWhen ScreenPointToWorldPointInRectangle is used from within an event handler that provides a PointerEventData object, the correct camera can be obtained by using PointerEventData.enterEventData (for hover functionality) orPointerEventData.pressEventCamera (for click functionality). This will automatically use the correct camera (or null) for the given event.

2

Vector3.Angle:1)函数public static float Angle(Vector3 from, Vector3 to);2)参数解释from :The vector from which the angular difference is measured.to :The vector to which the angular difference is measured.3)功能简述Returns the angle in degrees between from and to.The angle returned is the unsigned acute angle between the two vectors. This means the smaller of the two possible angles between the two vectors is used. The result is never greater than 180 degrees.

Unity 实用教程 之 2D中UI随鼠标旋转朝向鼠标
1

打开Unity,新建一个空工程,具体如下图

2

在场景中添加Image,适当调整好位置,具体如下图

3

把Canvas的Render Mode 设置为 “Screen Space - Camera”,把主摄像机赋给Canvas的Render Camera,具体如下图

4

在Image上新建添加脚本“FollowMouse”,具体如下图

5

编辑脚本“FollowMouse”,首先设置是旋转物体哪个Canvas的,然后通过“RectTransformUtility.ScreenPointToWorldPointInRectangle”进行坐标转换(注意:当canvas的“Render Mode”没有修改,为“Screen Space - Overlay”时,参数摄像机值为null空),判断鼠标的位置,接着“Vector3.Angle”确定旋转角度,最后,把旋转角通过四元数转换个旋转物体,具体代码和代码说明如下图

6

旋转角度正负(逆时针旋转为正)确定具体参见下图

7

脚本编译正确,回到Unity界面,把“Canvas”赋给脚本,具体如下图

8

运行场景,移动鼠标,看可以看见物体“Image”跟着鼠标旋转,具体如下图

9

到此,《Unity 实用教程 之 2D中UI随鼠标旋转朝向鼠标》讲解结束,谢谢

注意事项
1

在代码中限制旋转角度,可以旋转前添加代码: z = Mathf.Clamp(z, -90, 90);

2

当物体不是UI,而是直接精灵图时,注意把精灵图的z轴值为0,,不然旋转会有问题

3

For a RectTransform in a Canvas set to Screen Space - Overlay mode, the cam parameter should be null

4

您的支持,是我们不断坚持知识分享的动力,若帮到您,还请帮忙投票有得;若有疑问,请留言

推荐信息