V3.1.1 优化代码

优化可读性与规范化命名方式
This commit is contained in:
2023-06-30 18:30:12 +09:00
parent 64e477d6c2
commit cfccd12820
43 changed files with 912 additions and 1118 deletions
+83 -79
View File
@@ -1,13 +1,10 @@
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Actuators;
using System.Linq;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
using UnityEngine;
/*TODO:
√tag 攻击排他
@@ -18,17 +15,18 @@ Agent死亡时待机处理*/
public class AgentWithGun : Agent
{
public GameObject ParameterContainerObj;
public GameObject EnvironmentObj;
public GameObject EnemyContainerObj;
public GameObject SceneBlockContainerObj;
public GameObject EnvironmentUIControlObj;
public GameObject TargetControllerObj;
public GameObject parameterContainerObj;
public GameObject environmentObj;
public GameObject enemyContainerObj;
public GameObject sceneBlockContainerObj;
public GameObject environmentUIControlObj;
public GameObject targetControllerObj;
public GameObject HUDObj;
public Camera thisCam;
[Header("GetAxis() Simulate")]
public float MoveSpeed = 9.0f;
public float moveSpeed = 9.0f;
public float vX = 0f;
public float vZ = 0f;
public Vector3 thisMovement;
@@ -39,9 +37,10 @@ public class AgentWithGun : Agent
[Header("Env")]
public bool oneHotRayTag = true;
private List<float> spinRecord = new List<float>();
private bool lockMouse;
private float Damage;
private float damage;
private float fireRate;
private int enemyNum;
private bool lockCameraX;
@@ -49,6 +48,7 @@ public class AgentWithGun : Agent
// environment
private int shoot = 0;
private float lastShootTime = 0.0f;
private int enemyKillCount = 0;
private Vector3 killEnemyPosition;
@@ -59,10 +59,12 @@ public class AgentWithGun : Agent
private string myTag = "";
private float lastEnemyFacingDistance = 0f; // record last enemy facing minimum distance
private float lastTargetFacingDistance = 0f; // record last target facing minimum distance
// scripts
private RaySensors raySensors;
private CharacterController PlayerController;
private EnvironmentUIControl EnvUICon;
private CharacterController playerController;
private EnvironmentUIControl envUICon;
private ParameterContainer paramContainer;
private SceneBlockContainer blockContainer;
private EnemyContainer eneContainer;
@@ -71,13 +73,14 @@ public class AgentWithGun : Agent
private StartSeneData startSceneData;
// observation
float[] myObserve = new float[4];
float[] rayTagResult;
float[] rayTagResultOnehot;
float[] rayDisResult;
float[] targetStates;
float remainTime;
float inAreaState;
private float[] myObserve = new float[4];
private float[] rayTagResult;
private float[] rayTagResultOnehot;
private float[] rayDisResult;
private float[] targetStates;
private float remainTime;
private float inAreaState;
[System.NonSerialized] public int finishedState;
@@ -88,7 +91,8 @@ public class AgentWithGun : Agent
{
// initialize startSceneData & datas
// while GameObject StartSceneDataTransfer is exist
try {
try
{
startSceneData = GameObject.Find("StartSceneDataTransfer").GetComponent<StartSeneData>();
gamemode = startSceneData.gamemode;
}
@@ -100,18 +104,18 @@ public class AgentWithGun : Agent
}
// initialize scripts
paramContainer = ParameterContainerObj.GetComponent<ParameterContainer>();
eneContainer = EnemyContainerObj.GetComponent<EnemyContainer>();
blockContainer = SceneBlockContainerObj.GetComponent<SceneBlockContainer>();
EnvUICon = EnvironmentUIControlObj.GetComponent<EnvironmentUIControl>();
targetCon = TargetControllerObj.GetComponent<TargetController>();
paramContainer = parameterContainerObj.GetComponent<ParameterContainer>();
eneContainer = enemyContainerObj.GetComponent<EnemyContainer>();
blockContainer = sceneBlockContainerObj.GetComponent<SceneBlockContainer>();
envUICon = environmentUIControlObj.GetComponent<EnvironmentUIControl>();
targetCon = targetControllerObj.GetComponent<TargetController>();
hudController = HUDObj.GetComponent<HUDController>();
raySensors = GetComponent<RaySensors>();
PlayerController = this.transform.GetComponent<CharacterController>();
playerController = this.transform.GetComponent<CharacterController>();
// initialize Environment parameters
lockMouse = paramContainer.lockMouse;
Damage = paramContainer.Damage;
damage = paramContainer.damage;
fireRate = paramContainer.fireRate;
enemyNum = hudController.enemyNum;
lockCameraX = paramContainer.lockCameraX;
@@ -124,13 +128,13 @@ public class AgentWithGun : Agent
// ------------动作处理--------------
// moveAgent 用于模拟Input.GetAxis移动
public void moveAgent(int vertical, int horizontal)
public void MoveAgent(int vertical, int horizontal)
{
// Vector3 thisMovement;
if (horizontal != 0)//当按下按键(水平方向)
{
if (vX < MoveSpeed && vX > -MoveSpeed)//当前速度小于最大速度
if (vX < moveSpeed && vX > -moveSpeed)//当前速度小于最大速度
{
vX += (float)horizontal * acceleration;//增加加速度
}
@@ -139,13 +143,12 @@ public class AgentWithGun : Agent
//防止在一瞬间切换输入时速度仍保持不变
if ((vX * horizontal) > 0)//输入与当前速度方向同向
{
vX = (float)horizontal * MoveSpeed; //限制最大速度
vX = (float)horizontal * moveSpeed; //限制最大速度
}
else
{
vX += (float)horizontal * acceleration;//增加加速度
}
}
}
else
@@ -162,7 +165,7 @@ public class AgentWithGun : Agent
if (vertical != 0)//当按下按键(垂直方向)
{
if (vZ < MoveSpeed && vZ > -MoveSpeed)//当前速度小于最大速度
if (vZ < moveSpeed && vZ > -moveSpeed)//当前速度小于最大速度
{
vZ += (float)vertical * acceleration;//增加加速度
}
@@ -170,7 +173,7 @@ public class AgentWithGun : Agent
{
if ((vZ * vertical) > 0)//输入与当前速度方向同向
{
vZ = (float)vertical * MoveSpeed; //限制最大速度
vZ = (float)vertical * moveSpeed; //限制最大速度
}
else
{
@@ -192,17 +195,17 @@ public class AgentWithGun : Agent
thisMovement = (transform.forward * vZ + transform.right * vX);
//PlayerController下的.Move为实现物体运动的函数
//Move()括号内放入一个Vector3类型的量,本例中为Player_Move
if (thisMovement.magnitude > MoveSpeed)
if (thisMovement.magnitude > moveSpeed)
{
thisMovement = thisMovement.normalized * MoveSpeed;
thisMovement = thisMovement.normalized * moveSpeed;
}
PlayerController.Move(thisMovement * Time.deltaTime);
playerController.Move(thisMovement * Time.deltaTime);
// update Key Viewer
}
// ------------动作处理--------------
// cameraControl 用于控制Agent视角转动
public void cameraControl(float Mouse_X, float Mouse_Y)
public void CameraControl(float Mouse_X, float Mouse_Y)
{
//Mouse_X = Input.GetAxis("Mouse X") * MouseSensitivity * Time.deltaTime;
//Debug.Log(Input.GetAxis("Mouse X"));
@@ -224,7 +227,6 @@ public class AgentWithGun : Agent
//limit UP DOWN between -90 -> 90
yRotation = Mathf.Clamp(yRotation, -90f, 90f);
//相机左右旋转时,是以Y轴为中心旋转的,上下旋转时,是以X轴为中心旋转的
transform.Rotate(Vector3.up * Mouse_X);
//Vector3.up相当于Vector3(0,1,0),CameraRotation.Rotate(Vector3.up * Mouse_X)相当于使CameraRotation对象绕y轴旋转Mouse_X个单位
@@ -240,14 +242,14 @@ public class AgentWithGun : Agent
}
// GotKill 获得击杀时用于被呼出
public void killRecord(Vector3 thiskillEnemyPosition)
public void KillRecord(Vector3 thiskillEnemyPosition)
{
enemyKillCount += 1;
killEnemyPosition = thiskillEnemyPosition;
}
// check gun is ready to shoot
bool gunReady()
private bool GunReady()
{
if ((Time.time - lastShootTime) >= fireRate)
{
@@ -260,7 +262,7 @@ public class AgentWithGun : Agent
}
// ballistic 射击弹道处理,并返回获得reward
float ballistic()
private float Ballistic()
{
Vector3 point = new Vector3(thisCam.pixelWidth / 2, thisCam.pixelHeight / 2, 0);//发射位置
Ray ray = thisCam.ScreenPointToRay(point);
@@ -269,7 +271,6 @@ public class AgentWithGun : Agent
//按下鼠标左键
if (shoot != 0 && gunReadyToggle == true)
{
lastShootTime = Time.time;
if (Physics.Raycast(ray, out hit, 100))
{
@@ -277,9 +278,9 @@ public class AgentWithGun : Agent
{
// kill enemy
GameObject gotHitObj = hit.transform.gameObject;//获取受到Ray撞击的对象
gotHitObj.GetComponent<states>().ReactToHit(Damage, gameObject);
gotHitObj.GetComponent<States>().ReactToHit(damage, gameObject);
shoot = 0;
return targetCon.hitEnemyReward(gotHitObj.transform.position);
return targetCon.HitEnemyReward(gotHitObj.transform.position);
}
}
if (targetCon.targetTypeInt == (int)SceneBlockContainer.Targets.Attack)
@@ -314,7 +315,7 @@ public class AgentWithGun : Agent
}
}
float facingReward()
private float FacingReward()
{
float thisReward = 0;
bool isFacingtoEnemy = false;
@@ -333,7 +334,8 @@ public class AgentWithGun : Agent
isFacingtoEnemy = true;
}
}
if (raySensors.inViewEnemies.Count > 0 && !isFacingtoEnemy) {
if (raySensors.inViewEnemies.Count > 0 && !isFacingtoEnemy)
{
// have enemy in view
List<float> projectionDis = new List<float>();
foreach (GameObject thisEnemy in raySensors.inViewEnemies)
@@ -349,7 +351,7 @@ public class AgentWithGun : Agent
// Debug.DrawRay(thisEnemy.transform.position, verticalToRay, Color.magenta);
}
enemyFacingDistance = projectionDis.Min();
if(enemyFacingDistance <= lastEnemyFacingDistance)
if (enemyFacingDistance <= lastEnemyFacingDistance)
{
// closing to enemy
thisReward = 1 / MathF.Sqrt(paramContainer.facingInviewEnemyDisCOEF * enemyFacingDistance + 0.00001f);
@@ -365,14 +367,14 @@ public class AgentWithGun : Agent
// Debug.Log("ninimum = " + thisReward);
}
}
else if(targetCon.targetTypeInt == (int)SceneBlockContainer.Targets.Attack)
else if (targetCon.targetTypeInt == (int)SceneBlockContainer.Targets.Attack)
{
// attack mode
// Target to Agent distance
float targetDis = Vector3.Distance(blockContainer.thisBlock.transform.position, transform.position);
// center of screen between target's distance
float camCenterToTarget = Vector3.Distance(ray.origin + (ray.direction * targetDis), blockContainer.thisBlock.transform.position);
if(targetDis <= raySensors.viewDistance)
if (targetDis <= raySensors.viewDistance)
{
// Debug.DrawRay(new Vector3(0,0,0), viewPoint, Color.red);
// while center of screen between target's distance is lower than firebasesAreaDiameter
@@ -382,7 +384,8 @@ public class AgentWithGun : Agent
// Debug.DrawRay(ray.origin, viewPoint-ray.origin, Color.blue);
thisReward = paramContainer.facingReward;
}else
}
else
{
// while not facing to target
thisReward = (lastTargetFacingDistance - camCenterToTarget) * paramContainer.facingTargetReward;
@@ -396,7 +399,7 @@ public class AgentWithGun : Agent
// ------------Reward--------------
// rewardCalculate 计算本动作的Reward
public float rewardCalculate(float sceneReward,float mouseX,float movement)
public float RewardCalculate(float sceneReward, float mouseX, float movement)
{
float epreward = 0f;
// 击杀reward判断
@@ -405,7 +408,7 @@ public class AgentWithGun : Agent
for (int i = 0; i < enemyKillCount; i++)
{
// get
epreward += targetCon.killReward(killEnemyPosition);
epreward += targetCon.KillReward(killEnemyPosition);
}
enemyKillCount = 0;
}
@@ -414,9 +417,9 @@ public class AgentWithGun : Agent
enemyKillCount = 0;
}
// 射击动作reward判断
epreward += ballistic() + sceneReward;
epreward += Ballistic() + sceneReward;
// facing reward
epreward += facingReward();
epreward += FacingReward();
// Penalty
// spin penalty
spinRecord.Add(mouseX);
@@ -425,7 +428,7 @@ public class AgentWithGun : Agent
spinRecord.RemoveAt(0);
}
float spinPenaltyReward = Math.Abs(spinRecord.ToArray().Sum() * paramContainer.spinPenalty);
if(spinPenaltyReward >= paramContainer.spinPenaltyThreshold)
if (spinPenaltyReward >= paramContainer.spinPenaltyThreshold)
{
epreward -= spinPenaltyReward;
}
@@ -441,7 +444,6 @@ public class AgentWithGun : Agent
return epreward;
}
// ML-AGENTS处理-------------------------------------------------------------------------------------------ML-AGENTS
// env开始执行初始化
public override void OnEpisodeBegin()
@@ -452,26 +454,27 @@ public class AgentWithGun : Agent
{
Cursor.lockState = CursorLockMode.Locked; // hide and lock the mouse
}
paramContainer.resetTimeBonusReward();
paramContainer.ResetTimeBonusReward();
//thisAgentObj.name = thisAgentObj.GetInstanceID().ToString();
if (gamemode == 0)
{
// train mode
targetCon.rollNewScene();
targetCon.RollNewScene();
}
else
{
// play mode
targetCon.playInitialize();
targetCon.PlayInitialize();
}
// give default Reward to Reward value will be used.
if (hudController.chartOn)
{
EnvUICon.initChart();
envUICon.InitChart();
}
raySensors.updateRayInfo(); // update raycast
raySensors.UpdateRayInfo(); // update raycast
}
// ML-AGENTS处理-------------------------------------------------------------------------------------------ML-AGENTS
// 观察情报
public override void CollectObservations(VectorSensor sensor)
@@ -491,8 +494,8 @@ public class AgentWithGun : Agent
rayDisResult = raySensors.rayDisResult; // 探测用RayDis结果 float[](raySensorNum,1)
targetStates = targetCon.targetState; // (6) targettype, target x,y,z, firebasesAreaDiameter
remainTime = targetCon.leftTime;
inAreaState = targetCon.getInAreaState();
gunReadyToggle = gunReady();
inAreaState = targetCon.GetInAreaState();
gunReadyToggle = GunReady();
//float[] focusEnemyObserve = RaySensors.focusEnemyInfo;// 最近的Enemy情报 float[](3,1) MinEnemyIndex,x,z
//sensor.AddObservation(allEnemyNum); // 敌人数量 int
@@ -510,7 +513,7 @@ public class AgentWithGun : Agent
sensor.AddObservation(rayTagResult);
}
sensor.AddObservation(rayDisResult); // 探测用RayDis结果 float[](raySensorNum,1)
EnvUICon.updateStateText(targetStates, inAreaState, remainTime, gunReadyToggle, myObserve, rayTagResultOnehot, rayDisResult);
envUICon.UpdateStateText(targetStates, inAreaState, remainTime, gunReadyToggle, myObserve, rayTagResultOnehot, rayDisResult);
/*foreach(float aaa in rayDisResult)
{
Debug.Log(aaa);
@@ -535,22 +538,22 @@ public class AgentWithGun : Agent
//应用输入
shoot = mouseShoot;
cameraControl(Mouse_X, 0);
moveAgent(vertical, horizontal);
raySensors.updateRayInfo(); // update raycast
CameraControl(Mouse_X, 0);
MoveAgent(vertical, horizontal);
raySensors.UpdateRayInfo(); // update raycast
//判断结束
float sceneReward = 0f;
float endReward = 0f;
(finishedState, sceneReward, endReward) = targetCon.checkOverAndRewards();
float thisRoundReward = rewardCalculate(sceneReward+ endReward,Mouse_X,Math.Abs(vertical)+Math.Abs(horizontal));
(finishedState, sceneReward, endReward) = targetCon.CheckOverAndRewards();
float thisRoundReward = RewardCalculate(sceneReward + endReward, Mouse_X, Math.Abs(vertical) + Math.Abs(horizontal));
if (hudController.chartOn)
{
EnvUICon.updateChart(thisRoundReward);
envUICon.UpdateChart(thisRoundReward);
}
else
{
EnvUICon.removeChart();
envUICon.RemoveChart();
}
//Debug.Log("reward = " + thisRoundReward);
if (finishedState != (int)TargetController.EndType.Running)
@@ -562,11 +565,13 @@ public class AgentWithGun : Agent
switch (finishedState)
{
case (int)TargetController.EndType.Win:
Debug.LogWarning("Result|"+targetString+"|Win");
Debug.LogWarning("Result|" + targetString + "|Win");
break;
case (int)TargetController.EndType.Lose:
Debug.LogWarning("Result|"+targetString+"|Lose");
Debug.LogWarning("Result|" + targetString + "|Lose");
break;
default:
Debug.LogWarning("TypeError");
break;
@@ -645,6 +650,5 @@ public class AgentWithGun : Agent
//continuousActions[1] = Mouse_Y;
//continuousActions[2] = timeLimit;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^continuous-Control^^^^^^^^^^^^^^^^^^^^^^
}
}
@@ -1,8 +1,6 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.SideChannels;
using UnityEngine;
public class AimBotSideChennelController : MonoBehaviour
{
@@ -20,7 +18,6 @@ public class AimBotSideChennelController : MonoBehaviour
SideChannelManager.RegisterSideChannel(aimbotSideChannel);
}
// Side Channel
public void OnDestroy()
{
@@ -31,4 +28,4 @@ public class AimBotSideChennelController : MonoBehaviour
SideChannelManager.UnregisterSideChannel(aimbotSideChannel);
}
}
}
}
+5 -7
View File
@@ -1,9 +1,6 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.SideChannels;
using System;
using Unity.MLAgents.SideChannels;
using UnityEngine;
public class AimbotSideChannel : SideChannel
{
@@ -11,6 +8,7 @@ public class AimbotSideChannel : SideChannel
{
ChannelId = new Guid("8bbfb62a-99b4-457c-879d-b78b69066b5e");
}
protected override void OnMessageReceived(IncomingMessage msg)
{
var receivedString = msg.ReadString();
@@ -30,7 +28,7 @@ public class AimbotSideChannel : SideChannel
}
if (type == LogType.Error)
{
var stringToSend = "Error|"+logString;
var stringToSend = "Error|" + logString;
using (var msgOut = new OutgoingMessage())
{
msgOut.WriteString(stringToSend);
@@ -38,4 +36,4 @@ public class AimbotSideChannel : SideChannel
}
}
}
}
}
+5 -7
View File
@@ -1,7 +1,4 @@
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine;
public class Enemy : MonoBehaviour
{
@@ -22,12 +19,12 @@ public class Enemy : MonoBehaviour
/// <param name="target">目标</param>
/// <returns>目标target在扇形区域内返回true 否则返回false</returns>
void Start()
private void Start()
{
}
// Update is called once per frame
void Update()
private void Update()
{
//detactDeath();
//flag = IsInRange(angle, radius, transform, b);
@@ -43,6 +40,7 @@ public class Enemy : MonoBehaviour
float offsetAngle = Mathf.Acos(dot) * Mathf.Rad2Deg;
return offsetAngle < sectorAngle * .5f && direction.magnitude < sectorRadius;
}
/*
private void OnDrawGizmos()
{
@@ -81,4 +79,4 @@ public class Enemy : MonoBehaviour
}
}
*/
}
}
+13 -16
View File
@@ -1,35 +1,32 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyContainer : MonoBehaviour
{
public GameObject enemyPrefab;
public GameObject EnvironmentObj;
public GameObject TargetControllerObj;
public GameObject environmentObj;
public GameObject targetControllerObj;
private TargetController targetCon;
private void Start()
{
targetCon = TargetControllerObj.GetComponent<TargetController>();
targetCon = targetControllerObj.GetComponent<TargetController>();
}
// initialize enemy by random
public void randomInitEnemys(int EnemyNum)
public void RandomInitEnemys(int EnemyNum)
{
for (int i = 0; i < EnemyNum; i++)
{
float randX = UnityEngine.Random.Range(targetCon.minEnemyAreaX, targetCon.maxEnemyAreaX);
float randZ = UnityEngine.Random.Range(targetCon.minEnemyAreaZ, targetCon.maxEnemyAreaZ);
int enemyY = 1;
initEnemyAtHere(new Vector3(randX, enemyY, randZ));
InitEnemyAtHere(new Vector3(randX, enemyY, randZ));
}
}
// initialize enemy by random but not in block area
public void randomInitEnemysExcept(int enemyNum,Vector3 blockPosition,float sceneSize)
public void RandomInitEnemysExcept(int enemyNum, Vector3 blockPosition, float sceneSize)
{
float randX = 0f;
float randZ = 0f;
@@ -37,7 +34,7 @@ public class EnemyContainer : MonoBehaviour
{
randX = UnityEngine.Random.Range(targetCon.minEnemyAreaX, targetCon.maxEnemyAreaX);
randZ = UnityEngine.Random.Range(targetCon.minEnemyAreaZ, targetCon.maxEnemyAreaZ);
while (Vector3.Distance(blockPosition, new Vector3(randX,0f,randZ)) < sceneSize/2)
while (Vector3.Distance(blockPosition, new Vector3(randX, 0f, randZ)) < sceneSize / 2)
{
// while in scene area then respawn
Debug.Log("spawn enemy in area, re:roll");
@@ -46,22 +43,22 @@ public class EnemyContainer : MonoBehaviour
}
int enemyY = 1;
initEnemyAtHere(new Vector3(randX, enemyY, randZ));
InitEnemyAtHere(new Vector3(randX, enemyY, randZ));
}
}
// initialize enemy to thisPosition
public void initEnemyAtHere(Vector3 thisPosition)
public void InitEnemyAtHere(Vector3 thisPosition)
{
Instantiate(enemyPrefab, thisPosition + EnvironmentObj.transform.position, Quaternion.identity, this.transform);
Instantiate(enemyPrefab, thisPosition + environmentObj.transform.position, Quaternion.identity, this.transform);
}
// destroyEnemy delete enemyContainer's all enemy
public void destroyAllEnemys()
public void DestroyAllEnemys()
{
foreach (Transform childObj in this.transform)
{
childObj.GetComponent<states>().destroyMe();
childObj.GetComponent<States>().DestroyMe();
}
}
}
}
+26 -20
View File
@@ -1,6 +1,4 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using TMPro;
using UnityEngine;
@@ -9,9 +7,9 @@ using XCharts.Runtime;
public class EnvironmentUIControl : MonoBehaviour
{
public GameObject TargetControllerObj;
public GameObject ParameterContainerObj;
public GameObject GroundCanvasObj;
public GameObject targetControllerObj;
public GameObject parameterContainerObj;
public GameObject groundCanvasObj;
public GameObject chartObj;
public GameObject HUDObj;
public TextMeshProUGUI remainTimeText;
@@ -32,16 +30,16 @@ public class EnvironmentUIControl : MonoBehaviour
private bool resultActive = false;
// Start is called before the first frame update
void Start()
private void Start()
{
targetController = TargetControllerObj.GetComponent<TargetController>();
paramContainer = ParameterContainerObj.GetComponent<ParameterContainer>();
targetController = targetControllerObj.GetComponent<TargetController>();
paramContainer = parameterContainerObj.GetComponent<ParameterContainer>();
gaugeImg = gaugeImgObj.GetComponent<Image>();
hudController = HUDObj.GetComponent<HUDController>();
}
// Update is called once per frame
void Update()
private void Update()
{
// int remainTime = Convert.ToInt32(targetController.startTime + paramContainer.timeLimit - Time.time);
remainTimeText.text = "RemainTime:" + Convert.ToInt32(targetController.leftTime).ToString();
@@ -55,22 +53,23 @@ public class EnvironmentUIControl : MonoBehaviour
resultActive = false;
}
}
public void updateChart(float reward)
public void UpdateChart(float reward)
{
if (hudController.chartOn && realTimeRewardChart == null)
{
initChart();
InitChart();
}
step += 1;
realTimeRewardChart.AddXAxisData(Convert.ToString(step));
realTimeRewardChart.AddData(0, reward);
}
public void initChart()
public void InitChart()
{
if (hudController.chartOn && realTimeRewardChart == null)
{
Vector3 chartPos = new Vector3(-210f, 90f, 0f) * GroundCanvasObj.transform.localScale.x;
Vector3 chartPos = new Vector3(-210f, 90f, 0f) * groundCanvasObj.transform.localScale.x;
realTimeRewardChart = chartObj.AddComponent<LineChart>();
realTimeRewardChart.Init();
}
@@ -78,15 +77,14 @@ public class EnvironmentUIControl : MonoBehaviour
realTimeRewardChart.AddSerie<Line>("Rewards");
}
public void removeChart()
public void RemoveChart()
{
GameObject.Destroy(realTimeRewardChart);
realTimeRewardChart = null;
}
// show result in UI
public void showResult(int resultState)
public void ShowResult(int resultState)
{
switch (resultState)
{
@@ -98,6 +96,7 @@ public class EnvironmentUIControl : MonoBehaviour
overTime = Time.time;
resultActive = true;
break;
case (int)TargetController.EndType.Lose:
//lose
Debug.Log("lose");
@@ -106,13 +105,14 @@ public class EnvironmentUIControl : MonoBehaviour
overTime = Time.time;
resultActive = true;
break;
default:
break;
}
}
// update firebases target state gauge
public void updateTargetGauge(float firebasesBelong, float belongMaxPoint)
public void UpdateTargetGauge(float firebasesBelong, float belongMaxPoint)
{
if (firebasesBelong >= 0)
{
@@ -129,8 +129,9 @@ public class EnvironmentUIControl : MonoBehaviour
gaugeImg.fillAmount = -firebasesBelong / belongMaxPoint;
}
}
// update targetType text
public void updateTargetType(int targetInt)
public void UpdateTargetType(int targetInt)
{
switch (targetInt)
{
@@ -138,22 +139,27 @@ public class EnvironmentUIControl : MonoBehaviour
targetTypeText.text = "GOTO";
targetTypeText.color = Color.blue;
break;
case (int)SceneBlockContainer.Targets.Attack:
targetTypeText.text = "Attack!";
targetTypeText.color = Color.red;
break;
case (int)SceneBlockContainer.Targets.Defence:
targetTypeText.text = "Defence";
targetTypeText.color = Color.green;
break;
case (int)SceneBlockContainer.Targets.Free:
targetTypeText.text = "Free";
targetTypeText.color = Color.yellow;
break;
case (int)SceneBlockContainer.Targets.Stay:
targetTypeText.text = "Stay";
targetTypeText.color = Color.white;
break;
default:
targetTypeText.text = "TYPE ERROR";
targetTypeText.color = Color.red;
@@ -171,7 +177,7 @@ public class EnvironmentUIControl : MonoBehaviour
// targetState[5] = blockCont.thisBlock.belongRatio;
// float[] myObserve = { transform.localPosition.x/raySensors.viewDistance, transform.localPosition.y / raySensors.viewDistance, transform.localPosition.z / raySensors.viewDistance, transform.eulerAngles.y/360f }
// ??????????string??"targetType: 1.0 \r\n targetX: 2.0 \r\n"
public void updateStateText(float[] targetStates,float inAreaState,float remainTime, bool gunReadyToggle, float[] myObserve, float[] rayTagResultOnehot, float[] rayDisResult)
public void UpdateStateText(float[] targetStates, float inAreaState, float remainTime, bool gunReadyToggle, float[] myObserve, float[] rayTagResultOnehot, float[] rayDisResult)
{
stateBuilder.Clear();
@@ -195,4 +201,4 @@ public class EnvironmentUIControl : MonoBehaviour
stateText.text = stateBuilder.ToString();
}
}
}
+10 -13
View File
@@ -1,35 +1,32 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HPBar : MonoBehaviour
{
GameObject thisObj;
GameObject BGOBJ;
GameObject gaugeImgOBJ;
private GameObject thisObj;
private GameObject backgroundObj;
private GameObject gaugeImgOBJ;
void Start()
private void Start()
{
thisObj = transform.parent.gameObject;
BGOBJ = transform.GetChild(0).gameObject;
gaugeImgOBJ = BGOBJ.transform.GetChild(0).gameObject;
backgroundObj = transform.GetChild(0).gameObject;
gaugeImgOBJ = backgroundObj.transform.GetChild(0).gameObject;
Vector3 v = Camera.main.transform.position - transform.position;
v.x = v.z = 0.0f;
transform.LookAt(Camera.main.transform.position - v);
transform.Rotate(0, 180, 0);
}
void Update()
private void Update()
{
Vector3 v = Camera.main.transform.position - transform.position;
v.x = v.z = 0.0f;
transform.LookAt(Camera.main.transform.position - v);
transform.Rotate(0, 180, 0);
float maxHP = thisObj.GetComponent<states>().MaxHP;
float nowHP = thisObj.GetComponent<states>().getnowHP();
float maxHP = thisObj.GetComponent<States>().maxHP;
float nowHP = thisObj.GetComponent<States>().GetnowHP();
gaugeImgOBJ.GetComponent<Image>().fillAmount = nowHP / maxHP;
}
}
}
+6 -8
View File
@@ -1,6 +1,4 @@
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
@@ -12,7 +10,7 @@ public class HUDController : MonoBehaviour
public TMP_InputField chartOnTimeOutInputObj;
public TMP_InputField enemyNumInputObj;
public float chartOnTimeOut = 1;
public int enemyNum= 3;
public int enemyNum = 3;
public float chartOnTimeOutDefault = 120f;
private float chatOntimeStart = 0;
@@ -20,7 +18,7 @@ public class HUDController : MonoBehaviour
{
if (chartOn)
{
if (Time.time - chatOntimeStart >= chartOnTimeOut )
if (Time.time - chatOntimeStart >= chartOnTimeOut)
{
chartOn = false;
chartOnToggleObj.isOn = false;
@@ -28,13 +26,13 @@ public class HUDController : MonoBehaviour
}
}
public void onChartOnToggleChange()
public void OnChartOnToggleChange()
{
chatOntimeStart = Time.time;
chartOn = chartOnToggleObj.isOn;
}
public void onEnemyNumTextChange()
public void OnEnemyNumTextChange()
{
try
{
@@ -46,7 +44,7 @@ public class HUDController : MonoBehaviour
}
}
public void onChartTimeOutTextChange()
public void OnChartTimeOutTextChange()
{
try
{
@@ -57,4 +55,4 @@ public class HUDController : MonoBehaviour
chartOnTimeOut = chartOnTimeOutDefault;
}
}
}
}
+8 -8
View File
@@ -1,15 +1,13 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class Onehot
{
private List<string> tags = new List<string>();
public List<List<float>> onehot = new List<List<float>>();
private float totalNum;
public void initialize(List<string> inputTags)
public void Initialize(List<string> inputTags)
{
tags = inputTags;
totalNum = tags.Count;
@@ -21,7 +19,8 @@ public class Onehot
onehot.Add(thisOnehot);
}
}
public List<float> encoder(string name = null)
public List<float> Encoder(string name = null)
{
if (name == null)
{
@@ -34,7 +33,8 @@ public class Onehot
try
{
return onehot[tags.IndexOf(name)];
}catch(ArgumentOutOfRangeException)
}
catch (ArgumentOutOfRangeException)
{
List<float> allZeroOnehot = new List<float>();
for (int j = 0; j < totalNum; j++) allZeroOnehot.Add(0);
@@ -43,8 +43,8 @@ public class Onehot
}
}
public string decoder(List<float> thisOnehot)
public string Decoder(List<float> thisOnehot)
{
return tags[onehot.IndexOf(thisOnehot)];
}
}
}
+32 -8
View File
@@ -1,5 +1,3 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParameterContainer : MonoBehaviour
@@ -12,10 +10,10 @@ public class ParameterContainer : MonoBehaviour
private float agentDistance;
private int agentInArea;
[Header("Env")]
public bool lockMouse = false;
public float Damage = 50; // damage to enemy
public float damage = 50; // damage to enemy
public float fireRate = 0.5f;
public int timeLimit = 30;
public bool lockCameraX = false;
@@ -25,80 +23,106 @@ public class ParameterContainer : MonoBehaviour
public float spinPenaltyThreshold = 50;
public float facingInviewEnemyDisCOEF = 0.5f;
[Header("Dynamic Defaut Rewards")]
//[Tooltip("Hit Enemy reward")]
//public float hitRewardDefault = 60.0f;
[Tooltip("Free mode Hit Enemy reward")]
public float hitTargetRewardDefault = 60.0f;
//[Tooltip("Enemy down reward")]
//public float killRewardDefault = 60.0f;
[Tooltip("Enemy down in area Reward")]
public float killTargetEnemyRewardDefault = 100.0f;
[Tooltip("stay in firebasesArea reward")]
public float inAreaRewardDefault = 10.0f;
[Tooltip("free left time bonus reward. ALLR + leftTime * r")]
public float freeTimeBonusPerSec = 1.0f;
[Tooltip("target left time bonus reward. ALLR + leftTime * r")]
public float targetTimeBonusPerSec = 3.0f;
[Tooltip("in area left time bonus reward. ALLR + leftTime * r")]
public float areaTimeBonusPerSec = 1.0f;
[Tooltip("distance reward reward = r*(1-(nowDis/startDis))")]
public float distanceReward = 20.0f;
[Tooltip("facing to Target distance reward reward = r*(1-(nowDis/startDis))")]
public float facingTargetReward = 20.0f;
[Space(10)]
[Tooltip("Goto Win reward")]
public float goWinRewardDefault = 100.0f;
[Tooltip("Attack Win reward")]
public float attackWinRewardDefault = 100.0f;
[Tooltip("Defence Win reward")]
public float defenceWinRewardDefault = 100.0f;
[Tooltip("free Win reward")]
public float freeWinRewardDefault = 100.0f;
[Header("Static Rewards")]
[Tooltip("Nothing happened reward")]
public float nonReward = -0.05f;
[Tooltip("Episode Lose reward")]
public float loseReward = -0.05f;
[Tooltip("Agent Do shoot action reward")]
public float shootReward = -0.1f;
[Tooltip("Hit Not target Enemy reward")]
public float hitReward = 30.0f;
[Tooltip("Not Target Enemy down reward")]
public float killReward = 40.0f;
[Tooltip("Agent Do shoot action but gun is not read")]
public float shootWithoutReadyReward = -0.15f;
[Tooltip("Kill bonus reward stack to nothing happend reward")]
public float killBonusReward = 0.0f;
[Tooltip("Facing to enemy's reward")]
public float facingReward = 2.0f;
[Tooltip("Shoot at target area but didn't hit enemy")]
public float shootTargetAreaReward = 5.0f;
[Header("Penalty Rewards")]
[Tooltip("move Penalty Reward")]
public float movePenalty = 0f;
[Tooltip("spiiiiiiin Panalty Reward")]
public float spinPenalty = 0f;
[Tooltip("while move mouse a little bit's penalty")]
public float mousePenalty = 0f;
[Header("Dynamic Rewards")]
[Tooltip("Free mode Hit Enemy reward")]
public float hitTargetReward = 60.0f;
[Tooltip("Enemy down in area Reward")]
public float killTargetEnemyReward = 80.0f;
[Tooltip("stay in firebasesArea reward")]
public float inAreaReward = 1.0f;
[Space(10)]
[Tooltip("go Win reward")]
public float goWinReward = 50.0f;
[Tooltip("attack Win reward")]
public float attackWinReward = 50.0f;
[Tooltip("defence Win reward")]
public float defenceWinReward = 50.0f;
[Tooltip("free Win reward")]
public float freeWinReward = 50.0f;
@@ -122,7 +146,7 @@ public class ParameterContainer : MonoBehaviour
// get target distance and in area
if (targetCon.targetTypeInt is (int)SceneBlockContainer.Targets.Go or (int)SceneBlockContainer.Targets.Attack)
{
(agentDistance, agentInArea) = blockCont.getAgentTargetDistanceAndInside(agentObj.transform.position);
(agentDistance, agentInArea) = blockCont.GetAgentTargetDistanceAndInside(agentObj.transform.position);
// attack goto or defence target
if (agentInArea == 1)
{
@@ -153,10 +177,10 @@ public class ParameterContainer : MonoBehaviour
freeWinReward = freeWinRewardDefault;
}
public void resetTimeBonusReward()
public void ResetTimeBonusReward()
{
areaTimeBonus = areaTimeBonusPerSec * timeLimit;
freeTimeBonus = freeTimeBonusPerSec * timeLimit;
targetInAreaTime = 0f;
}
}
}
+33 -29
View File
@@ -1,12 +1,9 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
/*该scrip用于创建复数条ray于视角内,并探测被ray射到的物体*/
public class RaySensors : MonoBehaviour
{
public Camera agentCam;
@@ -16,32 +13,35 @@ public class RaySensors : MonoBehaviour
public GameObject agentCanvas;
[SerializeField, Range(0, 500)] public float viewDistance = 100; // how long the ray can detect
//[SerializeField, Range(0, 1)] public float totalRange = 1f; // Total view range Max = 1
[SerializeField, Range(0, 1)] public float focusRange = 0.15f; // center focus range
public int halfOuterRayNum = 3; // >=2
public int focusRayNum = 5; // >= 1 and must be odd num!
[Header("InGameLineSetting")]
public bool showInGameRay = true;
public bool showDebugRay = true;
public bool showInGameRayInfo = true;
public float lineWidth = 0.05f;
[Header("RayCastResult")]
public float[] rayTagResult;
public List<float> rayTagResultOneHot;
public float[] rayDisResult;
[System.NonSerialized] public int totalRayNum;
private string myTag = "";
GameObject[] linesOBJ;
GameObject[] rayInfoOBJ;
LineRenderer[] lineRenderers;
rayInfoUI[] rayInfoUIs;
private GameObject[] linesOBJ;
private GameObject[] rayInfoOBJ;
private LineRenderer[] lineRenderers;
private RayInfoUI[] rayInfoUIs;
public List<GameObject> inViewEnemies = new List<GameObject>();
private List<string> tags = new List<string> {"Wall","Enemy"};
private List<string> tags = new List<string> { "Wall", "Enemy" };
private Onehot oneHotTags = new Onehot();
private void Start()
{
@@ -52,8 +52,8 @@ public class RaySensors : MonoBehaviour
linesOBJ = new GameObject[totalRayNum];
lineRenderers = new LineRenderer[totalRayNum];
rayInfoOBJ = new GameObject[totalRayNum];
rayInfoUIs = new rayInfoUI[totalRayNum];
oneHotTags.initialize(tags);
rayInfoUIs = new RayInfoUI[totalRayNum];
oneHotTags.Initialize(tags);
for (int i = 0; i < totalRayNum; i++)
{
linesOBJ[i] = new GameObject();
@@ -64,20 +64,21 @@ public class RaySensors : MonoBehaviour
lineRenderers[i].material = lineMeterial;
rayInfoOBJ[i] = (GameObject)Instantiate(rayInfoPrefab);
rayInfoOBJ[i].transform.SetParent(agentCanvas.transform,false);
rayInfoOBJ[i].transform.SetParent(agentCanvas.transform, false);
rayInfoOBJ[i].name = "rayInfo-" + Convert.ToString(i);
rayInfoUIs[i] = rayInfoOBJ[i].GetComponent<rayInfoUI>();
rayInfoUIs[i] = rayInfoOBJ[i].GetComponent<RayInfoUI>();
}
}
public int tagToInt(string tag)
public int TagToInt(string tag)
{
switch (tag)
{
case "Wall":
return 1;
default:
if(tag != myTag)
if (tag != myTag)
{
return 2;
}
@@ -85,7 +86,7 @@ public class RaySensors : MonoBehaviour
}
}
private void singleRaycastUpdate(Ray ray,LineRenderer thisLineRenderer,rayInfoUI thisRayInfoUI, out float rayTagResult, out float rayDisResult)
private void SingleRaycastUpdate(Ray ray, LineRenderer thisLineRenderer, RayInfoUI thisRayInfoUI, out float rayTagResult, out float rayDisResult)
{
// get Raycast hit infomation and return Tag and distance
RaycastHit thisHit;
@@ -96,8 +97,8 @@ public class RaySensors : MonoBehaviour
if (Physics.Raycast(ray, out thisHit, viewDistance)) // 若在viewDistance范围内有碰撞
{
rayInfoText = thisHit.collider.tag;
rayTagResult = tagToInt(rayInfoText);
rayTagResultOneHot.AddRange(oneHotTags.encoder(rayInfoText));
rayTagResult = TagToInt(rayInfoText);
rayTagResultOneHot.AddRange(oneHotTags.Encoder(rayInfoText));
rayDisResult = thisHit.distance;
lineLength = rayDisResult;
rayInfoText += "\n" + Convert.ToString(rayDisResult);
@@ -108,13 +109,16 @@ public class RaySensors : MonoBehaviour
case 1:// Wall
rayColor = Color.white;
break;
case 2: // Enemy
rayColor = Color.red;
inViewEnemies.Add(thisHit.transform.gameObject);
break;
case -1: // Hit Nothing
rayColor = Color.gray;
break;
default: // default,got wrong
rayColor = Color.cyan;
break;
@@ -122,7 +126,7 @@ public class RaySensors : MonoBehaviour
}
else // 若在viewDistance范围无碰撞
{
rayTagResultOneHot.AddRange(oneHotTags.encoder());
rayTagResultOneHot.AddRange(oneHotTags.Encoder());
rayTagResult = -1f;
rayDisResult = -1f;
//输出log
@@ -132,14 +136,14 @@ public class RaySensors : MonoBehaviour
rayInfoPosition = ray.origin + (ray.direction * lineLength);
if (showInGameRay)
{
drawLine(ray, lineLength, thisLineRenderer, rayColor);
DrawLine(ray, lineLength, thisLineRenderer, rayColor);
}
else
{
turnOffLine(thisLineRenderer, rayColor);
TurnOffLine(thisLineRenderer, rayColor);
}
// drawRay in game
if (showInGameRayInfo) thisRayInfoUI.updateInfo(rayInfoText, rayInfoPosition, rayColor,TPSCam);
if (showInGameRayInfo) thisRayInfoUI.UpdateInfo(rayInfoText, rayInfoPosition, rayColor, TPSCam);
// Show log
if (showDebugRay) Debug.DrawRay(ray.origin, ray.direction * viewDistance, rayColor); // drawRay in debug
// Debug.Log(ray.origin + ray.direction);
@@ -147,7 +151,7 @@ public class RaySensors : MonoBehaviour
// Debug.Log(tagToInt(thisHit.collider.tag));
}
private void drawLine(Ray ray,float lineLength, LineRenderer thisLineRenderer, Color lineColor)
private void DrawLine(Ray ray, float lineLength, LineRenderer thisLineRenderer, Color lineColor)
{
thisLineRenderer.startColor = lineColor;
thisLineRenderer.endColor = lineColor;
@@ -157,7 +161,7 @@ public class RaySensors : MonoBehaviour
thisLineRenderer.SetPosition(1, ray.origin + (ray.direction * lineLength));
}
private void turnOffLine(LineRenderer thisLineRenderer, Color lineColor)
private void TurnOffLine(LineRenderer thisLineRenderer, Color lineColor)
{
thisLineRenderer.startColor = lineColor;
thisLineRenderer.endColor = lineColor;
@@ -167,7 +171,7 @@ public class RaySensors : MonoBehaviour
thisLineRenderer.SetPosition(1, new Vector3(0, 0, 0));
}
public void updateRayInfo()
public void UpdateRayInfo()
{
float focusLEdge = agentCam.pixelWidth * (1 - focusRange) / 2;
float focusREdge = agentCam.pixelWidth * (1 + focusRange) / 2;
@@ -178,19 +182,19 @@ public class RaySensors : MonoBehaviour
{
Vector3 point = new Vector3(i * focusLEdge / (halfOuterRayNum - 1), thisCamPixelHeight / 2, 0);
Ray thisRay = agentCam.ScreenPointToRay(point);
singleRaycastUpdate(thisRay,lineRenderers[i], rayInfoUIs[i] , out rayTagResult[i], out rayDisResult[i]);
SingleRaycastUpdate(thisRay, lineRenderers[i], rayInfoUIs[i], out rayTagResult[i], out rayDisResult[i]);
}
for (int i = 0; i < halfOuterRayNum; i++) // create right outside rays; focusRightEdge ~ MaxPixelHeight
{
Vector3 point = new Vector3(focusREdge + (i * focusLEdge / (halfOuterRayNum - 1)), thisCamPixelHeight / 2, 0);
Ray thisRay = agentCam.ScreenPointToRay(point);
singleRaycastUpdate(thisRay, lineRenderers[halfOuterRayNum + i], rayInfoUIs[halfOuterRayNum + i], out rayTagResult[halfOuterRayNum + i], out rayDisResult[halfOuterRayNum + i]);
SingleRaycastUpdate(thisRay, lineRenderers[halfOuterRayNum + i], rayInfoUIs[halfOuterRayNum + i], out rayTagResult[halfOuterRayNum + i], out rayDisResult[halfOuterRayNum + i]);
}
for (int i = 0; i < focusRayNum; i++) // create center focus rays; focusLeftEdge ~ focusLeftEdge
{
Vector3 point = new Vector3(focusLEdge + ((i + 1) * (focusREdge - focusLEdge) / (focusRayNum + 1)), thisCamPixelHeight / 2, 0);
Ray thisRay = agentCam.ScreenPointToRay(point);
singleRaycastUpdate(thisRay, lineRenderers[halfOuterRayNum * 2 + i], rayInfoUIs[halfOuterRayNum * 2 + i], out rayTagResult[halfOuterRayNum*2 + i], out rayDisResult[halfOuterRayNum*2 + i]);
SingleRaycastUpdate(thisRay, lineRenderers[halfOuterRayNum * 2 + i], rayInfoUIs[halfOuterRayNum * 2 + i], out rayTagResult[halfOuterRayNum * 2 + i], out rayDisResult[halfOuterRayNum * 2 + i]);
}
}
}
}
+42 -30
View File
@@ -1,12 +1,10 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class SceneBlock : MonoBehaviour
{
public GameObject FirebasesAreaObj;
public GameObject EnemyContainerObj;
public GameObject firebasesAreaObj;
public GameObject enemyContainerObj;
public float group1InareaNum = 0;
public float group2InareaNum = 0;
public float belongRatio = 0;
@@ -15,12 +13,15 @@ public class SceneBlock : MonoBehaviour
public float firebasesAreaScale;
public float firebasesAreaDiameter;
public enum SceneType { Go, Attack, Defence }
public enum SceneType
{ Go, Attack, Defence }
public SceneType sceneType;
public bool isDestroyed = false;
// firebase state
public string group1Tag = "Player";
public string group2Tag = "Enemy";
public float belongMaxPoint = 10f;
public float firebasesBelong; // -10 mean's belon to group2Tag 10 = belon to group1Tag
@@ -29,15 +30,25 @@ public class SceneBlock : MonoBehaviour
private float addPointEachInterval; // add point in each interval
private float intervalStart;
private GameObject EnvironmentObj;
private GameObject environmentObj;
public GameObject[] group1Objs;
public GameObject[] group2Objs;
// Start is called before the first frame update
void Start()
private void Start()
{
firebasesAreaPosition = transform.position + FirebasesAreaObj.transform.position;
firebasesAreaScale = FirebasesAreaObj.transform.localScale.x;
// if firebasesAreaObj is null, find sub object by name
if (firebasesAreaObj == null)
{
firebasesAreaObj = transform.Find("FirebasesArea").gameObject;
}
// if enemyContainerObj is null, find them by name
if (enemyContainerObj == null)
{
enemyContainerObj = transform.Find("EnemyContainer").gameObject;
}
firebasesAreaPosition = transform.position + firebasesAreaObj.transform.position;
firebasesAreaScale = firebasesAreaObj.transform.localScale.x;
firebasesAreaDiameter = firebasesAreaScale * blockSize;
firebasesBelong = -belongMaxPoint;
addPointEachInterval = belongMaxPoint / (stayTimeNeeded / addPointInterval);
@@ -45,13 +56,13 @@ public class SceneBlock : MonoBehaviour
}
// Update is called once per frame
void Update()
private void Update()
{
if (Time.time - intervalStart >= addPointInterval)
{
// update belong ratio every addPointInterval scecond
group1InareaNum = getInAreaNumber(group1Tag);
group2InareaNum = getInAreaNumber(group2Tag);
group1InareaNum = GetInAreaNumber(group1Tag);
group2InareaNum = GetInAreaNumber(group2Tag);
belongRatio = group1InareaNum - group2InareaNum;
if (belongRatio > 0)
{
@@ -76,24 +87,24 @@ public class SceneBlock : MonoBehaviour
}
//Initialize this scene block should be excuted after enemy created
public void initBlock(GameObject envObj)
public void InitBlock(GameObject envObj)
{
//Buffer all Player or enemy obj int this environment to list
EnvironmentObj = envObj;
environmentObj = envObj;
GameObject[] allGroup1Objs = GameObject.FindGameObjectsWithTag(group1Tag);
GameObject[] allGroup2Objs = GameObject.FindGameObjectsWithTag(group2Tag);
List<GameObject> group1ObjsList = new List<GameObject>();
List<GameObject> group2ObjsList = new List<GameObject>();
foreach (GameObject obj in allGroup1Objs)
{
if (obj.transform.root.gameObject == envObj && !obj.GetComponent<states>().isDead)
if (obj.transform.root.gameObject == envObj && !obj.GetComponent<States>().isDead)
{
group1ObjsList.Add(obj);
}
}
foreach (GameObject obj in allGroup2Objs)
{
if(obj.transform.root.gameObject == envObj && !obj.GetComponent<states>().isDead)
if (obj.transform.root.gameObject == envObj && !obj.GetComponent<States>().isDead)
{
group2ObjsList.Add(obj);
}
@@ -103,13 +114,13 @@ public class SceneBlock : MonoBehaviour
}
//check game over 0=notover 1=win
public int checkOver()
public int CheckOver()
{
return 0;
}
// get in area player number by tag
public float getInAreaNumber(string thisTag)
public float GetInAreaNumber(string thisTag)
{
float inAreaNum = 0;
float dist = 0f;
@@ -117,7 +128,7 @@ public class SceneBlock : MonoBehaviour
int index = 0;
if (thisTag == group1Tag)
{
foreach(GameObject obj in group1Objs)
foreach (GameObject obj in group1Objs)
{
// if object is dead then delete it from list
if (obj == null)
@@ -129,7 +140,7 @@ public class SceneBlock : MonoBehaviour
}
else
{
(dist, isInarea) = getDist_inArea(obj.transform.position);
(dist, isInarea) = GetDistInArea(obj.transform.position);
if (isInarea != 0f)
{
inAreaNum += 1;
@@ -137,9 +148,10 @@ public class SceneBlock : MonoBehaviour
}
index++;
}
}else if(thisTag == group2Tag)
}
else if (thisTag == group2Tag)
{
foreach(GameObject obj in group2Objs)
foreach (GameObject obj in group2Objs)
{
// if object is dead then delete it from list
if (obj == null)
@@ -151,7 +163,7 @@ public class SceneBlock : MonoBehaviour
}
else
{
(dist, isInarea) = getDist_inArea(obj.transform.position);
(dist, isInarea) = GetDistInArea(obj.transform.position);
if (isInarea != 0f)
{
inAreaNum += 1;
@@ -168,10 +180,10 @@ public class SceneBlock : MonoBehaviour
}
// get this position and target's distance and is in firebase area
public (float, int) getDist_inArea(Vector3 thisPosition)
public (float, int) GetDistInArea(Vector3 thisPosition)
{
thisPosition.y = FirebasesAreaObj.transform.position.y;
float dist = Vector3.Distance(thisPosition, FirebasesAreaObj.transform.position) - (firebasesAreaDiameter/2);
thisPosition.y = firebasesAreaObj.transform.position.y;
float dist = Vector3.Distance(thisPosition, firebasesAreaObj.transform.position) - (firebasesAreaDiameter / 2);
int isinarea = 0;
if (dist <= 0)
{
@@ -186,13 +198,13 @@ public class SceneBlock : MonoBehaviour
}
//destroy this block
public void destroyMe()
public void DestroyMe()
{
Destroy(this.gameObject);
foreach (Transform childObj in EnemyContainerObj.transform)
foreach (Transform childObj in enemyContainerObj.transform)
{
childObj.GetComponent<states>().destroyMe();
childObj.GetComponent<States>().DestroyMe();
}
isDestroyed = true;
}
}
}
+19 -17
View File
@@ -1,13 +1,12 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SceneBlockContainer : MonoBehaviour
{
public enum Targets { Free, Go, Attack, Defence, Stay, Num };// Num is use for get total target bumber
public enum Targets
{ Free, Go, Attack, Defence, Stay, Num };// Num is use for get total target bumber
public float sceneSize = 10f;
public GameObject EnvironmentObj;
public GameObject environmentObj;
public GameObject[] attackBlockPrefabs = new GameObject[1];
public GameObject[] goBlockPrefabs = new GameObject[1];
public GameObject[] defencePrefabs = new GameObject[1];
@@ -18,38 +17,41 @@ public class SceneBlockContainer : MonoBehaviour
private void Start()
{
}
// create block random
public void createNewBlock(Targets targetType, int blockType, Vector3 blockPosition,string tag1 = "Player", string tag2 = "Enemy")
public void CreateNewBlock(Targets targetType, int blockType, Vector3 blockPosition, string tag1 = "Player", string tag2 = "Enemy")
{
// check if thisBlock is deleted
if (thisBlockObj != null)
{
// delete thisBlock
Debug.LogWarning("Block not clear!");
destroyBlock();
DestroyBlock();
}
// choose target type
switch (targetType)
{
case Targets.Go:
// goto
thisBlockObj = Instantiate(goBlockPrefabs[blockType], blockPosition + EnvironmentObj.transform.position, Quaternion.identity, transform);
thisBlockObj = Instantiate(goBlockPrefabs[blockType], blockPosition + environmentObj.transform.position, Quaternion.identity, transform);
thisBlock = thisBlockObj.GetComponent<SceneBlock>();
thisBlock.group1Tag = tag1;
thisBlock.group2Tag = tag2;
sceneSize = thisBlock.blockSize;
break;
case Targets.Attack:
// attack
thisBlockObj = Instantiate(attackBlockPrefabs[blockType], blockPosition+ EnvironmentObj.transform.position, Quaternion.identity, transform);
thisBlockObj = Instantiate(attackBlockPrefabs[blockType], blockPosition + environmentObj.transform.position, Quaternion.identity, transform);
thisBlock = thisBlockObj.GetComponent<SceneBlock>();
thisBlock.group1Tag = tag1;
thisBlock.group2Tag = tag2;
sceneSize = thisBlock.blockSize;
break;
case Targets.Defence:
// defence
thisBlockObj = Instantiate(defencePrefabs[blockType], blockPosition + EnvironmentObj.transform.position, Quaternion.identity, transform);
thisBlockObj = Instantiate(defencePrefabs[blockType], blockPosition + environmentObj.transform.position, Quaternion.identity, transform);
thisBlock = thisBlockObj.GetComponent<SceneBlock>();
thisBlock.group1Tag = tag1;
thisBlock.group2Tag = tag2;
@@ -59,23 +61,23 @@ public class SceneBlockContainer : MonoBehaviour
}
// delete thisBlock
public void destroyBlock()
public void DestroyBlock()
{
if (thisBlock != null)
{
thisBlock.destroyMe();
thisBlock.DestroyMe();
}
thisBlockObj = null;
thisBlock = null;
}
public (float, int) getAgentTargetDistanceAndInside(Vector3 agentPosition)
public (float, int) GetAgentTargetDistanceAndInside(Vector3 agentPosition)
{
return thisBlock.getDist_inArea(agentPosition);
return thisBlock.GetDistInArea(agentPosition);
}
public void initializeBlock(GameObject envObj)
public void InitializeBlock(GameObject envObj)
{
thisBlock.initBlock(envObj);
thisBlock.InitBlock(envObj);
}
}
}
+103 -95
View File
@@ -1,22 +1,22 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using UnityEngine;
using Random = UnityEngine.Random;
public class TargetController : MonoBehaviour
{
public GameObject EnvironmentObj;
public GameObject AgentObj;
public GameObject environmentObj;
public GameObject agentObj;
public GameObject HUDObj;
public GameObject SceneBlockContainerObj;
public GameObject EnemyContainerObj;
public GameObject ParameterContainerObj;
public GameObject EnvironmentUIObj;
public GameObject WorldUIObj;
public GameObject sceneBlockContainerObj;
public GameObject enemyContainerObj;
public GameObject parameterContainerObj;
public GameObject environmentUIObj;
public GameObject worldUIObj;
// area
public GameObject edgeUp;
public GameObject edgeDown;
public GameObject edgeLeft;
public GameObject edgeRight;
@@ -24,6 +24,7 @@ public class TargetController : MonoBehaviour
//group
public string group1Tag = "Player";
public string group2Tag = "Enemy";
public float minEnemyAreaX;
@@ -43,7 +44,10 @@ public class TargetController : MonoBehaviour
[System.NonSerialized] public int targetTypeInt;
public float[] targetState = new float[6];
public enum EndType { Win, Lose, Running, Num };
public enum EndType
{ Win, Lose, Running, Num };
[System.NonSerialized] public int targetNum = 0;
private Dictionary<int, float[]> oneHotRarget = new Dictionary<int, float[]>();
@@ -64,11 +68,12 @@ public class TargetController : MonoBehaviour
private HUDController hudCon;
private RaySensors raySensors;
private StartSeneData startSceneData;
// start scene datas 0=train 1=play
private int gamemode;
// Start is called before the first frame update
void Start()
private void Start()
{
minEnemyAreaX = edgeLeft.transform.localPosition.x + 1.0f;
maxEnemyAreaX = edgeRight.transform.localPosition.x - 1.0f;
@@ -80,14 +85,14 @@ public class TargetController : MonoBehaviour
minAgentAreaZ = edgeDown.transform.localPosition.z + 1.0f;
maxAgentAreaZ = edgeAgent_Enemy.transform.localPosition.z - 1.0f;
blockCont = SceneBlockContainerObj.GetComponent<SceneBlockContainer>();
envUICon = EnvironmentUIObj.GetComponent<EnvironmentUIControl>();
enemyCont = EnemyContainerObj.GetComponent<EnemyContainer>();
agentCharaCon = AgentObj.GetComponent<CharacterController>();
paramCon = ParameterContainerObj.GetComponent<ParameterContainer>();
worldUICon = WorldUIObj.GetComponent<WorldUIController>();
blockCont = sceneBlockContainerObj.GetComponent<SceneBlockContainer>();
envUICon = environmentUIObj.GetComponent<EnvironmentUIControl>();
enemyCont = enemyContainerObj.GetComponent<EnemyContainer>();
agentCharaCon = agentObj.GetComponent<CharacterController>();
paramCon = parameterContainerObj.GetComponent<ParameterContainer>();
worldUICon = worldUIObj.GetComponent<WorldUIController>();
hudCon = HUDObj.GetComponent<HUDController>();
raySensors = AgentObj.GetComponent<RaySensors>();
raySensors = agentObj.GetComponent<RaySensors>();
freeProb = 1 - attackProb - gotoProb - defenceProb;
targetNum = (int)SceneBlockContainer.Targets.Num;
if (freeProb < 0)
@@ -136,7 +141,7 @@ public class TargetController : MonoBehaviour
}
}
public void rollNewScene()
public void RollNewScene()
{
startTime = Time.time;// Reset StartTime as now time
leftTime = paramCon.timeLimit - Time.time + startTime;
@@ -147,19 +152,19 @@ public class TargetController : MonoBehaviour
Debug.Log("GOTO THIS TARGET!");
targetTypeInt = (int)SceneBlockContainer.Targets.Go;
int randBlockType = Random.Range(0, blockCont.goBlockPrefabs.Length);
// get choosed scene size
// get choosed scene size
sceneSize = blockCont.goBlockPrefabs[randBlockType].GetComponent<SceneBlock>().blockSize;
float randX = UnityEngine.Random.Range(minEnemyAreaX + sceneSize/2 + 1f, maxEnemyAreaX - sceneSize/2 - 1f);
float randZ = UnityEngine.Random.Range(minEnemyAreaZ + sceneSize/2 + 1f, maxEnemyAreaZ - sceneSize/2 - 1f);
float randX = UnityEngine.Random.Range(minEnemyAreaX + sceneSize / 2 + 1f, maxEnemyAreaX - sceneSize / 2 - 1f);
float randZ = UnityEngine.Random.Range(minEnemyAreaZ + sceneSize / 2 + 1f, maxEnemyAreaZ - sceneSize / 2 - 1f);
targetPosition = new Vector3(randX, 0f, randZ);
// Init Agent position
moveAgentToSpwanArea();
MoveAgentToSpwanArea();
// init scene block
blockCont.destroyBlock();
blockCont.createNewBlock(SceneBlockContainer.Targets.Go, randBlockType, targetPosition, group1Tag, group2Tag);
enemyCont.destroyAllEnemys();
enemyCont.randomInitEnemysExcept(hudCon.enemyNum, targetPosition, sceneSize);
blockCont.thisBlock.initBlock(EnvironmentObj);
blockCont.DestroyBlock();
blockCont.CreateNewBlock(SceneBlockContainer.Targets.Go, randBlockType, targetPosition, group1Tag, group2Tag);
enemyCont.DestroyAllEnemys();
enemyCont.RandomInitEnemysExcept(hudCon.enemyNum, targetPosition, sceneSize);
blockCont.thisBlock.InitBlock(environmentObj);
// set startDistance
firstRewardFlag = true;
}
@@ -169,19 +174,19 @@ public class TargetController : MonoBehaviour
Debug.Log("ATTACK!");
targetTypeInt = (int)SceneBlockContainer.Targets.Attack;
int randBlockType = Random.Range(0, blockCont.attackBlockPrefabs.Length);
// get choosed scene size
// get choosed scene size
sceneSize = blockCont.attackBlockPrefabs[randBlockType].GetComponent<SceneBlock>().blockSize;
float randX = UnityEngine.Random.Range(minEnemyAreaX + sceneSize/2 + 1f, maxEnemyAreaX - sceneSize/2 - 1f);
float randZ = UnityEngine.Random.Range(minEnemyAreaZ + sceneSize/2 + 1f, maxEnemyAreaZ - sceneSize/2 - 1f);
float randX = UnityEngine.Random.Range(minEnemyAreaX + sceneSize / 2 + 1f, maxEnemyAreaX - sceneSize / 2 - 1f);
float randZ = UnityEngine.Random.Range(minEnemyAreaZ + sceneSize / 2 + 1f, maxEnemyAreaZ - sceneSize / 2 - 1f);
targetPosition = new Vector3(randX, 0f, randZ);
// Init Agent position
moveAgentToSpwanArea();
MoveAgentToSpwanArea();
// init scene block
blockCont.destroyBlock();
blockCont.createNewBlock(SceneBlockContainer.Targets.Attack, randBlockType, targetPosition, group1Tag, group2Tag);
enemyCont.destroyAllEnemys();
enemyCont.randomInitEnemysExcept(hudCon.enemyNum, targetPosition, sceneSize);
blockCont.thisBlock.initBlock(EnvironmentObj);
blockCont.DestroyBlock();
blockCont.CreateNewBlock(SceneBlockContainer.Targets.Attack, randBlockType, targetPosition, group1Tag, group2Tag);
enemyCont.DestroyAllEnemys();
enemyCont.RandomInitEnemysExcept(hudCon.enemyNum, targetPosition, sceneSize);
blockCont.thisBlock.InitBlock(environmentObj);
// set startDistance
firstRewardFlag = true;
targetEnemySpawnFinish = false;
@@ -192,19 +197,19 @@ public class TargetController : MonoBehaviour
Debug.Log("DEFENCE!");
targetTypeInt = (int)SceneBlockContainer.Targets.Defence;
int randBlockType = Random.Range(0, blockCont.attackBlockPrefabs.Length);
// get choosed scene size
// get choosed scene size
sceneSize = blockCont.defencePrefabs[randBlockType].GetComponent<SceneBlock>().blockSize;
float randX = UnityEngine.Random.Range(minEnemyAreaX + sceneSize/2 + 1f, maxEnemyAreaX - sceneSize/2 - 1f);
float randZ = UnityEngine.Random.Range(minEnemyAreaZ + sceneSize/2 + 1f, maxEnemyAreaZ - sceneSize/2 - 1f);
float randX = UnityEngine.Random.Range(minEnemyAreaX + sceneSize / 2 + 1f, maxEnemyAreaX - sceneSize / 2 - 1f);
float randZ = UnityEngine.Random.Range(minEnemyAreaZ + sceneSize / 2 + 1f, maxEnemyAreaZ - sceneSize / 2 - 1f);
targetPosition = new Vector3(randX, 0f, randZ);
// Init Agent position
moveAgentTo(targetPosition);
MoveAgentTo(targetPosition);
// init scene block
blockCont.destroyBlock();
blockCont.createNewBlock(SceneBlockContainer.Targets.Defence, randBlockType, targetPosition, group1Tag, group2Tag);
enemyCont.destroyAllEnemys();
enemyCont.randomInitEnemysExcept(hudCon.enemyNum, targetPosition, sceneSize);
blockCont.thisBlock.initBlock(EnvironmentObj);
blockCont.DestroyBlock();
blockCont.CreateNewBlock(SceneBlockContainer.Targets.Defence, randBlockType, targetPosition, group1Tag, group2Tag);
enemyCont.DestroyAllEnemys();
enemyCont.RandomInitEnemysExcept(hudCon.enemyNum, targetPosition, sceneSize);
blockCont.thisBlock.InitBlock(environmentObj);
// set startDistance
firstRewardFlag = true;
}
@@ -212,23 +217,23 @@ public class TargetController : MonoBehaviour
{
//Debug.Log("Free");
targetTypeInt = (int)SceneBlockContainer.Targets.Free;
enemyCont.destroyAllEnemys();
enemyCont.randomInitEnemys(hudCon.enemyNum);
moveAgentToSpwanArea();
blockCont.destroyBlock();
enemyCont.DestroyAllEnemys();
enemyCont.RandomInitEnemys(hudCon.enemyNum);
MoveAgentToSpwanArea();
blockCont.DestroyBlock();
}
updateTargetStates();
envUICon.updateTargetType(targetTypeInt);
UpdateTargetStates();
envUICon.UpdateTargetType(targetTypeInt);
}
// get target observation states
public void updateTargetStates()
public void UpdateTargetStates()
{
// targettype, x,y,z, firebasesAreaDiameter
if (targetTypeInt == (int)SceneBlockContainer.Targets.Free)
{
targetState[0] = targetTypeInt;
for(int i = 1; i < targetState.Length; i++)
for (int i = 1; i < targetState.Length; i++)
targetState[i] = 0f;
}
else
@@ -246,7 +251,7 @@ public class TargetController : MonoBehaviour
}
// move Agent into Agent Spawn Area
public void moveAgentToSpwanArea()
public void MoveAgentToSpwanArea()
{
float randX = UnityEngine.Random.Range(minAgentAreaX, maxAgentAreaX); ;
float randZ = 0f;
@@ -263,22 +268,22 @@ public class TargetController : MonoBehaviour
int Y = 1;
Vector3 initAgentLoc = new Vector3(randX, Y, randZ);
moveAgentTo(initAgentLoc);
MoveAgentTo(initAgentLoc);
}
// move Agent to this position
public void moveAgentTo(Vector3 thisPosition)
public void MoveAgentTo(Vector3 thisPosition)
{
// while using transform.localPosition to move character
// u should turn off character Controller or it won't work
agentCharaCon.enabled = false;
AgentObj.transform.localPosition = thisPosition;
agentObj.transform.localPosition = thisPosition;
agentCharaCon.enabled = true;
}
// check over and get rewards
// 1 = success,2 = overtime,0 = notover
public (int, float,float) checkOverAndRewards()
public (int, float, float) CheckOverAndRewards()
{
int endTypeInt = 0;
float thisReward = 0;
@@ -288,9 +293,9 @@ public class TargetController : MonoBehaviour
{
case (int)SceneBlockContainer.Targets.Go:
// goto
(nowDistance, inArea) = blockCont.getAgentTargetDistanceAndInside(AgentObj.transform.position);
envUICon.updateTargetGauge(blockCont.thisBlock.firebasesBelong, blockCont.thisBlock.belongMaxPoint);
float areaTargetReward = getDistanceReward(nowDistance, inArea);
(nowDistance, inArea) = blockCont.GetAgentTargetDistanceAndInside(agentObj.transform.position);
envUICon.UpdateTargetGauge(blockCont.thisBlock.firebasesBelong, blockCont.thisBlock.belongMaxPoint);
float areaTargetReward = GetDistanceReward(nowDistance, inArea);
//if(inArea != 0)
if (blockCont.thisBlock.firebasesBelong >= blockCont.thisBlock.belongMaxPoint)
{
@@ -316,13 +321,14 @@ public class TargetController : MonoBehaviour
endTypeInt = (int)EndType.Running;
}
break;
case (int)SceneBlockContainer.Targets.Attack:
// attack
(nowDistance, inArea) = blockCont.getAgentTargetDistanceAndInside(AgentObj.transform.position);
envUICon.updateTargetGauge(blockCont.thisBlock.firebasesBelong, blockCont.thisBlock.belongMaxPoint);
if (blockCont.thisBlock.getInAreaNumber(group2Tag) <= 0 && targetEnemySpawnFinish)
(nowDistance, inArea) = blockCont.GetAgentTargetDistanceAndInside(agentObj.transform.position);
envUICon.UpdateTargetGauge(blockCont.thisBlock.firebasesBelong, blockCont.thisBlock.belongMaxPoint);
if (blockCont.thisBlock.GetInAreaNumber(group2Tag) <= 0 && targetEnemySpawnFinish)
{
Debug.Log(blockCont.thisBlock.getInAreaNumber(group2Tag));
Debug.Log(blockCont.thisBlock.GetInAreaNumber(group2Tag));
// win
// let the area belongs to me and kill every enmy in this area.
thisReward = 0;
@@ -350,11 +356,12 @@ public class TargetController : MonoBehaviour
endTypeInt = (int)EndType.Running;
}
break;
case (int)SceneBlockContainer.Targets.Defence:
//defence
// !!! DIDN't FINISH!!!
(nowDistance, inArea) = blockCont.getAgentTargetDistanceAndInside(AgentObj.transform.position);
envUICon.updateTargetGauge(blockCont.thisBlock.firebasesBelong, blockCont.thisBlock.belongMaxPoint);
(nowDistance, inArea) = blockCont.GetAgentTargetDistanceAndInside(agentObj.transform.position);
envUICon.UpdateTargetGauge(blockCont.thisBlock.firebasesBelong, blockCont.thisBlock.belongMaxPoint);
if (leftTime <= 0 && blockCont.thisBlock.firebasesBelong >= 0f)
{
// win
@@ -377,6 +384,7 @@ public class TargetController : MonoBehaviour
endTypeInt = (int)EndType.Running;
}
break;
case (int)SceneBlockContainer.Targets.Stay:
// Stay
// endless
@@ -384,9 +392,10 @@ public class TargetController : MonoBehaviour
endReward = 0;
endTypeInt = (int)EndType.Running;
break;
default:
//free kill
if (EnemyContainerObj.transform.childCount <= 0)
if (enemyContainerObj.transform.childCount <= 0)
{
// win
// thisReward = paramCon.winReward + (paramCon.timeBonusPerSecReward * leftTime);
@@ -411,18 +420,18 @@ public class TargetController : MonoBehaviour
}
break;
}
envUICon.showResult(endTypeInt);
worldUICon.updateChart(targetTypeInt, endTypeInt);
return (endTypeInt, thisReward,endReward);
envUICon.ShowResult(endTypeInt);
worldUICon.UpdateChart(targetTypeInt, endTypeInt);
return (endTypeInt, thisReward, endReward);
}
// caulculate sceneReward if close to target then get great reward
public float getDistanceReward(float nowDistance,int inarea)
public float GetDistanceReward(float nowDistance, int inarea)
{
if (firstRewardFlag)
{
// first distance record
(lastDistance, _) = blockCont.getAgentTargetDistanceAndInside(AgentObj.transform.position);
(lastDistance, _) = blockCont.GetAgentTargetDistanceAndInside(agentObj.transform.position);
firstRewardFlag = false;
}
float thisSceneReward = 0f;
@@ -442,13 +451,13 @@ public class TargetController : MonoBehaviour
}
// calculate kill reward base on killed enemy's position
public float killReward(Vector3 enemyPosition)
public float KillReward(Vector3 enemyPosition)
{
float thisKillReward = 0f;
if (targetTypeInt == (int)SceneBlockContainer.Targets.Attack)
{
// attack mode
(_, int isInArea) = blockCont.thisBlock.getDist_inArea(enemyPosition);
(_, int isInArea) = blockCont.thisBlock.GetDistInArea(enemyPosition);
if (isInArea == 1)
{
// kill in area enemy
@@ -473,13 +482,13 @@ public class TargetController : MonoBehaviour
}
// calculate hit reward base on killed enemy's position and now mode
public float hitEnemyReward(Vector3 enemyPosition)
public float HitEnemyReward(Vector3 enemyPosition)
{
float thisHitReward = 0f;
if (targetTypeInt == (int)SceneBlockContainer.Targets.Attack)
{
// attack mode
(_, int isInArea) = blockCont.thisBlock.getDist_inArea(enemyPosition);
(_, int isInArea) = blockCont.thisBlock.GetDistInArea(enemyPosition);
if (isInArea == 1)
{
// hit in area enemy
@@ -505,9 +514,9 @@ public class TargetController : MonoBehaviour
}
// get in area state
public int getInAreaState()
public int GetInAreaState()
{
if(targetTypeInt == (int)SceneBlockContainer.Targets.Go)
if (targetTypeInt == (int)SceneBlockContainer.Targets.Go)
{
return inArea;
}
@@ -519,41 +528,40 @@ public class TargetController : MonoBehaviour
// Play Mode method
// Initialize Play mode
public void playInitialize()
public void PlayInitialize()
{
targetTypeInt = (int)SceneBlockContainer.Targets.Stay;
envUICon.updateTargetType(targetTypeInt);
moveAgentToSpwanArea();
enemyCont.destroyAllEnemys();
blockCont.destroyBlock();
envUICon.UpdateTargetType(targetTypeInt);
MoveAgentToSpwanArea();
enemyCont.DestroyAllEnemys();
blockCont.DestroyBlock();
}
// change to attack mode
public void attackModeChange()
public void AttackModeChange()
{
targetTypeInt = (int)SceneBlockContainer.Targets.Attack;
envUICon.updateTargetType(targetTypeInt);
envUICon.UpdateTargetType(targetTypeInt);
}
// change to free mode
public void freeModeChange()
public void FreeModeChange()
{
targetTypeInt = (int)SceneBlockContainer.Targets.Free;
envUICon.updateTargetType(targetTypeInt);
envUICon.UpdateTargetType(targetTypeInt);
}
// change to goto mode
public void gotoModeChange()
public void GotoModeChange()
{
targetTypeInt = (int)SceneBlockContainer.Targets.Go;
envUICon.updateTargetType(targetTypeInt);
envUICon.UpdateTargetType(targetTypeInt);
}
// change to stay mode
public void stayModeChange()
public void StayModeChange()
{
targetTypeInt = (int)SceneBlockContainer.Targets.Stay;
envUICon.updateTargetType(targetTypeInt);
envUICon.UpdateTargetType(targetTypeInt);
}
}
}
+13 -13
View File
@@ -1,33 +1,32 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XCharts.Runtime;
public class WorldUIController : MonoBehaviour
{
public LineChart WinChart;
public LineChart winChart;
public int[] totalGames;
public int[] winGames;
private int maxXAxis = 0;
// Start is called before the first frame update
void Start()
private void Start()
{
totalGames = new int[(int)SceneBlockContainer.Targets.Num];
winGames = new int[(int)SceneBlockContainer.Targets.Num];
Array.Clear(totalGames, 0, (int)SceneBlockContainer.Targets.Num);
Array.Clear(winGames, 0, (int)SceneBlockContainer.Targets.Num);
//WinChart.Init();
WinChart.RemoveData();
winChart.RemoveData();
for (int i = 0; i < (int)SceneBlockContainer.Targets.Num; i++)
{
string lineName = Enum.GetName(typeof(SceneBlockContainer.Targets), i);
WinChart.AddSerie<Line>(lineName);
winChart.AddSerie<Line>(lineName);
}
}
public void updateChart(int targetType, int endType)
public void UpdateChart(int targetType, int endType)
{
float winRatio = 0f;
switch (endType)
@@ -37,27 +36,28 @@ public class WorldUIController : MonoBehaviour
totalGames[targetType] += 1;
winGames[targetType] += 1;
winRatio = (float)winGames[targetType] / totalGames[targetType];
WinChart.AddData(targetType, winRatio);
winChart.AddData(targetType, winRatio);
if (totalGames[targetType] > maxXAxis)
{
maxXAxis = totalGames[targetType];
WinChart.AddXAxisData(Convert.ToString(maxXAxis));
winChart.AddXAxisData(Convert.ToString(maxXAxis));
}
break;
case (int)TargetController.EndType.Lose:
//lose
totalGames[targetType] += 1;
winRatio = (float)winGames[targetType] / totalGames[targetType];
WinChart.AddData(targetType, winRatio);
winChart.AddData(targetType, winRatio);
if (totalGames[targetType] > maxXAxis)
{
maxXAxis = totalGames[targetType];
WinChart.AddXAxisData(Convert.ToString(maxXAxis));
winChart.AddXAxisData(Convert.ToString(maxXAxis));
}
break;
default:
break;
}
}
}
}
+8 -8
View File
@@ -1,13 +1,13 @@
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine;
public class rayInfoUI : MonoBehaviour
public class RayInfoUI : MonoBehaviour
{
TextMeshProUGUI infoText;
bool infoTextReady = false;
private TextMeshProUGUI infoText;
private bool infoTextReady = false;
// Start is called before the first frame update
void Start()
private void Start()
{
try
{
@@ -20,7 +20,7 @@ public class rayInfoUI : MonoBehaviour
}
}
public void updateInfo(string info,Vector3 infoPosition, Color infoColor,Camera facetoCamera)
public void UpdateInfo(string info, Vector3 infoPosition, Color infoColor, Camera facetoCamera)
{
if (!infoTextReady)
{
@@ -34,4 +34,4 @@ public class rayInfoUI : MonoBehaviour
transform.LookAt(facetoCamera.transform.position - v);
transform.Rotate(0, 180, 0);
}
}
}
+14 -13
View File
@@ -1,22 +1,21 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class states : MonoBehaviour
public class States : MonoBehaviour
{
public bool isDead = false;
public float MaxHP = 100;
float myHP = 100;
public float maxHP = 100;
private float myHP = 100;
void Start()
private void Start()
{
myHP = MaxHP;
myHP = maxHP;
}
void Update()
private void Update()
{
}
private void detactDeath()
private void DetactDeath()
{
if (myHP <= 0)
{
@@ -24,6 +23,7 @@ public class states : MonoBehaviour
isDead = true;
}
}
// while got hit
public void ReactToHit(float Damage, GameObject damageSource)
{
@@ -33,7 +33,7 @@ public class states : MonoBehaviour
{
if (damageSource.tag == "Player")
{
damageSource.GetComponent<AgentWithGun>().killRecord(transform.position);
damageSource.GetComponent<AgentWithGun>().KillRecord(transform.position);
Destroy(this.gameObject);
isDead = true;
}
@@ -44,15 +44,16 @@ public class states : MonoBehaviour
}
}
}
// get my hp from other script
public float getnowHP()
public float GetnowHP()
{
return myHP;
}
public void destroyMe()
public void DestroyMe()
{
Destroy(this.gameObject);
isDead = true;
}
}
}