Unityでマウスの位置に画像(guiのimage)を表示させる
guiのimageを使ってマウスポインターの代わりに画像を表示させる
画像からアニメーションにも応用できるはず
用意するもの
・Windows PC
・Unity (制作時に使用したバージョンは2019)
・マウスの位置に表示させたい画像
作りたいもの
黒い丸がマウスポインタ—に追従している。
これはわかりやすくするためにマウスポインターを表示している。
作りたかた
1.HierarchyのプラスボタンからUI > ImageからCanvasとImageオブジェクトを作る。
2.Imageに入れる画像をTexture TypeをSprite(2D and UI)にし、ImageのSource Imageに入れる。
3.Imageのオブジェクト名を「MouseImage」に変更する。
4.HierarchyのプラスボタンからCreate Emptyで空のオブジェクトを作る、オブジェクト名を「MouseManager」に変更する。
5.下記のスクリプトをC#のファイルで作り、MouseManagerオブジェクトに入れる。
完成
スクリプト
MousePointerpos.C#
//画像publicImageMouse_Image;//Canvasの変数publicCanvascanvas;//キャンバス内のレクトトランスフォームpublicRectTransformcanvasRect;//マウスの位置の最終的な格納先publicVector2MousePos;// Start is called before the first frame updatevoidStart(){//マウスポインター非表示Cursor.visible=false;//HierarchyにあるCanvasオブジェクトを探してcanvasに入れいるcanvas=GameObject.Find("Canvas").GetComponent<Canvas>();//canvas内にあるRectTransformをcanvasRectに入れるcanvasRect=canvas.GetComponent<RectTransform>();//Canvas内にあるMouseImageを探してMouse_Imageに入れるMouse_Image=GameObject.Find("MouseImage").GetComponent<Image>();}// Update is called once per framevoidUpdate(){/*
* CanvasのRectTransform内にあるマウスの位置をRectTransformのローカルポジションに変換する
* canvas.worldCameraはカメラ
* 出力先はMousePos
*/RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect,Input.mousePosition,canvas.worldCamera,outMousePos);/*
* Mouse_Imageを表示する位置にMousePosを使う
*/Mouse_Image.GetComponent<RectTransform>().anchoredPosition=newVector2(MousePos.x,MousePos.y);}
参考文献
ぐーるらいふ 遊びのunityのメモ帳。敗北者の末路。
【Unity】タッチした位置にuGUI(RectTransform)を表示する
https://ghoul-life.hatenablog.com/entry/2018/11/13/000955
2020年5月30日閲覧
Unity DOCUMENTATION
RectTransformUtility .ScreenPointToLocalPointInRectangle
https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html
2020年5月30日閲覧