I know that there are some posts out there that kind-of cover this, but I'm new to Unity and I'm working on a FPS prototype trying to figure out how to have the gun always point to the cursor in the center of the screen.
There are a few good scripts out there, however I do not know where to place them, or if they are necessarily the best thing as far as performance is concerned (using Ray casting and getting the distance of the nearest object at the position of the cross-hairs)
There are two scripts I have found in the forums below. Which is better to use for performance, and where do I actually place the script?, on What GameObject?
var gun : GameObject = (the gun);
var target : Vector3;
var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0)); // This is assuming your crosshair is in the middle of the screen
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
target = hit.point; // We hit something, aim at that
} else {
target = ray.GetPoint(100); // Distance we're aiming at, could be something else
}
gun.transform.LookAt(hit.point);
And This one:
var hit : RaycastHit;
var Gun : GameObject;
var range = 100.0;
var crosshairTexture: Texture2D;
var position : Rect;
function Start ()
{
position = Rect ((Screen.width - crosshairTexture.width)/2, (Screen.hight - crosshairTexture.hight)/2 crosshairTexture.width, crosshairTecture.hight);
}
function OnGUI ()
{
GUI.DrawTexture (position, crosshairTexture);
}
function Update ()
{
var ray = camera.ViewportPointToRay
(Vector3(0.5,0.5,0));
Debug.DrawRay (ray.origin, ray.direction *
range, Color.green);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit))
{Gun.transform.LookAt(hit.point);}
else
{Gun.transform.LookAt(GetPoint(range));}
}
Would the best solution be to translate a point in the screen to a world point, and then parent the gun's aim and cross-hair element to the mouse's position? Any help would be amazing, thank you so much!