前言:
這篇文章是教你做一個在 RawImage 內的滑鼠 (鼠標),這是由上一篇文章改的 ( http://blog.csdn.net/weixin_38884324/article/details/79312392 ),想要知道更多細節可以參考上篇文章,就結果來說這篇改進了很多功能,例如:圖片移動,長寬改變,Anchors 或 Pivot 改變,都能正確顯示。
注意:另外這裡用 Texture2D 只是教學範例,不想搞得太複雜,實際應用中做好用 Shader來做,因為 Texture2D.Apply() 超慢 der 啦 ! 如何做可以參考以前我的文章 ( http://blog.csdn.net/weixin_38884324/article/details/79285371 ) ,我就不多說了,這是你們的回家作業,明天交。
如下圖,紅十字線將會跟著滑鼠 ( 鼠標 ) 移動:
就算圖片移動,長寬改變,Anchors 或 Pivot 改變,多重父物件,都能正確顯示。有沒有超強 ? 幹,超強大der 啦 !
第一步 C #:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class NewBehaviourScript : MonoBehaviour
{
public RawImage img;
public void OnMouseEnter ()
{
// 滑鼠進入圖片內先隱藏
Cursor.visible = false;
StartCoroutine ("OnMouseMoveInit");
}
public void OnMouseExit ()
{
// 滑鼠離開圖片外將顯示
Cursor.visible = true;
StopCoroutine ("OnMouseMoveInit");
}
IEnumerator OnMouseMoveInit ()
{
Vector3 mousePos = Vector3.zero;
while (Application.isPlaying) {
// 滑鼠有移動才執行
if (mousePos != (mousePos = Input.mousePosition)) {
// 加入圖片座標的應用,哈
RectTransform r = img.GetComponent <RectTransform> ();
float mouseImgX = mousePos.x - ((Screen.width - r.rect.width) / 2);
float mouseImgY = mousePos.y - ((Screen.height - r.rect.height) / 2);
// 如果圖片不再螢幕中心點,或發生位移,則要重新計算,如果你的圖片在螢幕中間的話,你也可以把這兩行刪掉
mouseImgX -= r.transform.position.x - (Screen.width / 2);
mouseImgY -= r.transform.position.y - (Screen.height / 2);
// 如果用戶調整了 Pivot 則需要重新計算,預設 0.5 如果你沒有調整,你其實可以把這兩行刪掉
mouseImgX += ((r.pivot.x-0.5f)*2) * (r.rect.width / 2);
mouseImgY += ((r.pivot.y-0.5f)*2) * (r.rect.height / 2);
//
OnMouseMove (mousePos.x, mousePos.y, mouseImgX, mouseImgY, r.rect.width, r.rect.height);
}
yield return new WaitForEndOfFrame ();
}
}
Texture2D t;
// 變成十字滑鼠 ( 鼠標 )
void OnMouseMove (float mouseScreenX, float mouseScreenY, float mouseImgX, float mouseImgY, float imgWidth, float imgHeight)
{
if(t !=null){
Destroy (t);
}
// 這裡用 Texture2D 只是教學範例,實際應用中做好用 Shader來做,因為 Texture2D.Apply() 超慢 der 啦 !
t = new Texture2D ((int)imgWidth, (int)imgHeight);
for(int y=0; y < t.height; y++){
for(int x=0; x < t.width; x++){
if (x == (int)mouseImgX || y == (int)mouseImgY) {
t.SetPixel (x, y, Color.red);
} else {
t.SetPixel (x, y, Color.white);
}
}
}
t.Apply ();
img.texture = t;
}
}
第二步:
- 創建一個 RawImage 的 UI 物件,然後把他加入 C# 的 img 變數中
- 記得在外面加入 Event Trigger
- 將 Pointer Enter 對印到 C# 的 OnMouseEnter ()
- 將 Pointer Exit 對印到 C# 的 OnMouseExit ()
寫在最後:
祝你們玩得開心,如果你們賺錢了記得分我一點。