- Home /
Proper way to handle mouse raycast
Seeking for a right way to write handlers for mouse events - over some/lclick/rclick, etc. So i wrote a raycaster
MouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(MouseRay, out MouseHit)){
// ???
}
and now I dont sure how I need to handle events on different object to make code structure right. Hitting different objects required different behavior, which exists in its class. Simplest way is something like "is-a" switch condition ( pseudo code )
if( hit is Terrain )
if ( RightMouseClicked )
Player.MoveTo( position )
else if( hit is Enemy )
if( RightMouseClicked )
Player.MoveTo( Enemy.position )
else
Player.Attack( Enemy ) // pew pew
...
But it looks not very incapsulated. On the other hand most incapsulated version having own raycaster on even trigger object, and thats stupid ofc. I see a compromise like some MouseTrigger interface realization or own method and it will be looks like
if( Hit.GetComponent<MouseHandler>() != null )
Hit.Hit.GetComponent<MouseHandler>().OnRaycastHit();
But thats further reasoning about it all makes me think that I making those things much complicated than they should be and Imissing some existing solution for same problems, so im here. Any ideas, examples or standarts please? Thanks
Answer by Vega4Life · Dec 09, 2018 at 04:29 PM
I tend to follow the rule set that its the clicked objects job to determine what it does when it's clicked. (Event driven OOP). Thus, I don't like raycasting here then having some crazy switches or if statements.
Here is a simple idea:
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// Placed on a cube. Click to change its color
/// Requires - Event System in scene AND Physics RayCaster on camera
/// </summary>
public class ColorChange : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
// eventData can tell you if it was left or right click
Renderer renderer = GetComponent<MeshRenderer>();
renderer.material.color = Color.red;
}
}
Pretty straightforward. Let's the clicked object decide all the things.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Initialising List array for use in a custom Editor 1 Answer
Check different collisions 1 Answer
Flip over an object (smooth transition) 3 Answers