Created
November 6, 2018 04:52
-
-
Save imAliAsad/26b2edf5aaa4af3f6985002c1374374c to your computer and use it in GitHub Desktop.
Create a rectangle selection behavior in unity like in strategy games
This file contains 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; | |
namespace Tutorial | |
{ | |
public class SelectionSquare : MonoBehaviour | |
{ | |
public Camera Camera; | |
[SerializeField] | |
private RectTransform rectSquareImage; | |
private Vector3 startPos; | |
private Vector3 endPos; | |
private void Start() | |
{ | |
rectSquareImage.gameObject.SetActive(false); | |
} | |
private void Update() | |
{ | |
if (Input.GetMouseButtonDown(0)) | |
{ | |
RaycastHit hit; | |
if (Physics.Raycast(Camera.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity)) | |
{ | |
startPos = hit.point; | |
} | |
} | |
if (Input.GetMouseButtonUp(0)) | |
{ | |
rectSquareImage.gameObject.SetActive(false); | |
} | |
if (Input.GetMouseButton(0)) | |
{ | |
if (!rectSquareImage.gameObject.activeInHierarchy) | |
{ | |
rectSquareImage.gameObject.SetActive(true); | |
} | |
endPos = Input.mousePosition; | |
Vector3 squareStart = Camera.WorldToScreenPoint(startPos); | |
squareStart.z = 0f; | |
Vector3 centre = (squareStart + endPos) / 2f; | |
rectSquareImage.position = centre; | |
float sizeX = Mathf.Abs(squareStart.x - endPos.x); | |
float sizeY = Mathf.Abs(squareStart.y - endPos.y); | |
rectSquareImage.sizeDelta = new Vector2(sizeX, sizeY); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment