public void OnSetTarget(TargetPoint target) { if(Target != null) { Target.RemoveLink(); } Target = target; Target.AddLink(); }
public void OnSetTarget(TargetPoint target) { if(Target != null) { Target.RemoveLink(); } Target = target; Target.AddLink(); targetPosition = Target.transform.position; Agent.stoppingDistance = Random.Range(1.0F, 15.0F); }
protected bool AcquireTarget(out TargetPoint target) { if (TargetPoint.FillBuffer(transform.localPosition, targetingRange)) { target = TargetPoint.RandomBuffered; return(true); } target = null; return(false); }
public static TargetPoint[] AllTargets(Vector2 position, float range) { TargetPoint[] points = new TargetPoint[100]; BufferedCount = Physics2D.OverlapCircleNonAlloc( position, range, buffer, enemyLayerMask ); foreach (var x in buffer) { points.Append(x.GetComponent <TargetPoint>()); } return(points); }
public void Modify(Tower tower, float damage) { TargetPoint.FillBuffer(tower.transform.localPosition, 3.5f, Game.enemyLayerMask); for (int i = 0; i < TargetPoint.BufferedCount; i++) { TargetPoint localTarget = TargetPoint.GetBuffered(i); localTarget.Enemy.ApplyDamage(40f, false); Explosion explosion = Game.SpawnExplosion(true); explosion.Initialize(localTarget, this.GetType().Name + level); // localTarget.Enemy.Effects.Add(explosion); } }
public override void LaunchCannon(TowerBase tower, TargetPoint target, Vector3 launchVelocity, float explodeRadius) { base.LaunchCannon(tower, target, launchVelocity, explodeRadius); this.tower = tower; this.target = target; this.launchVelocity = launchVelocity; this.explodeRadius = explodeRadius; targetPos = target.Position; transform.position = LaunchPoint; }
protected void FullfillTargets() { GameObject[] hings = FindObjectsOfType(typeof(GameObject)) as GameObject[]; for (int i = 0; i < hings.Length; ++i) { TargetPoint pt = hings[i].GetComponent <TargetPoint>(); if (pt) { Targets.Add(hings[i]); } } }
public void Launch(TargetPoint target) { Vector3 launchPoint = mortar.position; //Vector3 targetPoint = new Vector3(launchPoint.x + 3f, 0f, launchPoint.z); Vector3 targetPoint = target.Position; targetPoint.y = 0f; Vector2 dir; dir.x = targetPoint.x - launchPoint.x; dir.y = targetPoint.z - launchPoint.z; float x = dir.magnitude; float y = -launchPoint.y; dir /= x; float g = 9.81f; float s = launchSpeed; float s2 = s * s; float r = s2 * s2 - g * (g * x * x + 2f * y * s2); Debug.Assert(r >= 0f, "Launch velocity insufficient for range!"); float tanTheta = (s2 + Mathf.Sqrt(r)) / (g * x); float cosTheta = Mathf.Cos(Mathf.Atan(tanTheta)); float sinTheta = cosTheta * tanTheta; float reallyTime = x / (s * cosTheta); mortar.localRotation = Quaternion.LookRotation(new Vector3(dir.x, tanTheta, dir.y)); Game.SpawnShell().Initialize(launchPoint, targetPoint, new Vector3(s * cosTheta * dir.x, s * sinTheta, s * cosTheta * dir.y), shellBlastRadius, shellDamage); //Vector3 prev = launchPoint, next; //int times = 50; //for(int i = 0; i <= times; ++i) //{ // float t = i / (float)times * reallyTime; // float dx = s * cosTheta * t; // float dy = s * sinTheta * t - 0.5f * g * t * t; // next = launchPoint + new Vector3(dir.x * dx, dy, dir.y * dx); // Debug.DrawLine(prev, next, Color.blue, 1f); // prev = next; //} //Debug.DrawLine(launchPoint, targetPoint, Color.yellow, 1f); //Debug.DrawLine( // new Vector3(launchPoint.x, 0.01f, launchPoint.z), // new Vector3(launchPoint.x + dir.x * x, 0.01f, launchPoint.z + dir.y * x), // //new Vector3(targetPoint.x, 0.01f, targetPoint.z), // Color.white, 1f); }
public void Initialize(Vector3 position, float blastRange, float demage = 0f) { if (demage > 0f) { TargetPoint.FillBuffer(position, blastRange); for (int i = 0; i < TargetPoint.BufferedCount; i++) { TargetPoint.GetBuffered(i).Enemy.ApplyDemage(demage); } } transform.localPosition = position; scale = 2f * blastRange; }
public void Launch(TargetPoint target) { Vector3 launchPoint = mortar.position; Vector3 targetPoint = target.Position; targetPoint.y = 0f; Vector2 dir; dir.x = targetPoint.x - launchPoint.x; dir.y = targetPoint.z - launchPoint.z; float x = dir.magnitude; float y = -launchPoint.y; dir /= x; float g = 9.81f; float s = launchSpeed; float s2 = s * s; float r = s2 * s2 - g * (g * x * x + 2f * y * s2); Debug.Assert(r >= 0f, "Launch velocity insufficient for range!"); float tanTheta = (s2 + Mathf.Sqrt(r)) / (g * x); float cosTheta = Mathf.Cos(Mathf.Atan(tanTheta)); float sinTheta = cosTheta * tanTheta; mortar.localRotation = Quaternion.LookRotation(new Vector3(dir.x, tanTheta, dir.y)); Game.SpawnShell().Initialize(launchPoint, targetPoint, new Vector3(s * cosTheta * dir.x, s * sinTheta, s * cosTheta * dir.y), shellBlastRadius, shellDamage); /*Vector3 prev = launchPoint, next; * for (int i = 1; i <= 10; i++) * { * float t = i / 10f; * float dx = s * cosTheta * t; * float dy = s * sinTheta * t - 0.5f * g * t * t; * next = launchPoint + new Vector3(dir.x * dx, dy, dir.y * dx); * Debug.DrawLine(prev, next, Color.blue, 1f); * prev = next; * } * * Debug.DrawLine(launchPoint, targetPoint, Color.yellow, 1f); * Debug.DrawLine( * new Vector3(launchPoint.x, 0.01f, launchPoint.z), * new Vector3(launchPoint.x + dir.x * x, 0.01f, launchPoint.z + dir.y * x), * Color.white, 1f * );*/ }
/// <summary> /// Gets the target point behavior from an argument. /// </summary> /// <param name="arg">The argument to parse.</param> /// <param name="targetPoint">The parsed value, set to start by default.</param> /// <returns>True if the parse was valid.</returns> private static bool GetTargetPoint(string arg, out TargetPoint targetPoint) { targetPoint = TargetPoint.Start; switch (arg) { case VAL_START: targetPoint = TargetPoint.Start; return(true); case VAL_FINISH: targetPoint = TargetPoint.Finish; return(true); case VAL_NEAREST: targetPoint = TargetPoint.Nearest; return(true); default: return(false); } }
public void Initialize(Vector3 position, float blastRadius, float damage = 0f) { if (damage > 0f) { TargetPoint.FillBuffer(position, blastRadius); for (int i = 0; i < TargetPoint.BufferedCount; i++) { TargetPoint.GetBuffered(i).Enemy.ApplyDamage(damage); } } transform.localPosition = position; // transform.localScale = Vector3.one * (2f * blastRadius); scale = 2f * blastRadius; }
public override void OnDamageTarget(TargetPoint target) { base.OnDamageTarget(target); if (!target.Enemy.IsDead) { target.Enemy.TakeDamage(Damage); if (UnityEngine.Random.Range(0, 100) < freezeChance) { target.Enemy.Freeze(moveSpeedDecrese, freezeDuration); } } }
/// <summary> /// Find the grade of the measurement when compared to the given target point. If the target point is not in the /// test or the scalars are not compatible, we will return false and the grade will be set to null. Otherwise, we /// will set the grade to the appropriate grade and return true. /// </summary> /// <returns><c>true</c>, if measurement pass was doesed, <c>false</c> otherwise.</returns> /// <param name="targetPoint">Target point.</param> /// <param name="measurement">Measurement.</param> public bool FindGradeForMeasurement(TargetPoint targetPoint, Scalar measurement, out Grade grade) { if (!targetPoints.Contains(targetPoint) || !targetPoint.measurement.CompatibleWith(measurement.unit.quantity)) { grade = null; return(false); } measurement = measurement.ConvertTo(targetPoint.measurement.unit); var errorBand = Math.Abs(targetPoint.measurement.amount - measurement.amount) / targetPoint.measurement.amount; grade = FindGradeForBand(errorBand); return(true); }
private bool AcquireTarget() { Collider[] targets = Physics.OverlapSphere( transform.localPosition, TargetingRange, _enemyLayerMask); if (targets.Length > 0) { _target = targets[0].GetComponent <TargetPoint>(); Debug.Assert(_target != null, "Targeted none-target!", targets[0]); return(true); } _target = null; return(false); }
/// <summary> /// Add point that lives on arbitrary surface /// rayTarget Must compute ray-intersections in *scene space* /// </summary> public virtual int AppendTargetPoint(string name, Colorf color, IIntersectionTarget sceneRayTarget, float sizeScene = -1) { TargetPoint pt = new TargetPoint(); pt.id = point_id_counter++; pt.name = name; pt.color = color; pt.layer = -1; pt.sizeS = (sizeScene > 0) ? sizeScene : default_indicator_size; pt.initialized = false; pt.RayTarget = sceneRayTarget; GizmoPoints[pt.id] = pt; OnPointAdded(pt); return(pt.id); }
public override void Modify(TargetPoint enemy, float damage) { TargetPoint.FillBuffer(enemy.Position, 3.5f, Game.enemyLayerMask); for (int i = 0; i < TargetPoint.BufferedCount; i++) { TargetPoint localTarget = TargetPoint.GetBuffered(i); if (localTarget != enemy) { localTarget.Enemy.ApplyDamage(damage / 2f, false); Explosion explosion = Game.SpawnExplosion(false); explosion.Initialize(localTarget, this.GetType().Name + level); localTarget.Enemy.Effects.Add(explosion); } } }
public override void Modify(TargetPoint target, float damage) { WarEntity b = (WarEntity)target.Enemy.Effects.Behaviors.Find(effect => ((WarEntity)effect).name1 == this.GetType().Name + level); if (b != null) { b.age = 0f; } else { Corrosion corrosion = Game.SpawnCorrosion(); corrosion.Initialize(target, this.GetType().Name + level); target.Enemy.Effects.Add(corrosion); } }
public override void CalcWants(Option <Tile> MaybeFloor) { MaybeFloor.Match( some: Floor => { TargetPoint.Match( some: Target => { }, none: () => { UpdateTargetPoint(Floor.Point); } ); }, none: () => { } ); }
// установка новой цели движения public void OnSetTarget(TargetPoint point) { if (targetPoint != null) { targetPoint.DeleteLink(); } if (!TerrainNavGrid.IsPositionCorrect(point.Position)) { return; } StopMove(); targetPoint = point; targetPoint.AddLink(); PathImage = new PathImage(GameParams.Width, GameParams.Length); SetMovePosition(targetPoint.Position); }
private void UpdateGrabMarker() { Enemy boss = MonoBehaviourSingleton <StageObjectManager> .I.boss; if (!(boss == null) && !boss.isDead) { EnemyRegionWork enemyRegionWork = null; EnemyRegionWork[] regionWorks = boss.regionWorks; if (regionWorks != null) { for (int i = 0; i < regionWorks.Length; i++) { if (regionWorks[i].weakState == Enemy.WEAK_STATE.WEAK_GRAB) { enemyRegionWork = regionWorks[i]; break; } } if (enemyRegionWork == null) { UnableGrabMarker(); } else { TargetPoint targetPoint = boss.SearchTargetPoint(enemyRegionWork.regionId); if (targetPoint == null) { Debug.LogWarning((object)"Not found TargetPoint."); } else { if (m_grabMarker == null) { m_grabMarker = new TargetMarker(base._transform); } m_grabMarker.UpdateByTargetPoint(targetPoint, "ef_btl_target_cannon_03"); if (uiGrabStatusGizmo == null) { uiGrabStatusGizmo = MonoBehaviourSingleton <UIStatusGizmoManager> .I.CreateGrab(); } uiGrabStatusGizmo.targetEnemy = boss; uiGrabStatusGizmo.targetPoint = targetPoint; } } } } }
protected bool TrackTarget(ref TargetPoint target) { if (target == null || !target.Enemy.IsValid) { return(false); } Vector2 a = transform.position; Vector2 b = target.Position; if (Vector2.Distance(a, b) > targetingRange + 0.125f) { target = null; return(false); } return(true); }
//Launch a shell to the destionation pointed public void Launch(TargetPoint target) { Vector3 launchPoint = mortar.position; Vector3 targetPoint = target.Position; targetPoint.y = 0f; //Drawing the triangle Vector2 dir; dir.x = targetPoint.x - launchPoint.x; dir.y = targetPoint.z - launchPoint.z; //Targeting triangle float x = dir.magnitude; float y = -launchPoint.y; dir /= x; //Launch angle float g = 9.81f; //gravity float s = launchSpeed; //speed float s2 = s * s; float r = s2 * s2 - g * (g * x * x + 2f * y * s2); //Check if the range is enough if (r < 0f) { Debug.Assert(r >= 0f, "Launch velocity insufficient for range!"); return; } float tanTheta = (s2 + Mathf.Sqrt(r)) / (g * x); float cosTheta = Mathf.Cos(Mathf.Atan(tanTheta)); float sinTheta = cosTheta * tanTheta; //Rotate the mortar so it face it's target mortar.localRotation = Quaternion.LookRotation(new Vector3(dir.x, tanTheta, dir.y)); //Launch a shell Game.SpawnShell().Initialize( launchPoint, targetPoint, new Vector3(s * cosTheta * dir.x, s * sinTheta, s * cosTheta * dir.y), shellBlastRadius, shellDamage ); }
public void Modify(Tower tower) { buff.level = level; buff.name1 = buff.GetType().Name + level; TargetPoint.FillBuffer(tower.transform.localPosition, 3.5f, Game.towerLayerMask); Debug.Log(TargetPoint.BufferedCount); for (int i = 0; i < TargetPoint.BufferedCount; i++) { TargetPoint localTarget = TargetPoint.GetBuffered(i); Debug.Log("LT: " + localTarget); Debug.Log("Tower: " + localTarget.Tower); if (localTarget != null && !localTarget.Tower.StatusEffects.Any(effect => effect.name1 == buff.name1)) { localTarget.Tower.StatusEffects.Add(buff); } } }
protected override void Shoot(TargetPoint target) { base.Shoot(target); ProjectileBase projectile = pool.Get(); projectile.gameObject.SetActive(true); projectile.FireBullet(this, target, projectileSpeed); EventHandler handler = null; handler = (sender, e) => { pool.ReturnToPool(projectile); projectile.ReturnToPool -= handler; }; projectile.ReturnToPool += handler; }
public void Launch(TargetPoint target) { Vector3 launchPoint = mortar.position; Vector3 targetPoint = target.Position; targetPoint.y = 0f; Vector2 dir; dir.x = targetPoint.x - launchPoint.x; dir.y = targetPoint.z - launchPoint.z; float x = dir.magnitude; float y = -launchPoint.y; dir /= x; float g = 9.81f; float s = launchSpeed; float s2 = s * s; float r = s2 * s2 - g * (g * x * x + 2f * y * s2); Debug.Assert(r >= 0f, "Launch velocity insufficient for range!"); float tanTheta = (s2 + Mathf.Sqrt(r)) / (g * x); float cosTheta = Mathf.Cos(Mathf.Atan(tanTheta)); float sinTheta = cosTheta * tanTheta; mortar.localRotation = Quaternion.LookRotation(new Vector3(dir.x, tanTheta, dir.y)); try { Game.SpawnShell().Initialize( launchPoint, targetPoint, new Vector3(s * cosTheta * dir.x, s * sinTheta, s * cosTheta * dir.y), shellBlastRadius, shellDamage ); } catch { GameCompiler.SpawnShell().Initialize( launchPoint, targetPoint, new Vector3(s * cosTheta * dir.x, s * sinTheta, s * cosTheta * dir.y), shellBlastRadius, shellDamage ); } }
private void Shooting() { if (!_isShooting && (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) && _targetIndex != -1) { _isShooting = true; GameObject obj = _poolingSystem.Dequeue(_missileTag, _cannon.position, _cannon.rotation); var missile = obj.GetComponent <PlayerMissile>(); if (missile) { _audioManager.PlayPlayerShotClip(); _targetToDestroy = _visibleTargets[_targetIndex]; missile.Target = _targetToDestroy.Target; missile.OnAfterHit += OnAfterShoot; } } }
protected bool TrackTarget(ref TargetPoint target) { if (target == null) { return(false); } Vector3 a = transform.localPosition; Vector3 b = target.Position; float x = a.x - b.x; float z = a.z - b.z; float r = targetingRange + 0.125f * target.Enemy.Scale; if (x * x + z * z > r * r) { target = null; return(false); } return(true); }
private bool TrackTarget() { if (_target == null) { return(false); } var a = transform.position; var b = _target.Position; //0.125 碰撞器的半径 if (Vector3.Distance(a, b) > TargetingRange + 0.125f * _target.Enemy.Scale) { _target = null; return(false); } return(true); }
private bool AcquireTarget() { Vector3 a = transform.localPosition; Vector3 b = a; b.y += 3f; Collider[] targets = Physics.OverlapCapsule(/*transform.localPosition*/ a, b, targetingRange, enemyLayerMask); if (targets != null && targets.Length > 0) { target = targets[0].GetComponent <TargetPoint>(); Debug.Assert(target != null, "Targeted non-enemy!", targets[0]); return(true); } target = null; return(false); }
bool AcquireTarget() { Vector3 a = transform.localPosition; Vector3 b = a; b.y += 2f; int hits = Physics.OverlapCapsuleNonAlloc( a, b, targetingRange, targetsBuffer, enemyLayerMask ); if (hits > 0) { target = targetsBuffer[Random.Range(0, hits)].GetComponent <TargetPoint>(); Debug.Assert(target != null, "Targeted non-enemy", targetsBuffer[0]); return(true); } target = null; return(false); }
public void Launch(TargetPoint target) { // Find target point Vector3 launchPoint = mortar.position; Vector3 targetPoint = target.Position; targetPoint.y = 0f; // Claculate direction vector Vector2 dir; dir.x = targetPoint.x - launchPoint.x; dir.y = targetPoint.z - launchPoint.z; float x = dir.magnitude; float y = -launchPoint.y; dir /= x; // Calculate launch angle float g = 9.81f; // gravity float s = launchSpeed; float s2 = s * s; float r = s2 * s2 - g * (g * x * x + 2f * y * s2); Debug.Assert(r >= 0f, "Launch velocity insufficient for range!"); float tanTheta = (s2 + Mathf.Sqrt(r)) / (g * x); float cosTheta = Mathf.Cos(Mathf.Atan(tanTheta)); float sinTheta = cosTheta * tanTheta; // Set Morter turret rotation mortar.localRotation = Quaternion.LookRotation(new Vector3(dir.x, tanTheta, dir.y)); // Spawn shell Game.SpawnShell().Initialize( launchPoint, targetPoint, new Vector3(s * cosTheta * dir.x, s * sinTheta, s * cosTheta * dir.y), shellBlastRadius, shellDamage ); }
private void CreateScalpHotSpot(Vector3 p, Quaternion r) { if (scalpHotSpot.pos != null && scalpHotSpot.pos.transform.FindChild("point") != null) { DestroyImmediate(scalpHotSpot.pos.transform.FindChild("point").gameObject); DestroyImmediate(scalpHotSpot.pos.gameObject); DestroyImmediate(scalpHotSpot.rot.gameObject); } TargetPoint newHotSpot = new TargetPoint(false); GameObject hs = new GameObject(); hs.transform.position = p; hs.transform.rotation = r; hs.transform.parent = GameObject.Find("Head").transform; //GameObject pshere = GameObject.CreatePrimitive(PrimitiveType.Sphere); GameObject psphere = Instantiate(GameObject.Find("HotSpot Arrow")); //pshere.transform.localScale = new Vector3(0.01F, 0.01F, 0.01F); psphere.transform.position = hs.transform.position; psphere.transform.rotation = hs.transform.rotation; psphere.transform.parent = hs.transform; psphere.name = "point"; hs.name = "Scalp Hot Spot"; newHotSpot.pos = hs; newHotSpot.rot = hs; newHotSpot.ID = hs.name; scalpHotSpot = newHotSpot; }
private void FillPointslist(GameObject[] points_prefabs, List<TargetPoint> pointsList) { foreach (GameObject point in points_prefabs) { TargetPoint tp = new TargetPoint(point); if (point.tag == "point_land" || point.tag == "point_air") tp.edgeType = "land"; // точки траектории по воздуху ставим в ленд, там все равно не используется edgeType else if (point.tag == "point_hollow") tp.edgeType = "hollow"; else { tp.edgeType = "land"; tp.isFinalTarget = true; } pointsList.Add(tp); } }
// Update is called once per frame void Update() { coilTracker.setStylusSensitiveTrackingState(matching); if (matching) { CalculateOffsets(); if (logging) { Log(); } } if (settingGrid && (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.Mouse1))) { currentGrid.points.Add(CreateGridPoint()); } if (usingGrid && Input.GetKeyDown(KeyCode.Mouse1) && !matching) { MouseSelectGridPoint(); } if (settingHotSpot && (Input.GetKeyDown(KeyCode.Space))) { TargetPoint newHotSpot = new TargetPoint(false); GameObject hs = new GameObject(); hs.transform.position = GameObject.Find(coilTracker.coilName).transform.FindChild("container").FindChild("hotspot").transform.position; hs.transform.rotation = GameObject.Find(coilTracker.coilName).transform.FindChild("container").FindChild("hotspot").transform.rotation; CreateScalpHotSpot(GameObject.Find(coilTracker.coilName).transform.FindChild("container").FindChild("hotspot").transform.position, GameObject.Find(coilTracker.coilName).transform.FindChild("container").FindChild("hotspot").transform.rotation); setHotSpot.text = "Set Hot Spot"; settingHotSpot = false; } if (!matching && logging) { LogErrorToggle(errorToggleText); } }
private void MouseSelectGridPoint() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { int result; if (Int32.TryParse(hit.collider.gameObject.transform.parent.gameObject.name, out result)) { tPoint = currentGrid.points[result]; if (tPoint.fired == false) { tPoint.ID = result.ToString(); target(); } } else if (hit.collider.gameObject.transform.parent.gameObject.name.Equals("Scalp Hot Spot")) { tPoint = scalpHotSpot; if (tPoint.fired == false) { target(); } } } }
public Path GetPath(TargetPoint CurrentPoint, string enemytype) { //Debug.Log("navigation GetPath "); // Метод возвращает траекторию выбранную из массива случайным образом с учетом приоритетов , а также содержащую точку в которой объект находится сейчас //Заполняем словарь в котором содержаться только доступные траектории и их относительные приоритеты List<Path> temp_PathList = null; switch (enemytype) { case "inf": temp_PathList = PathList; break; case "air": temp_PathList = PathList_air; break; } Path defaultPath = null; ; // Используем эту траекторию в случае фейла алгоритма Dictionary<Path, float> Available_PathList = new Dictionary<Path, float>(); //закэшировать int SUMPriority = 0; // Сумма приоритетов всех доступных траекторий, это значение мы примем за 100 % при расчете приоритетов //Пробегаемся по всем доступным траекториям и вычисляем SUMPriority foreach (Path item in temp_PathList) { /* if (item == null) Debug.Log("NULL "); Debug.Log("temp_PathList " + temp_PathList.Count); Debug.Log("PathName " + item.PathName); Debug.Log("item.PointsList " + item.PointsList.Count); */ if (item.PointsList.Contains(CurrentPoint)) { if (defaultPath == null) { defaultPath = item; } SUMPriority += item.PathPriority; } } //Пробегаемся второй раз и заполняем словарь Available_PathList //Debug.Log("temp_PathList " + temp_PathList.Count); foreach (Path item in temp_PathList) { if (item.PointsList.Contains(CurrentPoint)) { //debugmanager.DrawDebugLine(new Vector2(0, 0), CurrentPoint.position, Color.red); float _priority = (float)item.PathPriority / SUMPriority; Available_PathList.Add(item, _priority); //Debug.Log("item.PathName" + item.PathName); //Debug.Log("_priority" + _priority); } } //Debug.Log("Available_PathList " + Available_PathList.Count); //Собственно выбираем траекторию var rnd = random.NextDouble(); //Получаем значение между 0 и 1 foreach (var item in Available_PathList) { if (rnd < Available_PathList[item.Key]) //Если значение приоритета больше чем случайное значение, то возвращаем его. В противном случае уменьшаем случайное значение и переходим к след элементу массива { //Debug.Log("Get Path " + item.Key.PathName + " prioprity: " + Available_PathList[item.Key] ); return item.Key; } rnd -= Available_PathList[item.Key]; } return defaultPath; }
public void ImportGrid() { DestroyCurrentGrid(); //String path = EditorUtility.OpenFilePanel("Select Grid", Application.dataPath + @"\Grids", "txt"); string path = Application.dataPath + @"\Grids\Load"; if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } string[] fileNames = System.IO.Directory.GetFiles(path); System.IO.FileStream filestream = new System.IO.FileStream(fileNames[0], System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); System.IO.StreamReader file = new System.IO.StreamReader(filestream); Grid newGrid = new Grid(file.ReadLine(), new List<TargetPoint>()); int points = System.Convert.ToInt32(file.ReadLine()); for (int i = 0; i < points; i++) { TargetPoint t = new TargetPoint(false); string data = file.ReadLine(); char[] d = new char[1]; d[0] = '\t'; string[] dims = data.Split(d); t.pos = new GameObject(); //t.pos.transform.position = GameObject.Find("Head").transform.InverseTransformPoint(GameObject.Find("Center").transform.TransformPoint(new Vector3((float)System.Convert.ToDouble(dims[1]), (float)System.Convert.ToDouble(dims[2]), (float)System.Convert.ToDouble(dims[3])))); t.pos.transform.position = GameObject.Find("Center").transform.TransformPoint(new Vector3((float)System.Convert.ToDouble(dims[1]), (float)System.Convert.ToDouble(dims[2]), (float)System.Convert.ToDouble(dims[3]))); if (dims[0].Equals("0")) { t.rot = new GameObject(); t.rot.transform.rotation = new Quaternion((float)System.Convert.ToDouble(dims[4]), (float)System.Convert.ToDouble(dims[5]), (float)System.Convert.ToDouble(dims[6]), (float)System.Convert.ToDouble(dims[7])); } else { t.rot = null; } newGrid.points.Add(t); } string datahs = file.ReadLine(); char[] dhs = new char[1]; dhs[0] = '\t'; string[] dimshs = datahs.Split(dhs); if (dimshs[0].Equals("0")) { Vector3 p = GameObject.Find("Center").transform.TransformPoint(new Vector3((float)System.Convert.ToDouble(dimshs[1]), (float)System.Convert.ToDouble(dimshs[2]), (float)System.Convert.ToDouble(dimshs[3]))); Quaternion r = new Quaternion((float)System.Convert.ToDouble(dimshs[4]), (float)System.Convert.ToDouble(dimshs[5]), (float)System.Convert.ToDouble(dimshs[6]), (float)System.Convert.ToDouble(dimshs[7])); CreateScalpHotSpot(p, r); } file.Close(); currentGrid = newGrid; foreach (TargetPoint point in currentGrid.points) { point.pos.transform.parent = GameObject.Find("Head").transform; point.pos.name = currentGrid.points.IndexOf(point).ToString(); //GameObject pshere = GameObject.CreatePrimitive(PrimitiveType.Sphere); //pshere.name = "point"; //pshere.transform.localScale = new Vector3(0.005F, 0.005F, 0.005F); //pshere.transform.position = point.pos.transform.position; //pshere.transform.parent = point.pos.transform; VisualizePoint(point.pos, point.rot); } settingGrid = false; usingGrid = true; matching = false; }
public TargetPoint GetTarget(Vector2 _position, TargetPoint _currentNextTarget, string enemytype) { //Debug.Log("------------------------------------------------------------------------Get target "); // var debugmanager = GameObject.Find("DebugManager").GetComponent<DebugManager>(); TargetPoint _target = _currentNextTarget; //На случай если не удасться найти ничего подходящего, оставляем текущую точку //Из массива TP_Array получаем все точки удовлетворяющие условиям List<TargetPoint> temp_TP_Array = null; switch (enemytype) { case "inf": temp_TP_Array = TP_Array; break; case "air": temp_TP_Array = TP_Array_air; break; } var query= from point in temp_TP_Array where (Vector2.Distance(_position, point.position)<7) orderby Vector2.Distance(_position, point.position) ascending select point; foreach (TargetPoint item in query) { RaycastHit2D hit = Physics2D.Linecast(_position, item.position, myLayerMask); if (hit.point.x==0 ) //Оставляем только те точки которые достаточно близко и в прямой видимости, если лайнкаст не встречает препятсвия то точка hit = 0.0 { _target = item; debugmanager.DrawDebugLine(_position, item.position, Color.blue); break; } } return _target; }
private TargetPoint CreateGridPoint() { TargetPoint point = new TargetPoint(false); GameObject pos = new GameObject(); pos.transform.position = GameObject.Find("Stylus").transform.FindChild("Point").position; pos.transform.parent = GameObject.Find("Head").transform; point.pos = pos; point.rot = new GameObject(); pos.name = currentGrid.points.Count.ToString(); VisualizePoint(pos); return point; }
public void setGridManualButtonPress() { if (!settingGrid) { GameObject.Find("StylusTracker").GetComponent<Stylus>().setStylusSensitiveTrackingState(true); GameObject.Find("Set Grid").transform.FindChild("Text").GetComponent<Text>().text = "Confirm Grid"; setGridManual(); } else { GameObject.Find("StylusTracker").GetComponent<Stylus>().setStylusSensitiveTrackingState(false); UnityEngine.Debug.Log("ready to select"); GameObject.Find("Set Grid").transform.FindChild("Text").GetComponent<Text>().text = "New Manual Grid"; foreach (TargetPoint point in currentGrid.points) { TargetPoint a = new TargetPoint(); TargetPoint b = new TargetPoint(); TargetPoint c = new TargetPoint(); float distanceA = -1; float distanceB = -1; float distanceC = -1; int count = 0; foreach (TargetPoint p in currentGrid.points) { if (!p.Equals(point)) { if (count == 0) { distanceA = Vector3.Distance(point.pos.transform.position, p.pos.transform.position); a = p; } else if (count == 1) { distanceB = Vector3.Distance(point.pos.transform.position, p.pos.transform.position); if (distanceB > distanceA) { b = p; } else { float switchF = distanceA; distanceA = distanceB; distanceB = switchF; b = a; a = p; } } else if (count == 3) { distanceC = Vector3.Distance(point.pos.transform.position, p.pos.transform.position); if (distanceC < distanceA && distanceC < distanceB) { float switchF = distanceA; distanceA = distanceC; distanceC = distanceB; distanceB = switchF; c = b; b = a; a = p; } else if (distanceC > distanceA && distanceC < distanceB) { float switchF = distanceB; distanceB = distanceC; distanceB = switchF; c = b; b = p; } else { c = p; } } else { float distance = Vector3.Distance(point.pos.transform.position, p.pos.transform.position); if (distance < distanceA && distance < distanceB && distance < distanceC) { distanceC = distanceB; distanceB = distanceA; distanceA = distance; c = b; b = a; a = p; } else if (distance > distanceA && distance < distanceB && distance < distanceC) { distanceC = distanceB; distanceB = distance; c = b; b = p; } else if (distance > distanceA && distance > distanceB && distance < distanceC) { distanceC = distance; c = p; } } count++; } } Vector3 side1 = a.pos.transform.position - point.pos.transform.position; Vector3 side2b = b.pos.transform.position - point.pos.transform.position; Vector3 side2c = c.pos.transform.position - point.pos.transform.position; Vector3 cross; if (Math.Abs(Vector3.Dot(side1.normalized, side2b.normalized)) < Math.Abs(Vector3.Dot(side1.normalized, side2c.normalized))) { cross = Vector3.Cross(side2b, side1); } else { cross = Vector3.Cross(side2c, side1); } GameObject center = GameObject.Find("Center").gameObject; Vector3 toCenter = center.transform.position - point.pos.transform.position; point.rot.transform.rotation = Quaternion.LookRotation(cross); if (Vector3.Dot(point.rot.transform.forward.normalized, toCenter.normalized) > 0) { point.rot.transform.rotation = Quaternion.LookRotation(-cross); } point.rot.transform.LookAt(point.rot.transform.up, point.rot.transform.forward); point.pos.transform.FindChild("point").transform.rotation = point.rot.transform.rotation; } settingGrid = false; usingGrid = true; GameObject.Find("ScalpGenerator").GetComponent<ScalpGenerator>().waitingToDraw = true; } }
private List<TargetPoint> FillPointsList(GameObject[] points_prefabs, List<TargetPoint> Common_tp_Array) { List < TargetPoint > _pointslist=new List<TargetPoint>(); foreach (GameObject pointGO in points_prefabs) { TargetPoint point = new TargetPoint(pointGO); if (Common_tp_Array.Count == 0) //для самой первой точки { Common_tp_Array.Add(point); _pointslist.Add(point); } else { TargetPoint _commontp = ArrayHasMatch_pos(pointGO, Common_tp_Array); if (_commontp != null) { _pointslist.Add(_commontp); } else { Common_tp_Array.Add(point); _pointslist.Add(point); } } } return _pointslist; }