duck

Fixed simple rope interpolation

Jun 29th, 2011
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.35 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Rope : MonoBehaviour
  5. {
  6.  
  7.     public int numJoints = 7;
  8.     public Transform source;
  9.     public Transform dest;
  10.  
  11.     Transform[] bones;
  12.  
  13.     // Use this for initialization
  14.     void Start ()
  15.     {
  16.        
  17.         bones = new Transform[numJoints];
  18.        
  19.         bones[0] = source;
  20.         bones[numJoints - 1] = dest;
  21.        
  22.         for (int n = 1; n < numJoints - 1; ++n) {
  23.             bones[n] = GameObject.CreatePrimitive (PrimitiveType.Sphere).transform;
  24.         }
  25.        
  26.     }
  27.  
  28.     // Update is called once per frame
  29.     void Update ()
  30.     {
  31.        
  32.         float length = (dest.position - source.position).magnitude;
  33.        
  34.         for (int n = 1; n < numJoints - 1; ++n) {
  35.            
  36.             float i = Mathf.InverseLerp (0, bones.Length - 1, n);
  37.             float si = Mathf.SmoothStep (0, 1, i);
  38.            
  39.             Vector3 sourceLine = source.position + source.forward * length * i;
  40.             Vector3 destLine = dest.position - dest.forward * length * (1 - i);
  41.            
  42.             Vector3 pos = Vector3.Lerp (sourceLine, destLine, si);
  43.             Quaternion rot = Quaternion.Slerp (source.rotation, dest.rotation, si);
  44.            
  45.             bones[n].position = pos;
  46.             bones[n].rotation = rot;
  47.         }
  48.        
  49.     }
  50.    
  51. }
Advertisement
Add Comment
Please, Sign In to add comment