Last active
October 15, 2023 23:29
-
-
Save HilariousCow/f3c5502164d0caa6c0eeb03e1ff677b2 to your computer and use it in GitHub Desktop.
If you are finding that PhysicsRaycaster isn't working when you use Cursor.lockstate (i.e. an FPS game), use this instead.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine.EventSystems; | |
//I used ILSpy on the Unity UI dll to copy out the Physicsraycaster code and fix where the ray eminates from (in this case, always the center of the screen) | |
public class InteractionRaycaster : PhysicsRaycaster { | |
[Range(0.0f, 0.5f)] | |
public float RayRadius; | |
public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList) | |
{ | |
if (this.eventCamera == null) | |
{ | |
return; | |
} | |
Ray ray = this.eventCamera.ScreenPointToRay(new Vector2(Screen.width / 2f, Screen.height/2f));//this used to be the event position, but when the cursor is locked, that becomes -1,-1 so i fixed it | |
float distance = this.eventCamera.farClipPlane - this.eventCamera.nearClipPlane; | |
RaycastHit[] array = Physics.SphereCastAll(ray, RayRadius, distance, this.finalEventMask); | |
if (array.Length > 1) | |
{ | |
Array.Sort<RaycastHit>(array, (RaycastHit r1, RaycastHit r2) => r1.distance.CompareTo(r2.distance)); | |
} | |
if (array.Length != 0) | |
{ | |
int i = 0; | |
int num2 = array.Length; | |
while (i < num2) | |
{ | |
RaycastResult item = new RaycastResult | |
{ | |
gameObject = array[i].collider.gameObject, | |
module = this, | |
distance = array[i].distance, | |
worldPosition = array[i].point, | |
worldNormal = array[i].normal, | |
screenPosition = eventData.position, | |
index = (float)resultAppendList.Count, | |
sortingLayer = 0, | |
sortingOrder = 0 | |
}; | |
resultAppendList.Add(item); | |
i++; | |
} | |
} | |
} | |
} |
Interestingly if I have it print to console what its raycasting I can see that it is working and hitting the correct object, but its not triggering the event, but using a fixed camera with a physics raycaster on the same object does trigger the event, what is going wrong?
I figured it out! I had to make a new Layer for only things I wanted to be raycasted and set this script Event Mask to only that layer then it started working! This script is such a life safer, hopefully this comment helps someone else who finds it!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there no way to use Event Triggers on objects with this? or does that require a Physics Raycaster, this is driving me nuts I just want to trigger even triggers and can't seem to do it in First Person cursor locked state.