I’ve been scripting a pulley system, and was hoping to get some critique of its implementation so far. One of my main problems is that with a low drag, the system has this whole perpetual bouncing thing going on, but with high drag, it doesn’t respond very well to things pushing on it.
using UnityEngine;
using System.Collections;
public class PulleyBehaviour : MonoBehaviour {
public Rigidbody bodyA;
public Rigidbody bodyB;
public GameObject pivotA;
public GameObject pivotB;
private Vector3 lastVelA;
private Vector3 lastVelB;
private float totalLength;
// Use this for initialization
void Start () {
Vector3 posA = bodyA.position;
Vector3 posB = bodyB.position;
float lengthA = (pivotA.transform.position - posA).magnitude;
float lengthB = (pivotB.transform.position - posB).magnitude;
totalLength = lengthA + lengthB;
lastVelA = bodyA.velocity;
lastVelB = bodyB.velocity;
}
// Update is called once per frame
void FixedUpdate () {
float lengthA = (pivotA.transform.position - bodyA.position).magnitude;
float lengthB = (pivotB.transform.position - bodyB.position).magnitude;
if( lengthA + lengthB > totalLength ) {
Vector3 d1 = bodyA.position - pivotA.transform.position;
Vector3 d2 = bodyB.position - pivotB.transform.position;
d1.Normalize();
d2.Normalize();
Vector3 forceA = (bodyA.velocity - lastVelA) * -bodyA.mass;
Vector3 forceB = (bodyB.velocity - lastVelB) * -bodyB.mass;
bodyB.AddForce( forceA );
bodyA.AddForce( forceB );
float diff = -(totalLength - lengthA - lengthB);
float aMoves = diff * (bodyB.mass / (bodyA.mass + bodyB.mass));
float bMoves = diff - aMoves;
bodyA.position = bodyA.position - aMoves * d1;
bodyB.position = bodyB.position - bMoves * d2;
}
}
}