1-7 Using Cursor Affordances
今天要來介紹替Cursor換圖示,當鼠標移動到敵人物件時,要顯示攻擊用的圖示;移動到一般的地形,要顯示移動的圖示。但為什麼我們要修改鼠標圖示呢?
在此引用維基百科(Wikipedia)一段針對Affordance的解釋:
環境賦使(affordance),或稱為直觀功能、預設用途、可操作暗示、支應性、示能性等,指一件物品實際上用來做何用途,或被認為有什麼用途。也就是說在物品的某個方面,具有讓人明顯知道該如何使用它的特性。例如門提供「打開」的功能,椅子提供「支撐」的功能。
首先,匯入三種鼠標的圖檔。我不會提供這三種圖檔,所以請你自己準備喜歡的吧。
接著選取三個鼠標圖檔,將Texture Type改成Cursor。
此時,就會發現圖示有部分自動去背了。此時三個圖檔可用作鼠標使用。
Target是戰鬥鼠標,Unkown是未知領域鼠標,Walk是移動鼠標。
接著,我們將專案裡已經寫好的Cursor文件,更名為CursorAffordance。
註:如不知道Cursor文件從何而來,請參考網誌文章1-4 Using Raycasts To Query Click
https://rpgcorecombat.blogspot.tw/2017/12/1-4-using-raycasts-to-query-click.html
CursorAffordance程式碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CursorAffordance : MonoBehaviour {
[SerializeField] Texture2D walkCursor = null;
[SerializeField] Texture2D targetCursor = null;
[SerializeField] Texture2D unknownCursor = null;
[SerializeField] Vector2 cursorHotspot = new Vector2 (0, 0);
CameraRaycaster cameraRaycaster;
void Start () {
//取得Camera Arm中的Camera Raycaster,因為CursorAffordance.cs也是放在Camera Arm之下,故可以直接用GetComponent取得。
cameraRaycaster = GetComponent ();
}
void Update () {
//於Console中顯示滑鼠點擊到的Layer
//print (cameraRaycaster.layerHit);
switch (cameraRaycaster.layerHit) {
case Layer.Enemy:
Cursor.SetCursor(targetCursor, cursorHotspot, CursorMode.Auto);
break;
case Layer.Walkable:
Cursor.SetCursor (walkCursor, cursorHotspot, CursorMode.Auto);
break;
case Layer.RaycastEndStop:
Cursor.SetCursor(unknownCursor, cursorHotspot, CursorMode.Auto);
break;
default:
Debug.LogError ("Don't know what cursor to show.");
break;
}
}
}
When setting a cursor you can specify if you want the cursor to be a hardware cursor or a software cursor. If you use a hardware cursor then rendering will be handled by the OS, otherwise Unity will render the cursor for you after everything else in the scene has been rendered.
https://blogs.unity3d.com/2012/10/22/cursor-api/
簡言之,選擇Hardware Cursor由系統控制鼠標的移動與繪製,操作速度較快不會Delay。若選擇Software Cursor則由Unity繪製,速度較慢。何時會使用到Software Cursor呢?Windows內建的鼠標有大小限制32x32,若你希望鼠標要更大,就得使用Software Cursor。
接著,將鼠標的圖檔拖曳到Cursor Affordance的變數欄位中。Cursor Hotspot是指鼠標的點擊錨點,我設置0,0的話,點擊區就會在圖檔的最左上角。如果你想設置在中間,就將你的圖檔長寬各除以2。
所以,我只好設定圖檔的大小了。我在圖檔的Inspector裡面設定Max Size為32,這樣看起來就正常多了。







留言
張貼留言