Skip to content

Instantly share code, notes, and snippets.

@MattRix
Last active August 8, 2024 00:25
Show Gist options
  • Save MattRix/bd0ba767f75906b7f86cb8214a60972e to your computer and use it in GitHub Desktop.
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
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));
}
}
@Eyliess
Copy link

Eyliess commented Apr 30, 2019

Absolutely amazing, thank you.

@Clonkex
Copy link

Clonkex commented Jan 23, 2020

This is saved me so much time, thank you! I wish I could star this 10 times 😄

@MattRix
Copy link
Author

MattRix commented Jan 23, 2020

I forgot I wrote this, glad you found it useful!

@silpyy
Copy link

silpyy commented Jul 13, 2020

This is a gem. Thanks alot.

@Irondef
Copy link

Irondef commented Nov 3, 2021

Thank you! Worked perfectly

@feraldeveloper
Copy link

how to give money github

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment