96 lines
1.9 KiB
C#
96 lines
1.9 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
[Serializable]
|
|
public class Constraint2D
|
|
{
|
|
public bool active;
|
|
|
|
public int p1;
|
|
|
|
public int p2;
|
|
|
|
public float length;
|
|
|
|
public Vector2 pos;
|
|
|
|
public int contype;
|
|
|
|
public Transform obj;
|
|
|
|
public static Constraint2D CreatePointTargetCon(int _p1, Transform trans)
|
|
{
|
|
Constraint2D constraint2D = new Constraint2D();
|
|
constraint2D.p1 = _p1;
|
|
constraint2D.active = true;
|
|
constraint2D.contype = 2;
|
|
constraint2D.obj = trans;
|
|
return constraint2D;
|
|
}
|
|
|
|
public static Constraint2D CreateLenCon(int _p1, int _p2, float _len)
|
|
{
|
|
Constraint2D constraint2D = new Constraint2D();
|
|
constraint2D.p1 = _p1;
|
|
constraint2D.p2 = _p2;
|
|
constraint2D.length = _len;
|
|
constraint2D.active = true;
|
|
constraint2D.contype = 0;
|
|
return constraint2D;
|
|
}
|
|
|
|
public static Constraint2D CreatePointCon(int _p1, Vector2 _pos)
|
|
{
|
|
Constraint2D constraint2D = new Constraint2D();
|
|
constraint2D.p1 = _p1;
|
|
constraint2D.pos = _pos;
|
|
constraint2D.active = true;
|
|
constraint2D.contype = 1;
|
|
return constraint2D;
|
|
}
|
|
|
|
public void Apply(MegaSoft2D soft)
|
|
{
|
|
switch (contype)
|
|
{
|
|
case 0:
|
|
ApplyLengthConstraint2D(soft);
|
|
break;
|
|
case 1:
|
|
ApplyPointConstraint2D(soft);
|
|
break;
|
|
}
|
|
}
|
|
|
|
public void ApplyLengthConstraint2D(MegaSoft2D soft)
|
|
{
|
|
if (active && soft.applyConstraints)
|
|
{
|
|
Vector2 vector = soft.masses[p2].pos - soft.masses[p1].pos;
|
|
float magnitude = vector.magnitude;
|
|
if (magnitude != 0f)
|
|
{
|
|
vector.x /= magnitude;
|
|
vector.y /= magnitude;
|
|
Vector2 vector2 = 0.5f * (magnitude - length) * vector;
|
|
soft.masses[p1].pos.x += vector2.x;
|
|
soft.masses[p1].pos.y += vector2.y;
|
|
soft.masses[p2].pos.x += 0f - vector2.x;
|
|
soft.masses[p2].pos.y += 0f - vector2.y;
|
|
}
|
|
}
|
|
}
|
|
|
|
public void ApplyPointConstraint2D(MegaSoft2D soft)
|
|
{
|
|
if (active)
|
|
{
|
|
soft.masses[p1].pos = pos;
|
|
}
|
|
}
|
|
|
|
public void ApplyAngleConstraint(MegaSoft2D soft)
|
|
{
|
|
}
|
|
}
|