- Home /
Need help undersanding this code
I'm no good at trigonometry, I'm having trouble understanding some of the lines in this code
#pragma strict
private var baseAngle = 0.0;
function OnMouseDown() {
var dir = Camera.main.WorldToScreenPoint(transform.position);
dir = Input.mousePosition - dir;
baseAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
//stops it resetting position
baseAngle -= Mathf.Atan2(transform.right.y, transform.right.x) * Mathf.Rad2Deg;
}
function OnMouseDrag() {
var dir = Camera.main.WorldToScreenPoint(transform.position);
dir = Input.mousePosition - dir;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - baseAngle;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
Answer by perchik · Mar 06, 2014 at 05:44 PM
So. OnMouseDown()
first we figure out the 2D screen space point, that corresponds to where this object is on the camera. (`var dir = Camera.main.WorldToScreenPoint(transform.position);`
Then, we get the vector from the mouse's current position to that screen position. ( dir = Input.mousePosition - dir;
)
Next, we calculate the angle, in degrees, that the vector represents. I think it's the angle from horizontal. (`baseAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;`)
After that, baseAngle
is adjusted by the angle formed between this objects transform.right and the horizontal.
Now. OnMouseDrag(), while the mouse is being dragged Get the vector from the mouse position to the object position again ( var dir = Camera.main.WorldToScreenPoint(transform.position); dir = Input.mousePosition - dir;
)
Then we calculate the angle that we need to rotate ('var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - baseAngle;')
Finally, we rotate this object: ('transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);')
All in all, I'm a little fuzzy on the outcome, but I'm pretty sure that if you click and drag on an object with this script, it rotates to face the mouse in 2D
perchik
sorry for the late reply, thank you for explaining this code, it helped a lot
@graviton - the official way to thank someone for helping you is to vote up, or accept, their answer. If the answer is the correct one, click the tick button.
Your answer
Follow this Question
Related Questions
Help understanding transform 1 Answer
How to rotate an object by its pivot in script 3 Answers
click to move workig script!! but pls help with rotation!! :( 1 Answer
Anima 2D Bone not rotating with mouse properly 0 Answers
Mouse Orbit snapping issues 0 Answers