30-01-2020, 03:36 AM
Update: this is a sample and it somehow works, but not precise yet as there is a spring thing happening. It would be great if we can make the springing thing disappear.
Code:
void FixedUpdate()
{
Ray ray = new Ray(this.transform.position, transform.forward);
if (triggerOnce)
{
Debug.Log("Tigger once");
triggerOnce = false;
RenderOnce();
}
else if (pickedParticleIndex >= 0)
{
float invmass = solver.invMasses[pickedParticleIndex];
Vector4 position = solver.transform.TransformPoint(solver.positions[pickedParticleIndex]);
Vector4 velocity = solver.velocities[pickedParticleIndex];
Vector4 targetposition = this.transform.position;
//// calculate picking position in solver space:
solver.externalForces[pickedParticleIndex] = ((targetposition - position) * springStiffness - velocity * springDamping) / invmass;
}
}
void RenderOnce()
{
Ray ray = new Ray(transform.position, transform.forward);
float closestMu = float.MaxValue;
float closestDistance = float.MaxValue;
for (int i = 0; i < solver.renderablePositions.count; ++i)
{
float mu;
Vector3 projected = ObiUtils.ProjectPointLine(solver.transform.TransformPoint(solver.renderablePositions[i]), ray.origin, ray.origin + ray.direction, out mu, false);
float distanceToRay = Vector3.SqrMagnitude((Vector3)solver.transform.TransformPoint(solver.renderablePositions[i]) - projected);
mu = Mathf.Max(0, mu);
float radius = solver.principalRadii[i][0] * radiusScale;
if (distanceToRay <= radius * radius && distanceToRay < closestDistance && mu < closestMu)
{
closestMu = mu;
closestDistance = distanceToRay;
pickedParticleIndex = i;
}
}
}