- Home /
Raycasting from object to center of screen instead of camera
I'm trying to change my code to fire a raycast from a empty gameobject to the center of the screen. I'm very new to raycast so i am usure what is wrong with my code the problem becomes when i shoot the raycast from the camera to center of screen and when i zoom my camera back i cant use the object because the raycast is following the camera, how i can make that instead of the camera the raycast comes in a empty gameobject?
This is my current code :
var ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)); //i think is here the problem
if (Physics.Raycast(ray, out RaycastHit hit, interactDistance, LayerMask.GetMask("item")))
{
Interactable interactable = hit.transform.GetComponent<Interactable>();
if (interactable)
{
if (Interact)
{
anim.SetTrigger("interact");
interactable.Use(this);
}
}
}
Answer by UnityM0nk3y · Apr 02, 2021 at 08:49 PM
I use Unity 2D but it should look something like this in 3D.
Make sure this code is on the object you want to raycast from, not the camera.
Then change your code to this:
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out RaycastHit hit, interactDistance, LayerMask.GetMask("item")))
{
Interactable interactable = hit.transform.GetComponent<Interactable>();
if (interactable)
{
if (Interact)
{
anim.SetTrigger("interact");
interactable.Use(this);
}
}
}
This will make the object raycast in the direction it's facing.
Your answer
Follow this Question
Related Questions
Question regarding Raycast hitting UI button object instead of gameobject 0 Answers
First Person Controller - Problems with footstep audio being played too fast. 0 Answers
My player doesn't turn based on the mouse when it's supposed to 0 Answers
Play animation of FPS player after hitting trigger 2 Answers
How would I script text to pop up? 1 Answer