It’s attached to an enemy space ship that follows you by turning to face you and moving forward. It works fine if the enemy is stationary and only the player moves, but when they both move the rotation jitters and doesn’t work properly at all. If I turn the rotation speed up to the point of instantaneous, then it works fine, but in this game I need it to be a slow and smooth rotation.
Any Idea on how to fix this, or maybe an alternative way of rotating on a 2D axis would be awesome.
One problem is that you’re editing individual components of a quaternion, which is really complicated, so you should probably convert the above code to something more like
I adapted this from a script that causes the object the script is on to look at the mouse. If this doesn’t work let me know and I’ll try to provide a better explanation, but this should work if you replace “TARGETTRANSFORM” with a transform of whatever name you want.
I program in C# but when I tested this with Javascript it didn’t throw any errors, so I hope it’s fine for you.
Good luck.
P.S. Put this in your FixedUpdate function or wherever your previous rotation script was.
var dir = transform.position - target.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
var newRotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * rotatespeed);
This assumes that this object is a sprite or Quad in which the ‘forward’ is to the right. If the forward is ‘up’, then you will need to adjust the angle by 90 degrees after the Atan2() call.