今天看了下UGUI的教程,实在太棒了。不过学了个囫囵吞枣。事件处理源码啥的都没心思看下去。具体总结下今天学的:
1.锚点和中心点问题:简单点说就是,锚点四个花瓣在一个点时,中心点的坐标;不在一个点时,中心点和花瓣所组成边框的距离
2.点击事件处理,button可以在OnClick,添加方法。Image等组件可以在EventTrigger设置。也可通过编写类实现以下接口实现。
using UnityEngine.EventSystem
IPointEnterHandler,IPointExitHandler,IPointDownHandler,IPointUpHandler,IPointClickHandler,IDragHandler
IDropHandler,IScrollHandler,IUpdateSelectedHandler,ISelectHandler,IDeselectHandler,IMoveHandler
简单的写了一个鼠标拖动图片的小脚本:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class drag:BeHaviour,IDragHandler,IDropHandler{
private RectTransform rt;
public RectTransform canvas;
Vector2 firstpos=new Vector2();
private bool isfirst=true;
void Start()
{
rt=transform as RectTransform;
}
public void OnDrag(PointsDates eventData)
{
Vector2 mousepos = eventData.position;
Vector2 uguipos = new Vector2();
bool isrect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,mousepos,eventData.enterEventCamera,out uguipos);
if(isfirst)
{
isfirst=false;
RectTransformUtility.ScreenPointToLocalPointRectangle(rt,mousepos,eventData.enterEventCamera,out firstpos);
}
if (isrect)
{
//rt.pivot = uguipos;
rt.anchoredPosition = uguipos-firstpos;
}
}
void Update () {
}
public void OnDrop(PointerEventData eventData)
{
isfirst = true;
}
}
3.点击按钮显示背包等界面
public void onBtClick()
{
RectTransform package = Instantiate(packageclone);//生成界面
package.SetParent(this.transform.parent);//改变parent
package.position = new Vector3(0, 0, 0);
package.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
package.localScale = new Vector3(1, 1, 1);
package.anchoredPosition = new Vector2(0, 0);//初始化大小、位置、旋转、在画布的位置等。
}
4、最难的拖拽功能,看的迷迷糊糊的,没练习。
抓取物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class dragItem : MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler {
// Use this for initialization
public dragPanelitem dragItempanel;
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnDrag(PointerEventData eventData)
{
if (dragItempanel != null)
{
dragItempanel.move(eventData);//移动物体
}
}
public void OnBeginDrag(PointerEventData eventData)
{
if (dragItempanel != null)
{
dragItempanel.hideItem();//将Image隐藏
}
}
public void OnEndDrag(PointerEventData eventData)
{
if (dragItempanel != null)
{
dragItempanel.setDragItemID(1);//获取抓取的物体
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
好好学习,天天向上。有志同道合的朋友可以关注下。共同进步