I have a vector3 value that I am setting in inspector and I am drawing a ray using OnDrawGizoms
to draw that vector line.
However, the position handle I made using Handles API to set the vector3 value is placed certain distance away from the vector unit. It's not placed exactly at the end point of the vector line that is drawn and I am not sure why.
My goal is to just make a handle to position a vector3 value.
EDIT: For some reason, the handle is positioned correctly for y position alone but not for x and z positions.
Here is my code:
In this script, it is the localTargetPosition
vector3 value that I want to make my handle for.
public class MovePlatform : MonoBehaviour
{
public Vector3 localTargetPosition = new Vector3(5, 0, 0);
public Vector3 m_initialPosition { get { return initialPosition; } set { initialPosition = value; } }
private Vector3 initialPosition, targetPosition, targetPosDebug;
public float speed = 3;
public bool loop;
void Start()
{
initialPosition = transform.position;
SetTargetPosition(localTargetPosition);
}
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
if (transform.position == targetPosition)
{
if (loop)
{
SwitchDirection();
}
}
}
public void SwitchDirection()
{
if (transform.position == initialPosition)
{
SetTargetPosition(localTargetPosition);
}
else
{
targetPosition = initialPosition;
}
}
private void SetTargetPosition(Vector3 localPosition)
{
targetPosition = initialPosition + transform.TransformDirection(localPosition);
targetPosDebug = targetPosition;
}
void OnDrawGizmos()
{
if (Application.isPlaying)
{
Debug.DrawLine(initialPosition, targetPosDebug, Color.red);
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(localTargetPosition), Color.red);
}
}
}
This is the script used for making handle:
[CustomEditor(typeof(MovePlatform)), CanEditMultipleObjects]
public class MovePlatformEditor : Editor
{
protected virtual void OnSceneGUI()
{
MovePlatform movePlatform = (MovePlatform)target;
Vector3 initialPosition = movePlatform.transform.TransformPoint(movePlatform.m_initialPosition);
Vector3 targetPosition = movePlatform.transform.TransformPoint(movePlatform.localTargetPosition);
EditorGUI.BeginChangeCheck();
Handles.Label(targetPosition, "Target", "button");
targetPosition = Handles.PositionHandle(targetPosition, movePlatform.transform.rotation);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(movePlatform, "Move Handles");
movePlatform.localTargetPosition = movePlatform.transform.InverseTransformPoint(targetPosition);
}
Handles.color = Color.yellow;
//Handles.DrawLine(initialPosition, targetPosition);
}
}