Created
October 23, 2022 21:11
-
-
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.
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 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