unity text实现鼠标光标
由于项目需求,需要在text上实现鼠标的cursor,并且随着点击位置cursor移动。实现方法:
1)新建一个光标的prefab(简单为之,直接在image中添加一个竖线spirte),增加脚本控制闪烁。
脚本如下:
public float cycleTime=0.2f; public Vector2 size =new Vector2(2,20); public Color oriColor = new Color(1, 1, 1, 1); public Color newColor = new Color(1, 1, 1, 0); // Use this for initialization void Start () { StartCoroutine(Shine()); } private void ShineAction(bool isColor) { gameObject.GetComponent<RectTransform>().sizeDelta= size; gameObject.GetComponent<Image>().color = isColor ? oriColor : newColor; } IEnumerator Shine() { while (true) { ShineAction(false); yield return new WaitForSeconds(cycleTime); ShineAction(true); yield return new WaitForSeconds(cycleTime); } }
2)获取text每个字符所在的位置(下代码中width即为每个字符对应的长度,characterInfo.advance为单个字符的长度)
public Text textComp; Font font = textComp.font;// Resources.Load<Font>("FZCQJW"); int fontsize = textComp.fontSize; string text = textComp.text; font.RequestCharactersInTexture(text, fontsize, FontStyle.Normal); CharacterInfo characterInfo; float width = 0f; for (int i = 0; i < text.Length; i++) { font.GetCharacterInfo(text[i], out characterInfo, fontsize); //width+=characterInfo.width; unity5.x提示此方法将来要废弃 width += characterInfo.advance; }
3)获取鼠标位置(获取鼠标位置为全局坐标系下的,需要通过transform.InverseTransformPoint(eventData.position)转化为text局部坐标系下数据),继承接口IPointerDownHandler实现其OnPointerDown方法,即可通过eventData.position获取当前点击位置
public void OnPointerDown(PointerEventData eventData) { }
完整代码如下:
public class RowToggleEvent : MonoBehaviour,IPointerDownHandler { public Text textComp; public GameObject cursor; private GameObject newCursor = null; public void OnPointerDown(PointerEventData eventData) { if (TransitData.cursor != null) Destroy(TransitData.cursor); Vector2 pointerDownPos = transform.InverseTransformPoint(eventData.position); Debug.Log(pointerDownPos); TransitData.cursor = Instantiate(cursor, gameObject.transform); float newCursorXpos = GetCursonXpos(pointerDownPos.x-50); Vector2 newCursorPos = new Vector2(newCursorXpos+50, -gameObject.GetComponent<RectTransform>().sizeDelta.y / 2); TransitData.cursor.GetComponent<RectTransform>().anchoredPosition = newCursorPos; Debug.Log(newCursorPos); } private float GetCursonXpos(float pointerDownXpos) { float xPos = 0; Font font = textComp.font;// Resources.Load<Font>("FZCQJW"); int fontsize = textComp.fontSize; string text = textComp.text; font.RequestCharactersInTexture(text, fontsize, FontStyle.Normal); CharacterInfo characterInfo; float width = 0f;
for (int i = 0; i < text.Length; i++) { font.GetCharacterInfo(text[i], out characterInfo, fontsize); width += characterInfo.advance;
if (pointerDownXpos <= width) { xPos = width; break; } else { if (i == text.Length - 1) xPos = width; } } return xPos; }