Rotate an Object around selected local axis towards another object?
Hi, I am currently trying to create something similar to a hinge joint, but without physics-interaction. This will then be used to create a lever for VR.
What I need for this, is to have an object rotate around a SINGLE axis - in the objects local space - that I choose in the direction of another Transform. The axis on the lever that later points in the direction of the other transform should also be selected.
Example: The lever-Object rotates around the LOCAL z-Axis so that the x-Axis points towards the other transform as far as posible on this axis.
Meanwhile the position and all other rotations should be maintained (in the example: position and x and y rotation). I tried combining tutorials, scripts and my last few braincells to create something that works but I just can not wrap my head around these Quaternions. This is what I have created the whole long day:
public class LeverFramework : MonoBehaviour
{
[SerializeField] private Transform axis;
[SerializeField] private float rotationSpeed;
[SerializeField] private bool restrictX = false;
[SerializeField] private bool restrictY = false;
[SerializeField] private bool restrictZ = false;
private InputDevice targetDevice;
public float XDegree;
public float YDegree;
public float ZDegree;
public Vector3 rotationAxis;
public GameObject sphere;
private void FixedUpdate()
{
//sphere.transform.position = currentDevicePos.position;
if (interactorPresent == true)
{
}
//sphere.transform.position = currentDevicePos.position;
Vector3 lookDirection = (sphere.transform.position - axis.position).normalized;
Quaternion rotation = Quaternion.LookRotation(lookDirection, rotationAxis) * Quaternion.Euler(XDegree, YDegree, ZDegree);
Debug.DrawRay(axis.position, lookDirection);
Quaternion completeRot = Quaternion.Slerp(axis.rotation, rotation, Time.deltaTime * rotationSpeed);
float x = axis.localRotation.x;
float y = axis.localRotation.y;
float z = axis.localRotation.z;
if (restrictX == false)
{
x = completeRot.eulerAngles.x;
}
if (restrictY == false)
{
y = completeRot.eulerAngles.y;
}
if (restrictZ == false)
{
z = completeRot.eulerAngles.z;
}
axis.rotation = Quaternion.Euler(x, y, z);
}
it did turn towards my "sphere" object in some occasions but if I rotate the parent of my "Axis" Transform which holds the lever model that should rotate towards the sphere on the selected axis, my axis-object developes consciousness and doesnt do what I had planned for it.
I dont even know where to start with the problem. I worked on a solution a few hours ago that contained trying to work in local space, but I failed miserably.
Can someone tell me from the ground up how to rotate my lever on only one axis in Local Space towards another transform while maintaining all other transforms? It would mean the world to me and I could sleep for the first time in weeks again (˘o˘ ). I hope someone can help me. Have a great day!