- Home /
Question by
notfriday666 · Aug 16, 2019 at 01:19 PM ·
rotationtranslate
Smooth rotating object not working
I have a script that I use to move and rotate object A to position and rotation of object B. For some reason my script is not rotating correctly. It translates objects correctly, but sometimes object rotates not enough and sometimes too much. This is my script:
using UnityEngine;
using System.Collections;
public class SmoothTranslator : MonoBehaviour
{
float distancePerSecond;
[SerializeField]
float rotationPerSecond;
public GameObject go;
public GameObject target;
public float timer = -10;
public void Translate(GameObject go, GameObject target, float time)
{
distancePerSecond = Vector3.Distance(target.transform.position, go.transform.position) / time;
rotationPerSecond = MyVector3.AngleInDeg(target.transform.rotation.eulerAngles, go.transform.rotation.eulerAngles) / time;
timer = time;
this.go = go;
this.target = target;
}
void Update()
{
if (timer > 0)
{
timer -= Time.deltaTime;
go.transform.position = Vector3.MoveTowards(go.transform.position, target.transform.position, distancePerSecond * Time.deltaTime);
go.transform.rotation = Quaternion.RotateTowards(go.transform.rotation, target.transform.rotation, rotationPerSecond * Time.deltaTime * 1.3f);
}
else
{
go.transform.position = target.transform.position;
go.transform.rotation = target.transform.rotation;
Destroy(this);
}
}
}
And this class where I calculate angle.
using UnityEngine;
public static class MyVector3
{
public static float AngleInRad(Vector3 vec1, Vector3 vec2)
{
return Mathf.Atan2(vec2.y - vec1.y, vec2.x - vec1.x);
}
public static float AngleInDeg(Vector3 vec1, Vector3 vec2)
{
return AngleInRad(vec1, vec2) * 180 / Mathf.PI;
}
}
Can somebody help me with this? I don't know what is wrong here.
Comment