duck

Untitled

Jun 29th, 2011
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 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.     public float lengthFactor = 1.5f;
  11.    
  12.     Transform[] bones;
  13.  
  14.     // Use this for initialization
  15.     void Start ()
  16.     {
  17.        
  18.         bones = new Transform[numJoints];
  19.        
  20.         bones[0] = source;
  21.         bones[numJoints - 1] = dest;
  22.        
  23.         for (int n = 1; n < numJoints - 1; ++n) {
  24.             bones[n] = GameObject.CreatePrimitive (PrimitiveType.Sphere).transform;
  25.         }
  26.     }
  27.  
  28.     // Update is called once per frame
  29.     void Update ()
  30.     {
  31.        
  32.         float length = (dest.position - source.position).magnitude * lengthFactor;
  33.         Vector3 prevPos = source.position;
  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.LookRotation(pos-prevPos);
  44.            
  45.             prevPos = pos;
  46.            
  47.             bones[n].position = pos;
  48.             bones[n].rotation = rot;
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment