webik150

Rotating2D

Sep 13th, 2016
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | None | 0 0
  1. //Rotating transform to look at position in 2D
  2. //There is no need to license for 3 lines of code I hope
  3. //NOTE: This probably isn't the best solution performance-wise. It works pretty well tho.
  4.  
  5. void Update(){
  6.     float rotationSpeed = 50; //If you want it to be instant, delete rotationSpeed and Time.deltaTime. Not tested, but should work.
  7.     Vector3 pointInSpaceAroundWhichIWantToRotate; //Possibly the position of the body of your character.
  8.     Vector2 diff = MousePosition2D () - (Vector2)transform.position;
  9.     float angle = Vector2.Angle (transform.up, diff);
  10.     Vector3 vec = Vector3.Cross (transform.up, diff);           //We need to determine the direction of diff. "transform.up" should be the way your character faces.
  11.     if (vec.z > 0) {
  12.         Char.head.transform.RotateAround (pointInSpaceAroundWhichIWantToRotate, Vector3.forward, angle * rotationSpeed * Time.deltaTime);
  13.     } else {
  14.         Char.head.transform.RotateAround (pointInSpaceAroundWhichIWantToRotate, Vector3.forward, -angle * rotationSpeed * Time.deltaTime);
  15.     }
  16. }
  17.  
  18. //NOTE: I use perspective camera in my 2D game, so I have to set the z position to 10. If you use ortographic, you don't have to do that.
  19. Vector2 MousePosition2D(){
  20.         Vector3 mousePos = Input.mousePosition;
  21.         mousePos.z = 10;
  22.         return Camera.main.ScreenToWorldPoint (mousePos);
  23. }
Advertisement
Add Comment
Please, Sign In to add comment