Last active
December 30, 2015 13:39
-
-
Save burtlo/7837264 to your computer and use it in GitHub Desktop.
Exploring some C# in Unity. Reading through and implementing one of the recipes found in Unity 4.x Cookbook, http://www.packtpub.com/unity-4-x-cookbook/book.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
public class CursorScript : MonoBehaviour { | |
public Texture2D iconArrow; | |
public Vector2 arrowRegPoint; | |
public Texture2D iconZoom; | |
public Vector2 zoomRegPoint; | |
public Texture2D iconTarget; | |
public Vector2 targetRegPoint; | |
private Vector2 mouseReg; | |
private delegate bool WhenActionPerformed(); | |
private delegate void ExecuteThisAction(); | |
private Dictionary<WhenActionPerformed,ExecuteThisAction> actions; | |
void Start () { | |
setCursorToArrow(); | |
guiTexture.enabled = true; | |
actions = new Dictionary<WhenActionPerformed,ExecuteThisAction>(); | |
addAction( | |
whenThisIsTrue: () => { return Input.GetKey(KeyCode.RightShift) || Input.GetKey(KeyCode.LeftShift); }, | |
performAction: () => setCursorToTarget() | |
); | |
addAction( | |
whenThisIsTrue: () => { return Input.GetMouseButton(1); }, | |
performAction: () => setCursorToZoom() | |
); | |
// This is the fallback action which will always be true | |
addAction( | |
whenThisIsTrue: () => { return true; }, | |
performAction: () => setCursorToArrow() | |
); | |
} | |
void Update () { | |
Vector2 mouseCoord = Input.mousePosition; | |
Texture mouseTex = guiTexture.texture; | |
guiTexture.pixelInset = new Rect(mouseCoord.x - mouseReg.x, | |
mouseCoord.y - mouseReg.y, | |
mouseTex.width, | |
mouseTex.height); | |
takeAppropriateAction(); | |
} | |
private void addAction(WhenActionPerformed whenThisIsTrue,ExecuteThisAction performAction) { | |
actions.Add(whenThisIsTrue,performAction); | |
} | |
private void takeAppropriateAction() { | |
actions.First(keyPair => keyPair.Key()).Value(); | |
} | |
private void setCursorToTarget() { | |
setCursorToTextureAtPoint(iconTarget,targetRegPoint); | |
} | |
private void setCursorToZoom() { | |
setCursorToTextureAtPoint(iconZoom,zoomRegPoint); | |
} | |
private void setCursorToArrow() { | |
setCursorToTextureAtPoint(iconArrow,arrowRegPoint); | |
} | |
private void setCursorToTextureAtPoint(Texture texture,Vector2 regPoint) { | |
if (texture) { | |
guiTexture.texture = texture; | |
mouseReg = regPoint; | |
Screen.showCursor = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment