Skip to content

Instantly share code, notes, and snippets.

@paulhayes
Created October 23, 2022 21:11
Show Gist options
  • Save paulhayes/3c626816b67358633a027bded7619776 to your computer and use it in GitHub Desktop.
Save paulhayes/3c626816b67358633a027bded7619776 to your computer and use it in GitHub Desktop.
Simple component for controlling a rigid bodies position and rotation using just the application of forces. Good for allowing playing manipulation of physics simulation.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RigidbodyTrackTransform : MonoBehaviour
{
[SerializeField] Rigidbody body;
[SerializeField] Transform target;
[SerializeField] float maxSpeed = 30f;
[SerializeField] float maxRotSpeed = 720f;
[SerializeField] [Range(0, 1)] float positionEase = 0.5f;
[SerializeField] [Range(0, 1)] float angularEase = 0.3f;
Vector3 targetPosition;
Quaternion targetRotation;
void FixedUpdate()
{
if(target){
targetPosition = target.position;
targetRotation = target.rotation;
}
var deltaPos = targetPosition - body.position;
var deltaRot = targetRotation * Quaternion.Inverse(body.rotation);
Vector3 axis;
float angle;
deltaRot.ToAngleAxis(out angle, out axis);
float speed = positionEase*Mathf.Min(deltaPos.magnitude/Time.deltaTime,maxSpeed);
float angularSpeed = angularEase*Mathf.Sign(angle)*Mathf.Min(Mathf.Abs(angle)/Time.deltaTime,maxRotSpeed);
body.velocity=Vector3.zero;
body.angularVelocity = Vector3.zero;
body.AddForce(speed*deltaPos.normalized,ForceMode.VelocityChange);
body.AddTorque( Mathf.Deg2Rad*angularSpeed*axis,ForceMode.VelocityChange);
}
public void SetTargetTransform(Transform target)
{
this.target=target;
}
public void SetTargetPositionRotation(Vector3 position, Quaternion rotation)
{
this.target=null;
targetPosition = position;
targetRotation = rotation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment