Really need your help. I'm trying to create a custom controller for my app to allow users to resize and rotate game objects using a single drag object.
I was able to create the code to create the visuals and to rotate it but I'm stuck on how to resize the game object. To position the drag handle at the start, I'm getting the bounds of the target object and taking the bounds.extents.magnitude
to determine the y position.
So I was hoping the behavior would be such that when you drag the handle closer to the center of the target object it shrinks the bounds.extents.magnitude
based on the new handle position and then becomes bigger if you go further away from the center of the target object.
Here is where I am now:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CircleMaker : MonoBehaviour
{
public float lineWidth = .1f;
private int segments=360;
private LineRenderer line;
private float radius;
private Renderer boundsSource;
private Bounds bounds;
public GameObject dragHandle;
public GameObject target;
private int pointCount;
private Vector3[] points;
public int angle = 0;
public float zPosition = -8.0f;
public bool isDraggingHandle = false;
void Start()
{
line = GetComponent<LineRenderer>();
boundsSource = target.GetComponent<Renderer>();
bounds = boundsSource.bounds;
line.useWorldSpace = true;
line.startWidth = lineWidth;
line.endWidth = lineWidth;
line.positionCount = segments + 1;
line.receiveShadows = false;
line.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
pointCount = segments + 1;
points = new Vector3[pointCount];
float r = bounds.extents.magnitude;
float d2r = Mathf.Deg2Rad * (target.transform.localEulerAngles.x * 360f / segments);
dragHandle.transform.position = new Vector3(Mathf.Sin(d2r) * r, Mathf.Cos(d2r) * r, zPosition) + target.transform.position;
DrawCircle();
}
void Update()
{
if (isDraggingHandle)
{
//rotate object based on drag handle location
Vector3 direction = target.transform.position - dragHandle.transform.position;
int sign = (direction.x >= 0) ? 1 : -1;
float offset = (sign >= 0) ? 0 : 360;
float angle = Vector2.Angle(Vector2.down, direction)*sign+offset;
target.transform.rotation = Quaternion.Euler(0, 0, angle);
}
if (target.GetComponent<DragAndDrop>().isDragging == true)
{
dragHandle.transform.parent = target.transform;
}
else
{
dragHandle.transform.parent = null;
}
DrawCircle();
}
//draw circle around target gameobject based on bounds.extents
void DrawCircle()
{
radius = bounds.extents.magnitude*target.transform.localScale.x;
for (int i = 0; i < pointCount; i++)
{
float rad = Mathf.Deg2Rad * (i * 360f / segments);
points[i] = new Vector3(Mathf.Sin(rad) * radius, Mathf.Cos(rad) * radius, zPosition) + target.transform.position;
}
line.SetPositions(points);
}
}