- Home /
 
How to rotate object to cursor?
 // Take mouse position
 mouse = Input.mousePosition;
 castPoint = Camera.main.ScreenPointToRay(mouse);
 
 // Take coordinates for Vector
 x=castPoint.direction.x;
 y=castPoint.direction.y; 
 
 // And make a direction
 movement=new Vector2(x,y);
 rb.AddForce(movement*speed,ForceMode2D.Force);
 
 
 
               But nothing happen In 2D game*
Answer by pyramidhead01 · Jul 15, 2019 at 01:29 PM
I think this should do what you are asking for.
First add these variables:
      public float RotationSpeed;
      private Quaternion lookRotation;
      private Vector3 direction;
 
               I think this is what you should use as your script:
     public void Update()
     {
         mouse = Input.mousePosition;
          castPoint = Camera.main.ScreenPointToRay(mouse);
         //I'm not sure if castPoint has a position in it or not, but if when you type castPoint.transform.position
         direction = (castPoint.- transform.position).normalized;
  
         //create the rotation we need to be in to look at the target
         lookRotation = Quaternion.LookRotation(direction);
  
         //rotate us over time according to speed until we are in the required rotation
         transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * RotationSpeed);
     }
 
               I used this script for reference, I don't know what a lot of this actually means (or how Quaternions actually work) but this is my holy grail reference for rotating: https://answers.unity.com/questions/254130/how-do-i-rotate-an-object-towards-a-vector3-point.html
Let me know if that works if if you have other questions.
Your answer
 
             Follow this Question
Related Questions
Slerp object in direction of traveling 1 Answer
Converting direction to Vector2 2 Answers
Making a character move automatically in one direction. 2 Answers
Move projectile in a specific direction 0 Answers
Character facing joystick direction 1 Answer