AaronBacon

SpringJoint Unity Code

Oct 13th, 2020
633
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SpringCompress : MonoBehaviour
  6. {
  7.     public Transform otherEnd; // The Other end of the spring that this object should try stay a set distance from
  8.     public float targetDistance; // The distance this object should try keep from otherEnd
  9.     public float springForce;
  10.     private Rigidbody rigid;
  11.     // Start is called before the first frame update
  12.     void Start()
  13.     {
  14.         rigid = GetComponent<Rigidbody>();
  15.     }
  16.  
  17.     // Update is called once per frame
  18.     void FixedUpdate()
  19.     {
  20.         private float current = Vector3.Distance(transform.position, otherEnd.position);
  21.         if(current > targetDistance) // Spring is extended
  22.         {
  23.             //Pull in spring
  24.              transform.LookAt(otherEnd);
  25.              rigid.AddRelativeForce(Vector3.forward * springForce);
  26.  
  27.         }
  28.         else // spring is compressed
  29.         {
  30.             //extend Spring
  31.             transform.LookAt(otherEnd);
  32.             rigid.AddRelativeForce(Vector3.forward * -springForce);
  33.         }
  34.     }
  35. }
  36.  
RAW Paste Data