Skip to content

Instantly share code, notes, and snippets.

@FaffyWaffles
Created October 25, 2022 08:15
Show Gist options
  • Select an option

  • Save FaffyWaffles/7aed78f107a47372a4549d8f0732c7dd to your computer and use it in GitHub Desktop.

Select an option

Save FaffyWaffles/7aed78f107a47372a4549d8f0732c7dd to your computer and use it in GitHub Desktop.
Moveable Point Cloud
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Sirenix.OdinInspector;
public class MovablePoints : MonoBehaviour
{
public List<Vector2> points = new List<Vector2>();
public List<int> moveablePoints = new List<int>();
[Range(.01f, 1f)] public float selectionRadius = .05f;
public bool selectionActive;
[OnValueChanged("GeneratePoints")]
[Range(3, 5000)] public int numPoints = 50;
[Button]
void GeneratePoints()
{
points.Clear();
for (int i = 0; i < numPoints; i++)
points.Add(new Vector2(UnityEngine.Random.Range(-1f, 1f), UnityEngine.Random.Range(-1f, 1f)));
}
public Vector2 clickedPos;
public List<Vector2> offsets = new List<Vector2>();
private void Update()
{
Vector2 mosPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetMouseButtonDown(0))
{
clickedPos = mosPos;
for (int i = 0; i < points.Count; i++)
{
Vector2 point = points[i];
if (IsPointInRange(point, mosPos))
{
if (!moveablePoints.Contains(i))
{
offsets.Add(point - clickedPos);
moveablePoints.Add(i);
}
}
}
}
if (Input.GetMouseButton(0))
{
for (int i = 0; i < moveablePoints.Count; i++)
{
Vector2 offset = offsets[i];
points[moveablePoints[i]] = mosPos + offset;
}
}
if (Input.GetMouseButtonUp(0))
{
offsets.Clear();
moveablePoints.Clear();
}
}
[Range(.001f, .1f)] public float gizmoSize = .05f;
void OnDrawGizmos()
{
if (selectionActive)
{
if (Input.GetAxis("Mouse ScrollWheel") > 0f && selectionRadius < 1)
selectionRadius += .01f;
if (Input.GetAxis("Mouse ScrollWheel") < 0f && selectionRadius > 0)
selectionRadius -= .01f;
Vector2 mosPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Handles.DrawWireDisc(mosPos, new Vector3(0, 0, 1), selectionRadius);
for (int i = 0; i < points.Count; i++)
{
Vector2 point = points[i];
if (IsPointInRange(point, mosPos))
{
if (Input.GetMouseButton(0) && moveablePoints.Contains(i))
Gizmos.color = Color.green;
else
Gizmos.color = Color.red;
}
else
Gizmos.color = Color.white;
Gizmos.DrawSphere(point, gizmoSize);
}
}
}
bool IsPointInRange(Vector2 point, Vector2 mosPos)
{
float dx = Mathf.Abs(point.x - mosPos.x);
float dy = Mathf.Abs(point.y - mosPos.y);
if (dx > selectionRadius)
return false;
if (dy > selectionRadius)
return false;
if (dx + dy <= selectionRadius)
return true;
if (Mathf.Pow(dx, 2) + Mathf.Pow(dy, 2) <= Mathf.Pow(selectionRadius, 2))
return true;
return false;
}
}
@FaffyWaffles
Copy link
Author

MoveablePoints

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment