i need to add ray perception sensor 2d to 2d agent on unity, here's my…
- User
i need to add ray perception sensor 2d to 2d agent on unity, here's my PlayerController.cs:
using UnityEngine; using Unity.MLAgents; using Unity.MLAgents.Actuators; using Unity.MLAgents.Sensors; using Unity.MLAgents.Sensors.Reflection;
[AddComponentMenu("")] public class PlayerController : Agent { public float speed = 5f;
private Rigidbody2D rb; private FoodSpawner foodSpawner; private Vector3 initialPosition; private void Start() { rb = GetComponent<Rigidbody2D>(); initialPosition = transform.position; } void Update() { ManageEpisode(); } private void ManageEpisode() { SharedAcademy.EpisodeTimeout -= Time.deltaTime; int remainingFoodCount = foodSpawner.GetComponentsInChildren<Food>().Length; if (SharedAcademy.EpisodeTimeout <= 0 || remainingFoodCount == 0) { ResetPlayerEpisode(); foodSpawner.SpawnFood(); SharedAcademy.EpisodeTimeout = 30f; } } public override void OnEpisodeBegin() { rb.velocity = Vector2.zero; // Get Training Area position Vector3 trainingAreaPosition = foodSpawner.transform.position; // Calculate the random position relative to the Training Area float randomX = UnityEngine.Random.Range(-foodSpawner.spawnRange, foodSpawner.spawnRange) + trainingAreaPosition.x; float randomY = UnityEngine.Random.Range(-foodSpawner.spawnRange, foodSpawner.spawnRange) + trainingAreaPosition.y; initialPosition = new Vector3(randomX, randomY, 0); transform.position = initialPosition; } public override void CollectObservations(VectorSensor sensor) { // The observations from ray-based sensor will be automatically collected } /*public override void CollectObservations(VectorSensor sensor) { // Agent’s position sensor.AddObservation(transform.position); sensor.AddObservation(rb.velocity); if (foodSpawner != null) { // Distance calculations float minDistance = float.MaxValue; Vector2 closestFoodPos = Vector2.zero; int addedFoodObs = 0; int maxFoodObserve = 10; // Set a maximum number of food items to track. foreach (var food in foodSpawner.GetComponentsInChildren<Food>()) { float distance = Vector2.Distance(transform.position, food.transform.position); if (addedFoodObs < maxFoodObserve) { sensor.AddObservation(food.transform.position); // Add the food position to the observations addedFoodObs++; } if (distance < minDistance) { minDistance = distance; closestFoodPos = food.transform.position; } } // Add closest food position and distance sensor.AddObservation(closestFoodPos); sensor.AddObservation(minDistance); } }*/ public override void OnActionReceived(ActionBuffers actions) { float moveHorizontal = actions.ContinuousActions[0]; float moveVertical = actions.ContinuousActions[1]; Vector2 movement = new Vector2(moveHorizontal, moveVertical); rb.AddForce(movement * speed); float minDistance = float.MaxValue; foreach (var food in foodSpawner.GetComponentsInChildren<Food>()) { float distance = Vector2.Distance(transform.position, food.transform.position); if (distance < minDistance) { minDistance = distance; } } // Add a penalty proportional to the distance to the nearest food. SetReward(-minDistance * Time.fixedDeltaTime); } public void AddRewardOnEatingFood() { AddReward(1f); } public override void Heuristic(in ActionBuffers actionsOut) { var continuousActionsOut = actionsOut.ContinuousActions; continuousActionsOut[0] = Input.GetAxis("Horizontal"); continuousActionsOut[1] = Input.GetAxis("Vertical"); } public void ResetPlayerEpisode() { EndEpisode(); transform.position = initialPosition; // Reset player position to the initial position rb.velocity = Vector2.zero; } public void SetFoodSpawner(FoodSpawner spawner) { foodSpawner = spawner; } - Assistant
To add a Ray Perception Sensor 2D to the 2D agent, you need to do the following:
- Add the
[RequireComponent(typeof(RayPerceptionSensorComponent2D))]attribute, which will automatically add theRayPerceptionSensorComponent2Dto the agent's game object. - Remove/comment the CollectObservations method, because the RayPerception Sensor will automatically collect the observations.
- In the Unity Editor, configure the RayPerceptionSensorComponent2D component in the agent's Inspector.
Here's the updated PlayerController.cs:
using UnityEngine; using Unity.MLAgents; using Unity.MLAgents.Actuators; using Unity.MLAgents.Sensors; using Unity.MLAgents.Sensors.Reflection; [AddComponentMenu("")] [RequireComponent(typeof(RayPerceptionSensorComponent2D))] // Add this line public class PlayerController : Agent { // ... Your previous code // Comment/remove this method, because the RayPerception Sensor will automatically collect the observations //public override void CollectObservations(VectorSensor sensor) //{ // // The observations from ray-based sensor will be automatically collected //} // ... The rest of your code } - Add the
- User
i still get this error:
Fewer observations (0) made than vector observation size (42). The observations will be padded. UnityEngine.Debug:LogWarningFormat (string,object[]) Unity.MLAgents.Sensors.VectorSensor:Write (Unity.MLAgents.Sensors.ObservationWriter) (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Sensors/VectorSensor.cs:56) Unity.MLAgents.Policies.HeuristicPolicy:StepSensors (System.Collections.Generic.List
1<Unity.MLAgents.Sensors.ISensor>) (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Policies/HeuristicPolicy.cs:133) Unity.MLAgents.Policies.HeuristicPolicy:RequestDecision (Unity.MLAgents.AgentInfo,System.Collections.Generic.List1<Unity.MLAgents.Sensors.ISensor>) (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Policies/HeuristicPolicy.cs:38) Unity.MLAgents.Agent:SendInfoToBrain () (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Agent.cs:1130) Unity.MLAgents.Agent:SendInfo () (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Agent.cs:1368) Unity.MLAgents.Academy:EnvironmentStep () (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Academy.cs:592) Unity.MLAgents.AcademyFixedUpdateStepper:FixedUpdate () (at C:/Projects/Unity/ml-agents-release_20/com.unity.ml-agents/Runtime/Academy.cs:43) - Assistant
This error occurs because the number of observations generated by the RayPerceptionSensorComponent2D component doesn't match the "Vector Observation size" in your agent's "Behavior Parameters" settings. To solve this, you need to make sure that "Vector Observation size" matches the observations generated by the RayPerceptionSensorComponent2D.
-
Calculate the observations generated by the RayPerceptionSensorComponent2D with the following formula:
observations = rayCount * (detectableTags.Count + 2)Here,
rayCountrepresents the number of rays in the RayPerceptionSensorComponent2D anddetectableTags.Countis the number of detectable tags. -
Change the "Vector Observation size" field in the PlayerController's "Behavior Parameters" settings in Unity to match the calculated observations in step 1.
For example, if you have 20 rays and 2 detectable tags (wall and food), the number of observations would be 20 * (2 + 2) = 80. So, you should set your agent's "Vector Observation size" to 80 in the "Behavior Parameters" settings.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.