I’ve been trying to make a FirstPerson version of the PhysicsRaycaster. The idea is to use the Unity event system with objects in the world, so a first-person character can interact with them.
So I thought, simple enough, just alter the PhysicsRaycaster to cast from the middle of the screen, instead of from the mouse-location.
// Code from PhysicsRaycaster.cs
public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
{
if (eventCamera == null) return;
//var ray = eventCamera.ScreenPointToRay(eventData.position); //old code
var ray = eventCamera.ViewportPointToRay(new Vector3(.5f, .5f, 0f)); //raycast from the center
...
Add this to the first-person camera, and it works as expected. However, then I wanted to use “Screen.lockCursor = true;” to lock the cursor, then suddenly it didn’t work any more. The object didn’t get the proper events any more.
Event I found they didn’t get properly:
“Pointer Enter”. These were fired only when the pointer was on the object and I click (click-down).
“Pointer Exit”. These were only fires when I first got the “Pointer Enter” event in the way described above, and I then click outside the object.
“Drag”. Never fired.
“PointerDown”, “PointerUp” and “PointerClick” seem to work fine. I haven’t tested other events yet.
All these events work perfectly if I don’t use “lockCursor”, even with my altered code that raycasts from the middle of the screen.
What’s wrong?
I logged the eventData coming as a parameter in the Raycast method to see what’s going wrong. It seems its ‘pointerEnter’ value isn’t set properly when “lockCursor = true”. It’s only set when I click (mouse button down), which looks like the reason for it not working properly.
However, I couldn’t find why it’s not set properly. I’ve been looking in the source code, but couldn’t find anything. I’ll continue searching, but perhaps anyone here can help?
Note: I’m using https://github.com/tenpn/unity3d-ui to search through the source code, since Bitbucket doesn’t seem to have a proper search function to search in the files. I’m trying to track where the eventData’s variables are set, but haven’t found anything that could cause my problem yet. I also searched for the use of “lockCursor” but nothing came up.
Note 2: The idea is also to make a first person version of the GraphicsRaycaster for world-space canvases. This however has the same error, and I’m currently focussing on trying to fix the PhysicsRaycaster, I’m guessing fixing one will fix the other.
Thanks!