Last active
August 8, 2024 00:25
-
-
Save MattRix/bd0ba767f75906b7f86cb8214a60972e to your computer and use it in GitHub Desktop.
A thing you can use to make a rigidbody move towards a position reliably
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System; | |
[RequireComponent (typeof(Rigidbody))] | |
public class PhysicsFollower : MonoBehaviour | |
{ | |
public Transform target; | |
Rigidbody rb; | |
[Range(0f,1f)] public float positionStrength = 1f; | |
[Range(0f,1f)] public float rotationStrength = 1f; | |
void Awake () | |
{ | |
rb = GetComponent<Rigidbody>(); | |
rb.useGravity = false; | |
rb.maxAngularVelocity = 30f; //set it to something pretty high so it can actually follow properly! | |
} | |
void FixedUpdate () | |
{ | |
if(target == null) return; | |
Vector3 deltaPos = target.position - transform.position; | |
rb.velocity = 1f/Time.fixedDeltaTime * deltaPos * Mathf.Pow(positionStrength, 90f*Time.fixedDeltaTime); | |
Quaternion deltaRot = target.rotation * Quaternion.Inverse(transform.rotation); | |
float angle; | |
Vector3 axis; | |
deltaRot.ToAngleAxis(out angle, out axis); | |
if (angle > 180.0f) angle -= 360.0f; | |
rb.angularVelocity = ((1f/Time.fixedDeltaTime) * angle * axis * 0.01745329251994f * Mathf.Pow(rotationStrength, 90f*Time.fixedDeltaTime)); | |
} | |
} |
This is saved me so much time, thank you! I wish I could star this 10 times 😄
I forgot I wrote this, glad you found it useful!
This is a gem. Thanks alot.
Thank you! Worked perfectly
how to give money github
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Absolutely amazing, thank you.