上面图片挂脚本,下面图片同名!!挂脚本的可以拉出线连接下面图片!!
连线时的样子
点击Button按钮后,错误的变红,正确的变绿
代码~~~~~~~
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.Events;
using System;
public class DrawLineUseImage : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler,IEndDragHandler
{
[Header("线宽度")]
public float lineWidth = 3f;
[Header("线颜色")]
public Color lineColor = Color.white;
public Button b;
bool isUP = true;
GameObject lineObj = null;
RectTransform lineObjRT = null;
Vector3 startPos = Vector3.zero;
Vector3 endPos = Vector3.zero;
GameObject GetObj;
void Start()
{
b.onClick.AddListener(delegate
{
Decide();
});
}
void DestoryAll()
{
for (int i = 0; i < transform.childCount; i++)
{
Destroy(transform.GetChild(i).gameObject);
}
}
Image lineObjImg;
public void OnPointerDown(PointerEventData eventData)
{
lineObj = new GameObject("LineObj");
lineObj.SetActive(false);
lineObjRT = lineObj.AddComponent<RectTransform>();
lineObjRT.pivot = new Vector2(0, 0.5f);
lineObjRT.localScale = Vector3.one;
lineObjImg = lineObj.AddComponent<Image>();
lineObjImg.color = lineColor;
lineObjImg.raycastTarget = false;
lineObjRT.SetParent(transform);
startPos = Input.mousePosition;
lineObjRT.position = startPos;
lineObjRT.sizeDelta = Vector2.zero;
lineObj.SetActive(true);
}
public void OnPointerUp(PointerEventData eventData)
{
if (eventData.pointerEnter!=null )
{
GetObj = eventData.pointerEnter;
}
if (eventData.pointerEnter == null)
{
DestroyImmediate(lineObjRT.gameObject);
}
}
void Decide()
{
if (GetObj != null)
{
if (GetObj.name == transform.name )
{
Debug.Log("回答正确");
lineObjImg.color = Color.green;
}
else
{
lineObjImg.color = Color.red;
Debug.Log("回答错误");
}
}
else
{
Debug.Log("回答错误");
// DestroyImmediate(lineObjRT.gameObject);
}
}
public void OnDrag(PointerEventData eventData)
{
endPos = Input.mousePosition;
Vector3 durationPos = endPos - startPos;
lineObjRT.sizeDelta = new Vector2(durationPos.magnitude, lineWidth);
float angle = Mathf.Atan2(durationPos.y, durationPos.x) * Mathf.Rad2Deg;
lineObjRT.localRotation = Quaternion.Euler(0, 0, angle);
isUP = true;
}
//如果线未连接答案,线消失后可再次拉出连线!
public void OnEndDrag(PointerEventData eventData)
{
if (eventData.pointerEnter.name!=transform.name)
{
transform.GetComponent<Image>().raycastTarget = false;
}
}
}