Skip to content

Instantly share code, notes, and snippets.

@imAliAsad
Created November 6, 2018 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imAliAsad/26b2edf5aaa4af3f6985002c1374374c to your computer and use it in GitHub Desktop.
Save imAliAsad/26b2edf5aaa4af3f6985002c1374374c to your computer and use it in GitHub Desktop.
Create a rectangle selection behavior in unity like in strategy games
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