Gradual rotation of an object from its plane

40 Views Asked by At

My problem is more complex than one would think from reading the title, of course I already know that to perform a rotation in steps, I should use, for example, this code:

Quaternion rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * speed);

transform.rotation = rotation

But my problem is slightly more complex, let me describe my situation:

I have a cube that must follow an object by rotating only the Y axis, to do this I use the translation on a plane, in a few words the plane is created from the cube, so it has the same inclination, then I get the translation of the object to follow on the plane, after obtaining the coordinates of that point I calculate the angle between the Forward vector of the cube and the vector that identifies the position of the point that we found before.

This works very well and is very useful, for example when I have complex objects such as cannons or towers in which I need only one section, for example the trunk to rotate on the Y axis, and in particular that these mechacnisms work even if the entire object undergoes a rotation, I lie it down or place it upside down.

This is the code I use:

Plane plane = new Plane(transform.up, .ransform.position);
Vector3 closestPoint = plane.ClosestPointOnPlane(target.transform.position);

float angle = Vector3.SignedAngle(transform.forward, closestPoint, plane.normal);

transform.Rotate(new Vector3(0, angle, 0), Space.Self);

As already mentioned the code works very well, my object follows the target as required, rotating only on the Y axis, and when this object is turned, for example, upside down, or placed on its side, it rotates as desired.

Now I would like the rotation not to be instantaneous, but to be gradual, so that I can use a rotation speed, this would be useful to give more respite to the object being pursued, for example the player having to dodge bullets from a cannon.

I tried to use this code:

Plane plane = new Plane(transform.up, transform.position);
Vector3 closestPoint = plane.ClosestPointOnPlane(target.transform.position);

float angle = Vector3.SignedAngle(transform.forward, closestPoint, plane.normal);

Vector3 targetRotation = new Vector3(transform.position.x, angle, transform.position.z);
Quaternion rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(targetRotation), Time.deltaTime * speed);

transform.rotation = rotation;

but the rotation is no longer correct, i.e. it no longer points towards the target, and many times the cube vibrates, the problem is that when the object rotates to chase the target it also shifts the plane and therefore forms a new rotation angle which changes every frame, plus the rotation it performs isn't even correct.

So how do I get a rotation like Transform.Rotate, but be gradual?

Thanks in advance

0

There are 0 best solutions below