Hello,我是KitStar。
代码虽然少,但是核心的知识点就是世界坐标、相机坐标和局部坐标的转换也就是下面的这个函数
以下文章整理的不对。还请见谅。
本章的需求很简单,就是“通过在屏幕中点击鼠标,在2d视图中控制物体进行移动”。在别的平台和引擎中简直是Hello world级别的需求在Unity3d中却变得有些棘手了,主要有几个问题困扰着我,
1、IO输入是怎么样的;
2、鼠标事件是如何接收的;
3、移动动画是如何实现的;
“原理很简单,现实很残酷”,Unity3d的开放性造成了所谓的插件和库很多,显得凌乱。这里还是按照自己的惯性思维来了,按照别的平台的教程,
A、首先要有一个容器,
B、在容器上放置需要移动的精灵,
C、通过容器接收鼠标事件,
D、事件驱动精灵移动
这里UGui中采用容器的概念(或者我还不知道别的库也有),所以先在UGui中实现,
第一步,加一个Panel对象
第二步,导入一个精灵的图片资源
第三步,加一个2d的Image对象,设置其sprite为刚才导入的图片资源
第四步,给Panel对象绑定一个脚本,PanelController,
树结构
加图资源后
绑定代码
具体代码如下:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class PanelController: MonoBehaviour , IPointerClickHandler
{
private Transform childPlayTransform;
private Transform parentCanvasTransform;
// Use this for initialization
void Start ()
{
//获得Image的Transform
childPlayTransform = transform.Find("Image");
parentCanvasTransform = transform.parent;
}
// Update is called once per frame
void Update () {
}
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log(string.Format("x:{0},y:{1}", eventData.position.x, eventData.position.y));
Debug.Log(string.Format("button x:{0},y:{1}", childPlayTransform.localPosition.x, childPlayTransform.localPosition.y));
Vector2 localPoint;
//在矩形范围内检测,全局鼠标点击点,到local点的转换
RectTransformUtility.ScreenPointToLocalPointInRectangle(transform as RectTransform, eventData.position,
eventData.enterEventCamera, out localPoint);
childPlayTransform.localPosition = localPoint;
}
}
代码虽然少,但是核心的知识点就是世界坐标、相机坐标和局部坐标的转换也就是下面的这个函数
//
// 摘要:
// Does the RectTransform contain the screen point as seen from the given camera?
//
// 参数:
// rect:
// The RectTransform to test with.
//
// screenPoint:
// The screen point to test.
//
// cam:
// The camera from which the test is performed from.
//
// 返回结果:
// True if the point is inside the rectangle.
public static bool RectangleContainsScreenPoint(RectTransform rect, Vector2 screenPoint, Camera cam);
public static bool ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint);