如何使用自定义编辑器移动另一个Bezier曲线

Ban*_*ane 19 c# unity-game-engine

我创建使用下面这是我从拿到代码贝塞尔曲线 在这里.我还制作了一个BezierPair游戏对象,它有两条贝塞尔曲线作为子对象.

从下面的相应图像和BezierPair,其中points[0]...... points[3]表示为P0...... P3:

  1. 我希望P0每个Bézier曲线在移动时始终保持不变.换句话说,我希望他们总是一起移动,同时选择关闭这个动作.

在此输入图像描述

  1. P1两条曲线是分开的.如何使P1每条曲线在相同距离的相同方向上移动?

在此输入图像描述

  1. P2两条曲线是分开的.我怎样才能让P2一个曲线镜P2沿连线另一曲线 P0P3?注意,镜像线将从曲线1在下面的例子中,因为采取curve1P2运动.如果curve2P2移动,则反射镜线将取自curve2S' P0P3.

在此输入图像描述

我不想在运行时这样做.因此必须使用自定义编辑器.我尝试在下面的代码中解决1.但是如果没有在层次结构窗口中选择BezierPair,第二条曲线的位置将不会更新

贝塞尔:

public static class Bezier {

public static Vector3 GetPoint (Vector3 p0, Vector3 p1, Vector3 p2,   Vector3 p3, float t) {
t = Mathf.Clamp01(t);
float oneMinusT = 1f - t;
return
    oneMinusT * oneMinusT * oneMinusT * p0 +
    3f * oneMinusT * oneMinusT * t * p1 +
    3f * oneMinusT * t * t * p2 +
    t * t * t * p3;
}

public static Vector3 GetFirstDerivative (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t) {
t = Mathf.Clamp01(t);
float oneMinusT = 1f - t;
return
    3f * oneMinusT * oneMinusT * (p1 - p0) +
    6f * oneMinusT * t * (p2 - p1) +
    3f * t * t * (p3 - p2);
}
}
Run Code Online (Sandbox Code Playgroud)

贝兹曲线:

[RequireComponent(typeof(LineRenderer))]
public class BezierCurve : MonoBehaviour {

public Vector3[] points;
LineRenderer lr;
public int numPoints = 49;
bool controlPointsChanged = false;

bool isMoving = false;

public void Reset () {
points = new Vector3[] {
    new Vector3(1f, 0f, 0f),
    new Vector3(2f, 0f, 0f),
    new Vector3(3f, 0f, 0f),
    new Vector3(4f, 0f, 0f)
};
}

void Start()    {

lr = GetComponent<LineRenderer> ();
lr.positionCount = 0;
DrawBezierCurve ();

}
public Vector3 GetPoint (float t) {
return transform.TransformPoint(Bezier.GetPoint(points[0], points[1], points[2], points[3], t));
}

public void DrawBezierCurve ()  {
lr = GetComponent<LineRenderer> ();
lr.positionCount = 1;
lr.SetPosition(0, points[0]);

for (int i = 1; i < numPoints+1; i++) {
    float t = i / (float)numPoints;
    lr.positionCount = i+1;
    lr.SetPosition(i, GetPoint(t));
}
}

public Vector3 GetVelocity (float t) {
return transform.TransformPoint(
    Bezier.GetFirstDerivative(points[0], points[1], points[2], points[3], t)) - transform.position;
}

public Vector3 GetDirection (float t) {
return GetVelocity(t).normalized;
}
}
Run Code Online (Sandbox Code Playgroud)

BezierCurveEditor:

[CustomEditor(typeof(BezierCurve))]
public class BezierCurveEditor : Editor {

private BezierCurve curve;
private Transform handleTransform;
private Quaternion handleRotation;

private const int lineSteps = 10;

private const float directionScale = 0.5f;

private void OnSceneGUI () {
curve = target as BezierCurve;
handleTransform = curve.transform;
handleRotation = Tools.pivotRotation == PivotRotation.Local ?
    handleTransform.rotation : Quaternion.identity;

Vector3 p0 = ShowPoint(0);
Vector3 p1 = ShowPoint(1);
Vector3 p2 = ShowPoint(2);
Vector3 p3 = ShowPoint(3);

Handles.color = Color.gray;
Handles.DrawLine(p0, p1);
Handles.DrawLine(p2, p3);
Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);

curve.DrawBezierCurve ();

if (GUI.changed) {
    curve.DrawBezierCurve ();
    EditorUtility.SetDirty( curve );
    Repaint();
}

}


private void ShowDirections () {
Handles.color = Color.green;
Vector3 point = curve.GetPoint(0f);
Handles.DrawLine(point, point + curve.GetDirection(0f) * directionScale);
for (int i = 1; i <= lineSteps; i++) {
    point = curve.GetPoint(i / (float)lineSteps);
    Handles.DrawLine(point, point + curve.GetDirection(i / (float)lineSteps) * directionScale);
}
}

private Vector3 ShowPoint (int index) {
Vector3 point = handleTransform.TransformPoint(curve.points[index]);
EditorGUI.BeginChangeCheck();
point = Handles.DoPositionHandle(point, handleRotation);
if (EditorGUI.EndChangeCheck()) {
    Undo.RecordObject(curve, "Move Point");
    EditorUtility.SetDirty(curve);
    curve.points[index] = handleTransform.InverseTransformPoint(point);
}
return point;
}
}
Run Code Online (Sandbox Code Playgroud)

BezierPair:

public class BezierPair : MonoBehaviour {


public GameObject bez1;
public GameObject bez2;

public void setupCurves()   {
    bez1 = GameObject.Find("Bez1");
    bez2 = GameObject.Find("Bez2");
}
}
Run Code Online (Sandbox Code Playgroud)

BezierPairEditor:

[CustomEditor(typeof(BezierPair))]
public class BezierPairEditor : Editor {

private BezierPair bezPair;

 public override void OnInspectorGUI()
{
    bezPair = target as BezierPair;

    if (bezPair.bez1.GetComponent<BezierCurve>().points[0] != bezPair.bez2.GetComponent<BezierCurve>().points[0])
    {
        Vector3 assignPoint0 = bezPair.bez1.GetComponent<BezierCurve>().points[0];
        bezPair.bez2.GetComponent<BezierCurve>().points[0] = assignPoint0;

    }
     if (GUI.changed)
    {

        EditorUtility.SetDirty(bezPair.bez1);
        EditorUtility.SetDirty(bezPair.bez2);
        Repaint();
    }
}
Run Code Online (Sandbox Code Playgroud)

Rod*_*ues 0

编辑:

我认为你不需要BezierPair上课。我建议您添加对要“配对”的其他对象的引用作为类 ( )BezierCurve上的公共字段。另一条曲线将与该曲线“配对”。一旦配对,可能会受到运动限制。您可以使用 3 个公共布尔字段 和 来控制所需的行为。BezierCurvepairedbehavior1behavior2behavior3

Note#1:我没有DrawBezierCurve从编辑器中调用该方法,而是将其添加[ExecuteInEditMode]到组件类中。这样,您就不会混合组件和编辑器之间的职责:BezierCurve 组件在场景上绘制自身,而 BezierCurveEditor 仅管理编辑逻辑,例如应用约束和绘制处理程序。

贝塞尔曲线:

using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
[ExecuteInEditMode] // Makes Update() being called often even in Edit Mode
public class BezierCurve : MonoBehaviour
{

  public Vector3[] points;
  public int numPoints = 50;
  // Curve that is paired with this curve
  public BezierCurve paired;
  public bool behavior1; // check on editor if you desired behavior 1 ON/OFF
  public bool behavior2; // check on editor if you desired behavior 2 ON/OFF
  public bool behavior3; // check on editor if you desired behavior 3 ON/OFF
  LineRenderer lr;

  void Reset()
  {
    points = new Vector3[]
    {
      new Vector3(1f, 0f, 0f),
      new Vector3(2f, 0f, 0f),
      new Vector3(3f, 0f, 0f),
      new Vector3(4f, 0f, 0f)
    };
  }

  void Start()
  {
    lr = GetComponent<LineRenderer>();
  }

  void Update()
  {
    // This component is the only responsible for drawing itself.
    DrawBezierCurve();
  }

  // This method is called whenever a field is changed on Editor
  void OnValidate()
  {
    // This avoids pairing with itself
    if (paired == this) paired = null;
  }

  void DrawBezierCurve()
  {
    lr.positionCount = numPoints;
    for (int i = 0; i < numPoints; i++)
    {
      // This corrects the "strange" extra point you had with your script.
      float t = i / (float)(numPoints - 1);
      lr.SetPosition(i, GetPoint(t));
    }
  }

  public Vector3 GetPoint(float t)
  {
    return transform.TransformPoint(Bezier.GetPoint(points[0], points[1], points[2], points[3], t));
  }

  public Vector3 GetVelocity(float t)
  {
    return transform.TransformPoint(Bezier.GetFirstDerivative(points[0], points[1], points[2], points[3], t)) - transform.position;
  }

  public Vector3 GetDirection(float t)
  {
    return GetVelocity(t).normalized;
  }
}
Run Code Online (Sandbox Code Playgroud)

注意#2:所需的行为是在处理程序绘图方法中编码的,因此您可以访问撤消和其他功能。

Note#3:自 Unity 5.3 起EditorUtility.SetDirty认为已过时,用于将对象标记为脏绘图,并且不应再用于修改场景中的对象Undo.RecordObject完成工作。

贝塞尔曲线编辑器:

using UnityEngine;
using UnityEditor;

// This attribute allows you to select multiple curves and manipulate them all as a whole on Scene or Inspector
[CustomEditor(typeof(BezierCurve)), CanEditMultipleObjects]
public class BezierCurveEditor : Editor
{
  BezierCurve curve;
  Transform handleTransform;
  Quaternion handleRotation;
  const int lineSteps = 10;
  const float directionScale = 0.5f;

  BezierCurve prevPartner; // Useful later.

  void OnSceneGUI()
  {
    curve = target as BezierCurve;
    if (curve == null) return;
    handleTransform = curve.transform;
    handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity;

    Vector3 p0 = ShowPoint(0);
    Vector3 p1 = ShowPoint(1);
    Vector3 p2 = ShowPoint(2);
    Vector3 p3 = ShowPoint(3);

    Handles.color = Color.gray;
    Handles.DrawLine(p0, p1);
    Handles.DrawLine(p2, p3);
    Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);

    // Handles multiple selection
    var sel = Selection.GetFiltered(typeof(BezierCurve), SelectionMode.Editable);
    if (sel.Length == 1)
    {
      // This snippet checks if you just attached or dettached another curve,
      // so it updates the attached member in the other curve too automatically
      if (prevPartner != curve.paired)
      {
        if (prevPartner != null) { prevPartner.paired = null; }
        prevPartner = curve.paired;
      }
    }
    if (curve.paired != null & curve.paired != curve)
    {
      // Pair the curves.
      var partner = curve.paired;
      partner.paired = curve;
      partner.behavior1 = curve.behavior1;
      partner.behavior2 = curve.behavior2;
      partner.behavior3 = curve.behavior3;
    }
  }

  // Constraints for a curve attached to back
  // The trick here is making the object being inspected the "master" and the attached object is adjusted to it.
  // This way, you avoid the conflict of one object trying to move the other.
  // [ExecuteInEditMode] on component class makes it posible to have real-time drawing while editing.
  // If you were calling DrawBezierCurve from here, you would only see updates on the other curve when you select it
  Vector3 ShowPoint(int index)
  {
    var thisPts = curve.points;
    Vector3 point = handleTransform.TransformPoint(thisPts[index]);
    EditorGUI.BeginChangeCheck();
    point = Handles.DoPositionHandle(point, handleRotation);
    if (EditorGUI.EndChangeCheck())
    {
      if (curve.paired != null && curve.paired != curve)
      {
        Undo.RecordObjects(new Object[] { curve, curve.paired }, "Move Point " + index.ToString());
        var pairPts = curve.paired.points;
        var pairTransform = curve.paired.transform;
        switch (index)
        {
          case 0:
            {
              if (curve.behavior1)
              {
                pairPts[0] = pairTransform.InverseTransformPoint(point);
              }
              break;
            }
          case 1:
            {
              if (curve.behavior2)
              {
                var p1 = handleTransform.TransformPoint(thisPts[1]);
                pairPts[1] += pairTransform.InverseTransformVector(point - p1);
              }
              break;
            }
          case 2:
            {
              if (curve.behavior3)
              {
                var p0 = handleTransform.TransformPoint(thisPts[0]);
                var p3 = handleTransform.TransformPoint(thisPts[3]);
                var reflect = Vector3.Reflect(p3 - point, (p3 - p0).normalized);
                pairPts[2] = pairTransform.InverseTransformPoint(p3 + reflect);
              }
              break;
            }
          default:
            break;
        }
      }
      else
      {
        Undo.RecordObject(curve, "Move Point " + index.ToString());
      }
      thisPts[index] = handleTransform.InverseTransformPoint(point);
    }
    return point;
  }
}
Run Code Online (Sandbox Code Playgroud)

为了使其正常工作,请BezierCurve通过检查器将一个字段引用到另一个字段的配对字段,然后设置“开/关”您想要的行为。

提示:修改 的属性LineRenderer以获得很酷的渐变或宽度变化(如画笔描边)。End Cap Vertices如果您有一个尖点节点并希望它看起来连续,请增加“线条渲染器”上的值。用作Sprites-Default2D 材质。

  • 我认为这不需要另一个问题。在我看来,最好在这里解决它,而不是问另一个严重依赖于这个问题的问题。 (4认同)
  • 我喜欢贝塞尔曲线选择选项,我认为这真的会很好用。我考虑解决方法“[ExecuteInEditMode]”的主要原因是我预见自己将使用大量曲线。也许,一种仅在选择曲线更新或可以执行某些操作时检查曲线更新的方法。 (2认同)