Janooba
New member
I've created an override for the Interact script to allow the user to interact with items solely by using a center-of-screen raycast. This greatly reduces complexity when working primarily with First Person view-mode. I'd like to see some form of this implemented into the base code, as it's a pretty standard operation for first person shooters.
How is this different from the standard "Raycast" option?
The raycast option works similar, but will shoot a ray from an arbitrary defined, static offset from the player's origin. Although there is an option to change direction depending on the view direction, it won't take into account crouch, or any other changes to the camera's position, and so it will never be quite lined up.
ScreenInteract.cs
Usage:
How is this different from the standard "Raycast" option?
The raycast option works similar, but will shoot a ray from an arbitrary defined, static offset from the player's origin. Although there is an option to change direction depending on the view direction, it won't take into account crouch, or any other changes to the camera's position, and so it will never be quite lined up.
ScreenInteract.cs
C#:
using Opsive.UltimateCharacterController.Character.Abilities;
using UnityEngine;
/// <summary>
/// Interacts with another object within the scene. The object that the ability interacts with must have the Interact component added to it.
/// Uses the custom cast to detect if the player is looking directly at the object.
/// </summary>
[DefaultStartType(AbilityStartType.ButtonDown)]
[DefaultInputName("Action")]
[DefaultAbilityIndex(9)]
[DefaultAllowPositionalInput(false)]
[DefaultAllowRotationalInput(false)]
[AllowMultipleAbilityTypes]
public class ScreenInteract : Interact
{
/// <summary>
/// Called when the ablity is tried to be started. If false is returned then the ability will not be started.
/// </summary>
/// <returns>True if the ability can be started.</returns>
public override bool CanStartAbility()
{
if (DetectUsingRaycast())
return base.CanStartAbility();
return false;
}
private bool DetectUsingRaycast()
{
// Use a raycast to detect if the character is looking at the object.
if (Physics.Raycast(m_LookSource.Transform.position, m_LookSource.Transform.forward, out m_RaycastResult, m_CastDistance, m_DetectLayers, QueryTriggerInteraction.Collide))
{
var hitObject = m_RaycastResult.collider.gameObject;
if (ValidateObject(hitObject, false))
{
m_DetectedObject = hitObject;
return true;
}
}
return false;
}
}
Usage:
- Throw this script anywhere in your project, and add the ScreenInteract ability to your character.
- Add the "Screen Interact" ability to your character
- Set the Object Detection to Customcast