I'm currently following tutorials on Youtube to learn howto use Unity. My code runs perfectly as per the tutorial, but i just have some questions regarding the code, with regards to screenToWorldPoint & viewportToWorldPoint.
The purpose of the code is for a 2D platformer, where the character's arms will rotate and face where the mouse cursor is.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArmRotation : MonoBehaviour {
public int rotationOffset = 0;
// Update is called once per frame
void Update () {
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; //Gets the difference between
difference.Normalize(); //Normalizing the vector
float rotateZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotateZ + rotationOffset);
}
}
I've done some googling and am aware of the difference between screenToWorldPoint and viewportToWorldPoint as per the answer here https://answers.unity.com/questions/168156/screen-vs-viewport-what-is-the-difference.html
Where
- Screen: from [0,0] to [Screen.width, Screen.height]
- Viewport: from [0,0] to [1,1]
Questions:
Why do we have to calculate the difference between the position of the mouse cursor and the position of the character's arm instead of just setting the following: .
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition);
I've tried setting it to the position of the mouse cursor instead of using the difference between the arm & the cursor and while the code still works and the arm is still able to rotate, it is a little "off" from the direction of the cursor. E.g A little higher than where the cursor is. Why does using the difference solve this issue?
Why do we call difference.Normalize() ? To my understanding, Normalize returns a vector between 0 & 1.However, Mathf.Atan2 returns the angle in radians whose Tan is calculated by y/x. As such, calling Normalize and returning a vector to a value between 0 & 1 makes no difference because the value calculated will be the same between a un-normalised and normalised vector since the proportions are the same?
When i use ViewportToWorldPoint instead of ScreenToWorldPoint, i do not use Normalize because to my understanding, the Vector returned by ViewportToWorldPoint should already be within 0 & 1, hance we do not have to normalise it. However, when i test the code out in play mode,the arm barely rotates. Why is this so?
I would appreciate any help or pointers in the right directions.
Thanks!
EDIT: I had a look at the manual and realise that Normalize() returns a vector with the same direction, but magnitude 1, but i'm still just as confused