Question by
$$anonymous$$ · Jun 21, 2016 at 08:15 PM ·
cameraraycast3rd person controller
3rd person shooter- fire at where crosshairs are pointing to
In the my game, I want the player to place a target gameobject where the crosshairs on the screen(In the center) are pointing. I've tried many different things, but none of them seem to work properly. What should I do? I just need an example of a method that would work for my purposes. Thank you.
Here is some code:
GameObject target = gameObject.transform.FindChild("target").gameObject;
float targetz = 20.0f;
RaycastHit hit;
Ray ray = gameObject.GetComponent<Camera>().ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 1.0f));
if (Physics.Raycast(ray, out hit)) {
Transform objectHit = hit.transform;
//target.transform.position = objectHit.position;
//print("got raycast hit");
Vector3 localpos = gameObject.transform.InverseTransformDirection(objectHit.position);
targetz = localpos.magnitude;
//print(gameObject.transform.InverseTransformDirection(objectHit.position).magnitude);
}
target.transform.localPosition = new Vector3(0,0,targetz);
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612083410im_/https://answers.unity.com/themes/thub/images/avi.jpg)