AIUNITY
AIUNITY
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
Class Definition
public class AgentController : Agent
Target Reference
public Transform target;
if(rand == 0)
{
target.localPosition = new Vector3(2.5f, 0.5f, 0);
}
11. if (rand == 0)
o If the random number is 0, the target's position is set to the right (x = 2.5).
if(rand == 1)
{
target.localPosition = new Vector3(-2.5f, 0.5f, 0);
}
12. if (rand == 1)
o If the random number is 1, the target's position is set to the left (x = -2.5).
CollectObservations()
sensor.AddObservation(transform.localPosition);
14. sensor.AddObservation(transform.localPosition);
o Adds the agent's position as an observation.
o The agent will learn to consider its position in relation to the target and obstacles.
sensor.AddObservation(target.localPosition);
15. sensor.AddObservation(target.localPosition);
o Adds the target's position as an observation.
OnActionReceived()
float speed = 2;
continuousActions[0] = Input.GetAxisRaw("Horizontal");
Collision Handling
private void OnTriggerEnter(Collider other)
if (other.CompareTag("sphere"))
24. if (other.CompareTag("sphere"))
o Checks if the agent collides with an object tagged as sphere (the target).
AddReward(1);
EndEpisode();
25. AddReward(1);
o Rewards the agent with a positive value (1) for reaching the target.
26. EndEpisode();
o Ends the current episode, signaling the environment to reset.
if (other.CompareTag("wall"))
27. if (other.CompareTag("wall"))
o Checks if the agent collides with a wall.
AddReward(-1);
EndEpisode();
28. AddReward(-1);
o Penalizes the agent with a negative reward (-1) for hitting a wall.
o Ends the episode as a failure.