My camera’s transform is a bit jittery/bouncy which caused inconsistent rays being created, so I came up with a “solution” in which I’m using a consistent cached value of the camera’s position rather than Camera.ScreenPointToRay. Unfortunately this doesn’t seem to work at all, I’m not able to get the Debug Log message.
Ray highlightRay = new Ray(Camera.main.GetComponent<MouseOrbitImproved>().cachedPosition + Camera.main.transform.forward, Input.mousePosition);
RaycastHit highlightHit;
int layermask10 = (1 << 11); //hit the tile layer
if (Physics.Raycast (highlightRay, out highlightHit, 30.0F, layermask10)) {
if(highlightHit.transform.tag == "Tile"){
Debug.Log("hit a tile");
}
}
I’m certain the problem is in the creation of highlightRay because replacing it with Camera.ScreenPointToRay(Input.mousePosition) produces expected behavior. What am I doing wrong with highlightRay?
A ray shoots from a point in a direction. You have your point(maybe, its hard to tell) but not your direction. Most things can be found out with a simple print or Debug.log test. For example, printing out what Input.mousePosition actually is will tell you that, although it is a Vector3, the z is 0.
You can try changing Input.mousePosition to Camera.main.transform.forward to see if that will solve your problem.
The parameters for Ray are origin and direction. Mouse position is not a direction. (and the directional vector should be normalized).
Why not just address the ‘jitter’ issue? If cachedPosition is not being lerped but just the camera position in the last frame, it will still ‘jitter’, just now with lag.
Debug raycasts with Debug.DrawRay. The main thing to remember is DrawRay dir parameter needs to have a magnitude of your ray length. e.g. :
Vector3 rayOrigin = Camera.main.GetComponent<MouseOrbitImproved>().cachedPosition;
Vector3 rayDirection = Camera.main.transform.forward;
float rayDistance = 30f;
Ray highlightRay = new Ray( rayOrigin, rayDirection);
Debug.DrawRay( rayOrigin, rayDirection * rayDistance, Color.red );
// ...
if ( Physics.Raycast( highlightRay, out highlightHit, rayDistance, layermask10 )) {
// ...
Sorry my original post wasn’t explicit enough, I want the ray to be cast towards the mouse’s position, so knowing that what should I replace Input.mousePosition with?
The only way to factor in the mouse position in world space is with ScreenToWorldPoint. But then you still have the problem of the direction. Something like
It just seems like a LOT of work to emulate something that ScreenPointToRay already does. Why is the camera jittering? How is this affecting the performance of ScreenPointToRay?