- Home /
Lookat Direction by AddTorque?
I have a rigidbody character spinning only around Y.
I need it to be able to set direction in 2 different ways / different player modes, using AddTorque:
A) Look at Target over time
B) Look at Direction over time (Direction = normalized Vector 3, like the normal returned from a raycast hit)
I can do either with different code, but I want to use the same code for both as much as possible, to have the same behavior in terms of smoothing etc.
I have settled on a well functioning code for A) Look at Target.
Now I cannot for the love of god get my head around how to adapt it to not spin, but focus in a direction, as B)
Here's the code I use for A), which I really like the feel of, and need to adapt to a B) mode..
float rotationSpeed = 10f;
public GameObject targetObject;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Vector3 targetPosition = targetObject.transform.position;
Vector3 inverseVect = transform.InverseTransformPoint(targetPosition);
float rotationAngle = Mathf.Atan2(inverseVect.x, inverseVect.z) * Mathf.Rad2Deg;
Vector3 rotationVelocity = (Vector3.up * rotationAngle) * rotationSpeed * Time.deltaTime;
Vector3 deltavel = (rotationVelocity - rb.angularVelocity);
rb.AddTorque(deltavel, ForceMode.Impulse);
}
Comment