I’m trying to select bolts in a machine by clicking on them.
The bolts have a sphere-collider on them, and I cast a ray from the camera, but Physics.Raycast() always returns false.
I checked the value of mousePos, but that seems correct, and the created ray is also correct.
I tried doing it on other objects with colliders attached but Raycast() simply wont ever return true.
I feel like I must be doing something very basic wrong, but I can’t figure out what.
Also, this worked at some point, but then somehow stopped, and I have no idea why.
Does anyone have any idea?
Here’s my code:
private void Tap(InputAction.CallbackContext callback)
{
Vector3 mousePos = _pos.ReadValue<Vector2>();
RayCastNodes(mousePos);
}
private void RayCastNodes(Vector3 mousePos)
{
Ray ray = Camera.main.ScreenPointToRay(mousePos);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
for (int i = 0; i < Nodes.Length; i++)
{
if (Nodes[i].Transform == hit.collider.transform.parent)
{
SelectBolt(i);
break;
}
}
}
}
It’s not hitting anything, it’s like the raycast function just stopped working.
I went through it with breakpoints a ton of times, and the raycast always returns false.
I added just generic cubes with box-colliders that take up the entire view, and still the raycast returns false
The code you’re using to test if the raycast is working may itself be bugged. If your code moves the cube to world position zero before doing the raycast then it will fail because the physics engine won’t update the cube’s position immediately. Try manually placing the cube at world position zero.
As for your main bug - test to see if the input system is actually returning the correct screen position.
That’s what I did, I have the cube at position zero, I then do the raycast, and in my project the reycast returns zero, and in an new test project it returns true.
Somehow Raycasts don’t work in my project.
I’m gonna recreate my entire project in a new project and hope the same thing doesn’t happen.
To make it crystal clear, this is my code for the test:
using UnityEngine;
public class RaycastTest : MonoBehaviour
{
Collider testCollider;
void Start()
{
testCollider = GetComponent<Collider>();
}
void FixedUpdate()
{
RaycastHit hit;
if (testCollider.Raycast(new Ray(new Vector3(3, 0, 0), new Vector3(-1, 0, 0)), out hit, float.MaxValue))
{
Debug.Log("hit");
}
}
}
I have this script attached to a default cube at position zero, scale 1, in a new scene.
In my own project it doesn’t log anything, as the rayscast retuns false.
In a new project it returns true, and it logs “hit” every frame
Somehow I had GameObject SDK in Project Settings set to None (I guess it got changed after switching build platform) and when I set it back to PhysX, everything starts working as it should