void Update()
{
Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mouseposition - transform.position;
float angle = Mathf.Atan2(direction.y,direction.x)*Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0,0,angle);
}
Guys this is my code snippet from PlayerMovement code.
I wrote this code for make player look at mouse.It works but player rotating very fast.
How can i control the rotate speed?
Rotation can be done in different ways.
If we save your existing code, then I found an example here with Quaternion.Euler method:
// Rotation scripting with Euler angles correctly.
// Store the Euler angle in a class variable, and only use it to
// apply it as an Euler angle, but never rely on reading the Euler back.
float angle;
float speed;
void Update ()
{
x += Time.deltaTime * speed;
transform.rotation = Quaternion.Euler(0,0,x);
}
- Use
Time.deltaTime to stay tuned with different FPS.
- Add
speed variable by multiplication to control the speed.
- You can notice that this snippet uses
+= instead of =.
So the final snippet will use Quaternion.RotateTowards â£additionally to make it smooth imitating += operator:
[SerializeField]
private float speed = 200f; // degrees per second
void Update()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePosition - transform.position;
float targetAngle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion targetRotation = Quaternion.Euler(0, 0, targetAngle);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
targetRotation,
speed * Time.deltaTime
);
}