110 lines
2.9 KiB
C#
110 lines
2.9 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class DefaultRotationHandler : IRotateHandler
|
|
{
|
|
private List<float> anglesToRotate = new List<float>();
|
|
private List<float> addedAngles = new List<float>();
|
|
private int currentAngleIndex = 0;
|
|
|
|
public DefaultRotationHandler()
|
|
{
|
|
// add regular angles
|
|
anglesToRotate.Add(0);
|
|
anglesToRotate.Add(45);
|
|
anglesToRotate.Add(90);
|
|
anglesToRotate.Add(135);
|
|
anglesToRotate.Add(180);
|
|
anglesToRotate.Add(225);
|
|
anglesToRotate.Add(270);
|
|
anglesToRotate.Add(315);
|
|
}
|
|
public void performRotation(BlockEditContext ctx)
|
|
{
|
|
if (ctx != null && ctx.IsActive)
|
|
{
|
|
float previousAngle = anglesToRotate[currentAngleIndex];
|
|
|
|
currentAngleIndex++;
|
|
currentAngleIndex %= anglesToRotate.Count;
|
|
|
|
float currentAngle = anglesToRotate[currentAngleIndex];
|
|
float deltaAngle = currentAngle - previousAngle;
|
|
|
|
Vector3 pivotPoint = ctx.GhostTransform.position;
|
|
if (ctx.TargetSocket != null && ctx.MySocket != null)
|
|
{
|
|
pivotPoint = ctx.MySocket.transform.position;
|
|
}
|
|
else if (ctx.AttachPoint != null)
|
|
{
|
|
pivotPoint = ctx.AttachPoint.position;
|
|
}
|
|
|
|
applyRotation(ctx.GhostTransform, pivotPoint, ctx.RotationAxis, deltaAngle);
|
|
}
|
|
}
|
|
public void addAngle(float angle)
|
|
{
|
|
if (addedAngles.Contains(angle))
|
|
{
|
|
return;
|
|
}
|
|
|
|
// normalize the angle (0 - 360)
|
|
if (angle >= 0)
|
|
{
|
|
angle = angle % 360;
|
|
}
|
|
else
|
|
{
|
|
while (angle < 0)
|
|
{
|
|
angle += 360;
|
|
}
|
|
}
|
|
int currentSize = anglesToRotate.Count;
|
|
// add it to list
|
|
for (int i = 0; i < anglesToRotate.Count; i++)
|
|
{
|
|
if (angle < anglesToRotate[i])
|
|
{
|
|
anglesToRotate.Insert(i, angle);
|
|
return;
|
|
}
|
|
}
|
|
if (currentSize == anglesToRotate.Count) // it's the largest element in the whole rotations
|
|
{
|
|
anglesToRotate.Add(angle);
|
|
}
|
|
|
|
addedAngles.Add(angle);
|
|
}
|
|
|
|
public void removeAngle(float angle)
|
|
{
|
|
anglesToRotate.Remove(angle);
|
|
addedAngles.Remove(angle);
|
|
}
|
|
|
|
// should be called when changing the object to be snapped to
|
|
public void clearAngles()
|
|
{
|
|
foreach (float angle in addedAngles)
|
|
{
|
|
anglesToRotate.Remove(angle);
|
|
}
|
|
addedAngles.Clear();
|
|
|
|
// reset to the nearest rotation angle
|
|
currentAngleIndex++;
|
|
currentAngleIndex %= anglesToRotate.Count;
|
|
}
|
|
|
|
private void applyRotation(Transform transform, Vector3 pivot, Vector3 axis, float angle)
|
|
{
|
|
transform.RotateAround(pivot, axis, angle);
|
|
}
|
|
}
|