# Look at rotation at a moving object while moving (C#)(2D)

I used some javascript that happened to work in C#.

``````			var newRotation = Quaternion.LookRotation(transform.position - target.position, Vector3.back);

newRotation.x = 0.0f;

newRotation.y = 0.0f;

transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * rotatespeed);
``````

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

``````Quaternion newRotation = Quaternion.LookRotation(transform.position - target.position, Vector3.back);
Vector3 eulers = newRotation.eulerAngles;
eulers.x = 0.0f;

eulers.y = 0.0f;
nwRotation = Quaternion.Euler(eulers);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * rotatespeed);
``````

And then move that code to LateUpdate or FixedUpdate if that doesn’t fix it.

Hey W1k3,

I’m working on a 2D game at the moment and this is the bit in my scripts I use for looking at another object:

``````rigidbody2D.transform.eulerAngles = new Vector3(0,0,Mathf.Atan2((TARGETTRANSFORM.position.y - transform.position.y), (TARGETTRANSFORM.position.x - transform.position.x))*Mathf.Rad2Deg - 90);
``````

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;