Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.