- Home /
interacting with the object in the direction of the crosshair,unity crosshair do not interact with the object in the direction it is facing
As in the internet cafe simulator, how can I make it interact with the corshair in the direction it looks at? I tried to look int but I didn't know how to search
Answer by Llama_w_2Ls · Aug 18, 2020 at 04:07 PM
To interact with objects that your crosshair is looking at (assuming that your crosshair is always directly in the center of your camera) you can use a raycast that points from your crosshair to the direction that youre looking at. Just make sure that the objects you want to interact with have colliders for this example:
public Camera Cam;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
InteractWithObjects();
}
}
void InteractWithObjects()
{
RaycastHit hit; //Create a raycast called 'hit'
// Fires a raycast from the camera to the camera's forward position and outputs the data of what it hit in the 'hit' variable
if (Physics.Raycast(Cam.transform.position ,Cam.transform.forward, out hit)) //If i hit something:
{
Debug.Log(hit.collider.gameObject.name); //Display the object's name
Debug.Log(hit.distance); //Display the objects distance from the camera
hit.collider.gameObject.GetComponent<Rigidbody>().AddForce(Cam.transform.forward * 1000f); //Adds a forward force to the object within the crosshair's direction
}
}
There are multiple possibilities that you could accomplish using a raycast. If this isnt what you were looking for then im sorry, but maybe you could also try the event system to check if the crosshair is hovering over an object. @aliemredoser2004