Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9309

Unityでマウスの位置に画像(guiのimage)を表示させる

$
0
0

Unityでマウスの位置に画像(guiのimage)を表示させる

guiのimageを使ってマウスポインターの代わりに画像を表示させる

画像からアニメーションにも応用できるはず

用意するもの

・Windows PC
・Unity (制作時に使用したバージョンは2019)
・マウスの位置に表示させたい画像

作りたいもの

Rec_20181224_181408_20200530_175000.gif
黒い丸がマウスポインタ—に追従している。
これはわかりやすくするためにマウスポインターを表示している。

作りたかた

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オブジェクトに入れる。
完成

image.PNG
manager.PNG

スクリプト

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日閲覧


Viewing all articles
Browse latest Browse all 9309

Trending Articles