Skip to content

Instantly share code, notes, and snippets.

@nebadon2025
Forked from HilariousCow/InteractionRaycaster.cs
Created October 15, 2023 23:29
Show Gist options
  • Save nebadon2025/a808fa0b13c552cc5c42982e03334894 to your computer and use it in GitHub Desktop.
Save nebadon2025/a808fa0b13c552cc5c42982e03334894 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.
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++;
}
}
}
}
@nebadon2025
Copy link
Author

nebadon2025 commented Oct 15, 2023

Make a new Layer for only things you to be raycasted and set this script Event Mask to only that layer then it should work! This script is such a life safer, hopefully this comment helps someone else who finds it! Thanks @HilariousCow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment