Neodroid  0.2.0
Machine Learning Environment Prototyping Tool
Ray.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections.Generic;
3 using UnityEngine;
4 
5 namespace droid.Runtime.Prototyping.Sensors.Rays.Experimental {
11  public class Ray : MonoBehaviour {
12  List<float> _perception_buffer = new List<float>();
13  Vector3 _end_position;
14  RaycastHit _hit;
15 
25  public List<float> Perceive(float ray_distance,
26  IEnumerable<Single> ray_angles,
27  string[] detectable_objects,
28  float start_offset,
29  float end_offset) {
30  this._perception_buffer.Clear();
31  // For each ray sublist stores categorial information on detected object
32  // along with object distance.
33  foreach (var angle in ray_angles) {
34  this._end_position = this.transform.TransformDirection(PolarToCartesian(ray_distance, angle));
35  this._end_position.y = end_offset;
36  if (Application.isEditor) {
37  Debug.DrawRay(this.transform.position + new Vector3(0f, start_offset, 0f),
38  this._end_position,
39  Color.black,
40  0.01f,
41  true);
42  }
43 
44  var sub_list = new float[detectable_objects.Length + 2];
45  if (Physics.SphereCast(this.transform.position + new Vector3(0f, start_offset, 0f),
46  0.5f,
47  this._end_position,
48  out this._hit,
49  ray_distance)) {
50  for (var i = 0; i < detectable_objects.Length; i++) {
51  if (this._hit.collider.gameObject.CompareTag(detectable_objects[i])) {
52  sub_list[i] = 1;
53  sub_list[detectable_objects.Length + 1] = this._hit.distance / ray_distance;
54  break;
55  }
56  }
57  } else {
58  sub_list[detectable_objects.Length] = 1f;
59  }
60 
61  this._perception_buffer.AddRange(sub_list);
62  }
63 
64  return this._perception_buffer;
65  }
66 
70  public static Vector3 PolarToCartesian(float radius, float angle) {
71  var x = radius * Mathf.Cos(DegreeToRadian(angle));
72  var z = radius * Mathf.Sin(DegreeToRadian(angle));
73  return new Vector3(x, 0f, z);
74  }
75 
79  public static float DegreeToRadian(float degree) { return degree * Mathf.PI / 180f; }
80  }
81 }
static Vector3 PolarToCartesian(float radius, float angle)
Converts polar coordinate to cartesian coordinate.
Definition: Ray.cs:70
static float DegreeToRadian(float degree)
Converts degrees to radians.
Definition: Ray.cs:79
List< float > Perceive(float ray_distance, IEnumerable< Single > ray_angles, string[] detectable_objects, float start_offset, float end_offset)
Creates perception vector to be used as part of an observation of an agent.
Definition: Ray.cs:25
Ray perception component. Attach this to agents to enable "local perception" via the use of ray casts...
Definition: Ray.cs:11