forked from TouchScript/TouchScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProjectionUtils.cs
More file actions
47 lines (42 loc) · 1.88 KB
/
Copy pathProjectionUtils.cs
File metadata and controls
47 lines (42 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using UnityEngine;
namespace TouchScript.Utils
{
/// <summary>
/// Projection utils.
/// </summary>
public static class ProjectionUtils
{
/// <summary>
/// Projects a screen point to a plane from a camera's point of view.
/// </summary>
/// <param name="position">Screen point.</param>
/// <param name="camera">The camera.</param>
/// <param name="projectionPlane">Projection plane.</param>
/// <returns>Projected point on the plane in World coordinates.</returns>
public static Vector3 CameraToPlaneProjection(Vector2 position, Camera camera, Plane projectionPlane)
{
var distance = 0f;
var ray = camera.ScreenPointToRay(position);
var result = projectionPlane.Raycast(ray, out distance);
if (!result && distance == 0f) return -projectionPlane.normal * projectionPlane.GetDistanceToPoint(Vector3.zero); // perpendicular to the screen
return ray.origin + ray.direction * distance;
}
/// <summary>
/// Projects a screen point to a plane using parallel projection.
/// </summary>
/// <param name="position">Screen point.</param>
/// <param name="projectionPlane">Projection plane.</param>
/// <returns>Projected point on the plane in World coordinates.</returns>
public static Vector3 ScreenToPlaneProjection(Vector2 position, Plane projectionPlane)
{
var distance = 0f;
var ray = new Ray(position, Vector3.forward);
var result = projectionPlane.Raycast(ray, out distance);
if (!result && distance == 0f) return -projectionPlane.normal * projectionPlane.GetDistanceToPoint(Vector3.zero); // perpendicular to the screen
return ray.origin + new Vector3(0, 0, distance);
}
}
}