Unity 3D – Drag to Rotate GameObject
1. Create a Cube, assign RotateObject.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | var clickPos : Vector2; var offsetPos : Vector2; var divider = 80; function Start() { clickPos = Vector2(0,0); offsetPos = Vector2(0,0); } function Update () { offsetPos = Vector2(0,0); if (Input.GetKeyDown(leftClick())) { clickPos = mouseXY(); } if (Input.GetKey(leftClick())) { offsetPos = clickPos - mouseXY(); } // Rotate the GameObject transform.Rotate(Vector3(-(offsetPos.y/divider),offsetPos.x/divider,0.0), Space.World); } // Debug Code: Prints the current mouse position function OnGUI () { /*GUI.Label(Rect(10,350,200,100), "mouse X = " + Input.mousePosition.x); GUI.Label(Rect(10,370,200,100), "mouse Y = " + Input.mousePosition.y); GUI.Label(Rect(120,350,200,100), "click X = " + clickPos.x); GUI.Label(Rect(120,370,200,100), "click Y = " + clickPos.y); GUI.Label(Rect(210,350,200,100), "offset X = " + offsetPos.x); GUI.Label(Rect(210,370,200,100), "offset Y = " + offsetPos.y);*/ } // Return true when left mouse is clicked or hold function leftClick() { return KeyCode.Mouse0; } //Immediate location of the mouse function mouseXY() { return Vector2(Input.mousePosition.x, Input.mousePosition.y); } //Immediate location of the mouse's X coordinate function mouseX() { return Input.mousePosition.x; } //Immediate location of the mouse's Y coordinate function mouseY() { return Input.mousePosition.y; } |