0
\$\begingroup\$

Is there any way to cast a ray from an object using the mouse position as the direction for the ray? I´ve been looking for a while but I can´t find something like that anywhere, so if anyone could help with this it would be great.

I´m using kind of a top view, you can see how here: Perspective

And what I want to do is set a empty game object on top of the character to act as the origin for the ray, then when I press a key the mouse is unlocked and an area appears, here´s how that looks: Area

And I want to use the position where the mouse clicks to be the direction of the ray.

\$\endgroup\$
0

1 Answer 1

0
\$\begingroup\$

First you want to convert the position of the mouse on screen to a position in 3D world space. That involves a raycast from the camera's perspective to find what's under your mouse cursor. So first we'll form that ray:

var camera = Camera.main;

var screenRay = camera.ScreenPointToRay(Input.MousePosition);

Now depending on your needs, you might want to...

  • Cast this ray into your physics scene, stopping at the closest solid collider [in selected layers]
if(Physics.Raycast(screenRay, out RaycastHit hit, float.positiveInfinity, selectionLayers)) {
    selectedPoint = hit.point;
    // ...
  • Cast this ray against a specific collider representing your selection region
if(selectionZoneCollider.Raycast(screenRay, out RaycastHit hit, float.positiveInfinity)) {
    selectedPoint = hit.point;
    // ...
  • Cast this ray against an infinite plane representing your ground/aiming level
if(selectionPlane.Raycast(screenRay, out float distance)) {
    selectedPoint = screenRay.GetPoint(distance);
    // ...

Whichever way you go, now you have a position in world space to aim toward. You might still want to shift that point (eg. if it's a point on your ground plane, you might want to lift it up on the y-axis to a position at eye/gun level).

Then you can form a ray toward that point from your origin transform by simply writing:

var originToSelectionRay = new Ray(originTransform.position, selectedPoint - originTransform.position);
\$\endgroup\$
1
  • \$\begingroup\$ Thank you, that´s exactly what I needed \$\endgroup\$
    – ElCoru
    Mar 16, 2020 at 19:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .