Game in 2D on the Unity engine. My hierarchy structure is like this - EmptyObject, named…
- User
Game in 2D on the Unity engine. My hierarchy structure is like this - EmptyObject, named TrainingArea, script TrainingArea.cs is connected to it. I have copied my TrainingArea many times, and while training, it seems to me that when other agents eat their food, it disappears from the first agent. I may be wrong and it may not be. But I know for sure that the food disappears by itself from the very first agent. Sometimes a player in the TrainingArea will spawn not 10 food, but 1 or 3. In addition, other players in their TrainingArea cannot eat their own food. But when trying to eat some food, it may be lost from the first player in the first TrainingArea. In general, the problem may be in the food array. I want each TrainingArea and their Player or Food objects to be independent of other TrainingAreas.
here’s my TrainingArea.cs: using UnityEngine; using System.Collections.Generic;
public class TrainingArea : MonoBehaviour { [SerializeField] private GameObject playerPrefab; [SerializeField] private GameObject foodPrefab; [SerializeField] private int numberOfFoods = 10; [SerializeField] private float spawnRadius = 5.0f; private PlayerAgent playerAgent; private List foodInstances = new List();
private void Start() { SpawnPlayer(); SpawnFoods(); }
public void ResetArea() { ResetPlayer(); ResetFoods(); }
private void ResetPlayer() { if (playerAgent != null) { playerAgent.transform.localPosition = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), 0); } }
public void ResetFoods() { List eatenFoods = new List();
foreach (GameObject food in foodInstances) { if (food != null) { food.transform.localPosition = GetValidSpawnPosition(); } else { eatenFoods.Add(food); } }
foreach (GameObject food in eatenFoods) { Vector3 spawnPosition = GetValidSpawnPosition(); GameObject foodInstance = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform); foodInstances.Add(foodInstance); }
// Remove eaten food references from the list foodInstances.RemoveAll(food => food == null); }
private void SpawnPlayer() { Vector3 randomPosition = GetValidSpawnPosition(); GameObject playerInstance = Instantiate(playerPrefab, randomPosition + transform.position, Quaternion.identity, transform); playerAgent = playerInstance.GetComponent(); }
private void SpawnFoods() { for (int i = 0; i < numberOfFoods; i++) { Vector3 spawnPosition = GetValidSpawnPosition(); GameObject foodInstance = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform); foodInstances.Add(foodInstance); } }
private Vector3 GetValidSpawnPosition() { Vector3 spawnPosition; do { spawnPosition = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), 0); } while (playerAgent != null && Vector3.Distance(playerAgent.transform.localPosition, spawnPosition) <= 5.0f);
return spawnPosition; }
public bool AllFoodEaten() { foreach (GameObject food in foodInstances) { if (food != null) { return false; } } return true; } }
- Assistant
It seems that your issue might stem from the fact that different TrainingArea instances might be sharing the same list of food instances. For every TrainingArea, you have a list of references to food objects, and while spawning the foods in the ResetFoods method, you add new food objects to this list. You might have overlapping references in these lists, causing the food to be consumed in another TrainingArea when it is eaten in one.
To fix this issue, I would recommend making separate food instances for each TrainingArea player. Update your TrainingArea.cs script's
ResetFoodsfunction as shown below:public void ResetFoods() { List<GameObject> eatenFoods = new List<GameObject>(); // Clear any null food instances left foodInstances.RemoveAll(food => food == null); foreach (GameObject food in foodInstances) { if (food != null) { food.transform.localPosition = GetValidSpawnPosition(); } } // Spawn the remaining food instances while (foodInstances.Count < numberOfFoods) { Vector3 spawnPosition = GetValidSpawnPosition(); GameObject foodInstance = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform); foodInstances.Add(foodInstance); } } - User
The problem is that if a player from the second TrainingArea goes to the same corner that has food in the first TrainingArea, then the food will disappear in the first TrainingArea.
- Assistant
I see, this issue might be caused by the physics simulation for the whole scene picking up multiple foods and players at once when checking for overlap. You can try to address this issue by having separate PhysicsScenes for each TrainingArea. This way, the calculations for foods and players in different TrainingAreas would not interfere with each other.
- Update the
Start()method in the TrainingArea.cs class like this:
private void Start() { Physics2D.autoSimulation = false; // Disabling the autoSimulation to manually control the physics simulation SpawnPlayer(); SpawnFoods(); }- Update the
FixedUpdate()method in the PlayerAgent.cs class like this:
private void FixedUpdate() { // Manually simulate physics only for the objects within the training area this PlayerAgent belongs to PhysicsScene2D localPhysicsScene = trainingArea.gameObject.scene.GetPhysicsScene2D(); localPhysicsScene.Simulate(Time.fixedDeltaTime); episodeTime += Time.fixedDeltaTime; if (episodeTime >= maxEpisodeTime || trainingArea.AllFoodEaten()) { EndEpisode(); } } - Update the
- User
- Assistant
The issue seems to be with the
OnActionReceivedmethod in the PlayerAgent.cs script, where the OverlapCircle check is performed to determine if the player has collided with a Food object. In theUpdate()method, you're updating the transform.localPosition for the player, but the code you provided is using transform.position in the OverlapCircle method. This discrepancy could be responsible for the misalignment issue you're experiencing.To fix this, update the
OnActionReceivedmethod in your PlayerAgent.cs script, by using transform.localPosition instead of transform.position in OverlapCircle checks.public override void OnActionReceived(ActionBuffers actions) { float moveX = Mathf.Clamp(actions.ContinuousActions[0], -1, 1); float moveY = Mathf.Clamp(actions.ContinuousActions[1], -1, 1); Vector3 move = new Vector3(moveX, moveY, 0) * moveSpeed * Time.fixedDeltaTime; Vector3 newPosition = transform.localPosition + move; Collider2D collider = Physics2D.OverlapCircle(newPosition, 0.5f, LayerMask.GetMask("Wall")); if (collider == null || !collider.CompareTag("Wall")) { SetReward(-0.1f); transform.localPosition = newPosition; } Collider2D collider2 = Physics2D.OverlapCircle(transform.localPosition, 0.5f, LayerMask.GetMask("Food")); if (collider2 != null && collider2.CompareTag("Food")) { Debug.Log("OnTriggerEnter2D"); SetReward(1f); trainingArea.GetFoodInstances().Remove(collider2.gameObject); Destroy(collider2.gameObject); } } - User
you did not understand me. even if there is only one TrainingArea left on the stage, and if I move it to the right, my food will be considered eaten if it is far to the right. The same for the left, the more I move the TrainingArea to the left, the more it will be on the left, even if the sprites are displayed correctly. The same goes for top and bottom. The ideal position of the TrainingArea is 0,0,0 where everything works correctly. Fix it.
- Assistant
I apologize for the confusion. Since the issue happens when you move the TrainingArea, it likely means that the food's transform.localPosition is used in calculations instead of the actual world position. To resolve this, update the TrainingArea.cs script's
GetValidSpawnPosition()method to return the position relative to the TrainingArea.Update the
GetValidSpawnPosition()method in the TrainingArea.cs script:private Vector3 GetValidSpawnPosition() { Vector3 spawnPosition; do { spawnPosition = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), 0); } while (playerAgent != null && Vector3.Distance(playerAgent.transform.position, spawnPosition + transform.position) <= 5.0f); return spawnPosition; } - User
- Assistant
Based on the code you provided, it seems the new food positions should be calculated correctly when the episode resets. Since the issue persists, let's add some debug messages to make sure that the TrainingArea instances don't interfere with each other.
First, give unique names to each TrainingArea instance in the scene by updating the method inside the TrainingArea.cs script like this:
- User
how to check if my Ray Perception Sensor 2D is working? here's my PlayerAgent.cs:
- Assistant
To check if your Ray Perception Sensor 2D is working, you can visualize the rays being cast by the sensor in the Scene View when Unity is running in Play mode.
First, add a
RayPerceptionSensorComponent2Dcomponent to your player prefab through the Unity Editor. Configure its properties like the number of rays and their angles, ray length, etc., according to your needs.In the PlayerAgent.cs script, replace the existing
CollectObservations(VectorSensor sensor)method with the following one:public override void CollectObservations(VectorSensor sensor) { GetComponent<RayPerceptionSensorComponent2D>().CollectObservations(sensor); sensor.AddObservation(transform.localPosition); }Now, when you run the scene in the Unity editor, you should be able to see the rays being cast from the player in the Scene View. The rays are drawn as green lines originating from the player object, extending in the specified direction and with the specified length. If a ray hits an object, the line will change its color to red (for hit), yellow (if it hits a detected object), or white (if it doesn't hit anything).
- User
- Assistant
To collect the position of the player and food relative to their TrainingArea as observations, update the
CollectObservations(VectorSensor sensor)method inside the PlayerAgent.cs script:public override void CollectObservations(VectorSensor sensor) { // Adding player position relative to training area sensor.AddObservation(transform.localPosition); // Adding food positions relative to training area foreach (GameObject food in trainingArea.GetFoodInstances()) { if (food != null) sensor.AddObservation(food.transform.localPosition); else sensor.AddObservation(Vector3.zero); } }By using
transform.localPosition, we ensure that we're collecting food positions relative to their TrainingArea instead of their world positions. To account for eaten food, we add a zero vector, which will represent the absence of the food object in that slot in the list.However, keep in mind that increasing the collected observations will also increase the complexity of the agent's training process. If the food list is large, it may increase computation requirements and slow down learning. In such cases, you might consider using other approaches such as observation filters so that the agent only observes nearby foods. But for a small number of food objects in the training area, this method should work without causing issues.
- User
my neural network quickly plateaus without starting to understand how to play. I even set -reward when it hits a wall. I don’t understand what the problem is, help me assign rewards.
public override void OnActionReceived(ActionBuffers actions) { float moveX = Mathf.Clamp(actions.ContinuousActions[0], -1, 1); float moveY = Mathf.Clamp(actions.ContinuousActions[1], -1, 1); Vector3 move = new Vector3(moveX, moveY, 0) * moveSpeed * Time.fixedDeltaTime; Vector3 newPosition = transform.position + move; // Change to position instead of localPosition // Change the OverlapCircle to use transform.position (world space) instead of localPosition Collider2D collider = Physics2D.OverlapCircle(transform.position + move, 0.5f, LayerMask.GetMask("Wall")); if (collider == null || !collider.CompareTag("Wall")) { SetReward(-0.1f); transform.position = newPosition; // Change to position instead of localPosition } // Change the OverlapCircle to use transform.position (world space) instead of localPosition Collider2D collider2 = Physics2D.OverlapCircle(transform.position + move, 0.5f, LayerMask.GetMask("Food")); if (collider2 != null && collider2.CompareTag("Food")) { // Make sure the food object is part of the current TrainingArea if (trainingArea.GetFoodInstances().Contains(collider2.gameObject)) { Debug.Log("OnTriggerEnter2D"); SetReward(1f); Destroy(collider2.gameObject); } } } - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.