- Home /
Need explanation for this code
Hi all
Following is the code to fire bullet in the direction of mouse for a 2D platformer.(thanks Robertbu for the answer)
Can somebody please explain me the code from pos.z to var q? those three lines in below code? what exactly its doing
var prefab : GameObject;
function Update () {
if (Input.GetMouseButtonDown(0)) {
var pos = Input.mousePosition;
pos.z = transform.position.z - Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
var q = Quaternion.FromToRotation(Vector3.up, pos - transform.position);
var go = Instantiate(prefab, transform.position, q);
go.rigidbody.AddForce(go.transform.up * 500.0);
}
}
Thanks
Answer by robertbu · Oct 08, 2014 at 07:39 PM
pos.z = transform.position.z - Camera.main.transform.position.z;
The code I posted assumes the camera is facing positive 'z' and has rotation (0,0,0). This line of code calculates the distance from the camera plane to the object. The 'z' value of the position passed to ScreenToWorldPoint() must contain the distance when using a perspective camera. If the camera is orthographic, the code will still work, but there are other ways to do the calculation.
pos = Camera.main.ScreenToWorldPoint(pos);
This converts the screen position to a world position at the specified distance from the camera plane.
var q = Quaternion.FromToRotation(Vector3.up, pos - transform.position);
'pos - transform.position' produces a vector that would point from the current game object to pos. The FromToRotation() calculates the rotation necessary to convert a vector pointing 'up' to a vector pointing in the direction of 'pos'. This code is assuming that in the prefab, the top side is what you want to point at 'pos'. This is a bit unusual. For 3D, usually you want the front side pointing at things (so that Transform.LookAt() and Quaternion.LookRotation() work correctly).