public static bool CheckWallCollison(this AIHeroClient player, Vector3 targetpos) { for (int i = 0; i < targetpos.Distance(player.Position); i += 30) { Vector3 wallPosition = targetpos.ExtendVector3(player.Position, targetpos.Distance(player.Position) - i); if (NavMesh.GetCollisionFlags(wallPosition).HasFlag(CollisionFlags.Wall) || NavMesh.GetCollisionFlags(wallPosition).HasFlag(CollisionFlags.Building)) return true; } return false; }
/// <summary> /// Moves to somewhere. /// </summary> /// <param name="location">where to move to</param> /// <param name="destinationName">name of location for debugging purposes</param> /// <param name="range">how close it should get</param> public static async Task<bool> Execute(Vector3 location, string destinationName = "", float range = 10f) { while (ZetaDia.IsInGame && location.Distance(ZetaDia.Me.Position) >= range) { Logger.LogVerbose("Moving to " + destinationName); PlayerMover.NavigateTo(location, destinationName); await Coroutine.Yield(); } var distance = location.Distance(ZetaDia.Me.Position); if (distance <= range) Navigator.PlayerMover.MoveStop(); Logger.LogVerbose("MoveTo Finished. Distance={0}", distance); return true; }
public static Vector3 GetBestPosition(Obj_AI_Hero target, Vector3 firstPosition, Vector3 secondPosition) { if (firstPosition.IsWall() && !secondPosition.IsWall() && secondPosition.Distance(target.ServerPosition) < firstPosition.Distance(target.ServerPosition)) // if firstposition is a wall and second position isn't { return secondPosition; //return second position } if (secondPosition.IsWall() && !firstPosition.IsWall() && firstPosition.Distance(target.ServerPosition) < secondPosition.Distance(target.ServerPosition)) // if secondPosition is a wall and first position isn't { return firstPosition; // return first position } return firstPosition; }
public static GameObject GetNearestSoldierToMouse(Vector3 pos) { var soldier = Orbwalker.AzirSoldiers.ToList().OrderBy(x => pos.Distance(x.Position)); if (soldier.FirstOrDefault() != null) return soldier.FirstOrDefault(); return null; }
public static Obj_AI_Base GetTarget(Vector3 fromPosition) { var targetList = EntityManager.Heroes.Enemies.Where( h => h.IsValidTarget(SpellManager.E.Range) && !h.HasBuffOfType(BuffType.SpellShield) && !h.HasBuffOfType(BuffType.SpellImmunity) && h.Health > ObjectManager.Player.GetAutoAttackDamage(h, true) * 2).ToList(); if (!targetList.Any()) { return null; } foreach (var enemy in targetList) { var prediction = SpellManager.E.GetPrediction(enemy); var predictionsList = new List<Vector3> { enemy.ServerPosition, enemy.Position, prediction.CastPosition, prediction.UnitPosition }; var wallsFound = 0; foreach (var position in predictionsList) { var distance = fromPosition.Distance(position); for (var i = 0; i < Config.Settings.Condemn.PushDistance; i += (int)enemy.BoundingRadius) { var finalPosition = fromPosition.Extend(position, distance + i).To3D(); if (NavMesh.GetCollisionFlags(finalPosition).HasFlag(CollisionFlags.Wall) || NavMesh.GetCollisionFlags(finalPosition).HasFlag(CollisionFlags.Building)) { wallsFound++; break; } } } if (wallsFound >= Config.Settings.Condemn.Accuracy) { return enemy; } } return null; }
/// <summary> /// Moves to a position, finds actor by Id and interacts with it /// </summary> /// <param name="actorId">id of actor to interact with</param> /// <param name="range">how close to get</param> /// <param name="position">position from which to interact</param> /// <param name="interactLimit">maximum number of times to interact</param> public static async Task<bool> Execute(Vector3 position, int actorId, float range = -1f, int interactLimit = 5) { if (position == Vector3.Zero) return false; if (interactLimit < 1) interactLimit = 5; if (range < 0) range = 2f; if (position.Distance(ZetaDia.Me.Position) > range) { if (!await MoveTo.Execute(position, position.ToString())) { Logger.Log("MoveTo Failed for {0} Distance={1}", position, position.Distance(ZetaDia.Me.Position)); return false; } } var actor = ZetaDia.Actors.GetActorsOfType<DiaObject>(true).FirstOrDefault(a => a.ActorSNO == actorId); if (actor == null) { Logger.LogVerbose("Interaction Failed: Actor not found with Id={0}", actorId); return false; } var distance = position.Distance(ZetaDia.Me.Position); if (distance <= range || distance - actor.CollisionSphere.Radius <= range) { for (int i = 1; i <= interactLimit; i++) { Logger.Log("Interacting with {0} ({1}) Attempt={2}", actor.Name, actor.ActorSNO, i); if (actor.Interact() && i > 1) break; await Coroutine.Sleep(100); await Coroutine.Yield(); } } // Better to be redundant than failing to interact. Navigator.PlayerMover.MoveTowards(actor.Position); await Coroutine.Sleep(250); actor.Interact(); Navigator.PlayerMover.MoveStop(); await Coroutine.Sleep(1000); await Interact(actor); return true; }
public static Vector3 GetFirstWallPoint(Vector3 start, Vector3 end, int step = 1) { if (start.IsValid() && end.IsValid()) { var distance = start.Distance(end); for (var i = 0; i < distance; i = i + step) { var newPoint = start.Extend(end, i); if (NavMesh.GetCollisionFlags(newPoint) == CollisionFlags.Wall || newPoint.IsWall()) { return newPoint; } } } return Vector3.Zero; }
/// <summary> /// Gets the first wall point/node, w/e. /// </summary> /// <param name="playerPosition"></param> /// <param name="endPosition"></param> /// <param name="step"></param> /// <returns></returns> public Vector3 FirstWallPoint(Vector3 playerPosition, Vector3 endPosition, int step = 1) { if (!playerPosition.IsValid() || !endPosition.IsValid()) { return Vector3.Zero; } var distance = playerPosition.Distance(endPosition); for (var i = 0; i < distance; i = i + step) { var newPoint = playerPosition.Extend(endPosition, i); if (NavMesh.GetCollisionFlags(newPoint) == CollisionFlags.Wall || newPoint.IsWall()) { return newPoint; } } return Vector3.Zero; }
public override void OnExcute() { //状态保护 进入动画之后才执行 if (!animator.GetCurrentAnimatorStateInfo(0).IsName(aniName)) { return; } if (enemy.damage_) { //切换到 受伤状态 if (manager.ChangeState <EnemyStateDamage>()) { return; } } //球形视野检测Player 巡逻半径 viewPoint = transform.position; Collider[] players = Physics.OverlapSphere(viewPoint, enemy.PatrolRadius, 1 << LayerMask.NameToLayer("Player")); foreach (var player in players) { Vector3 vec = player.transform.position - viewPoint; float angle = Vector3.Angle(transform.forward, vec); if (angle < enemy.PatrolAngle / 2) { //切换到 追逐状态 if (manager.ChangeState <EnemyStateChase>()) { return; } } else { if (vec.magnitude < enemy.PatrolBackRadius) //背面 有效半径 { //切换到 追逐状态 if (manager.ChangeState <EnemyStateChase>()) { return; } } } } //没有寻路路径时 使用CC的move移动 防止卡死 if (!agent.hasPath && enemy.pathPoints.Length > 1) { Gravity(); //计算路径点方向 Vector3 direc = enemy.pathPoints[point].position - transform.position; direc.y = 0; //忽略y值 direc.Normalize(); //单位化 direc *= speed; //乘速度 //只改变水平向量值 HoriMove.x = direc.x; HoriMove.z = direc.z; //进行移动 cc.Move(HoriMove * Time.deltaTime); } //计算敌人到路径点的距离 进行移动 float distance = Vector3.Distance(transform.position, enemy.pathPoints[point].position); if (distance < 0.3f) { //只有一个寻路点 if (enemy.pathPoints.Length < 2) { //进入空闲状态 if (manager.ChangeState <EnemyStateIdle>()) { return; } } //空闲状态巡逻点 foreach (var pointIdle in enemy.pathPointsIdle) { if (enemy.pathPoints[point] == pointIdle) { //设定转向 与 巡逻点一致 transform.rotation = enemy.pathPoints[point].rotation; //判断当前路径点是第几个空闲点 设定空闲状态动画 if (enemy.pathPoints[point] == enemy.pathPointsIdle[0]) { animator.SetFloat("Blend", 0.0f); } else if (enemy.pathPoints[point] == enemy.pathPointsIdle[1]) { animator.SetFloat("Blend", 1.0f); } else if (enemy.pathPoints[point] == enemy.pathPointsIdle[2]) { animator.SetFloat("Blend", 2.0f); } else if (enemy.pathPoints[point] == enemy.pathPointsIdle[3]) { animator.SetFloat("Blend", 3.0f); } else { animator.SetFloat("Blend", 0.0f); } //进入空闲状态 if (manager.ChangeState <EnemyStateIdle>()) { return; } } } //不进入空闲状态 继续巡逻 if (point == enemy.pathPoints.Length - 1) //到达终点 { pointChange = -1; //改变路径点修改方向 } else if (point == 0) //到达起点 { pointChange = 1; //改变路径点修改方向 } point += pointChange; //改变路径点 agent.SetDestination(enemy.pathPoints[point].position); //设定寻路点 } }
private bool InAttackRange() { float distanceToPlayer = Vector3.Distance(player.transform.position, transform.position); return(distanceToPlayer < chaseDistance); }
public bool PlaceObject(SimObjPhysics sop, ReceptacleSpawnPoint rsp, bool PlaceStationary, int degreeIncrement, bool AlwaysPlaceUpright) { if (rsp.ParentSimObjPhys == sop) { #if UNITY_EDITOR Debug.Log("Can't place object inside itself!"); #endif return(false); } //remember the original rotation of the sim object if we need to reset it //Quaternion originalRot = sop.transform.rotation; Vector3 originalPos = sop.transform.position; Quaternion originalRot = sop.transform.rotation; //get the bounding box of the sim object we are trying to place BoxCollider oabb = sop.BoundingBox.GetComponent <BoxCollider>(); //zero out rotation and velocity/angular velocity, then match the target receptacle's rotation sop.transform.rotation = rsp.ReceptacleBox.transform.rotation; Rigidbody sopRB = sop.GetComponent <Rigidbody>(); sopRB.velocity = Vector3.zero; sopRB.angularVelocity = Vector3.zero; //set 360 degree increment to only check one angle, set smaller increments to check more angles when trying to place (warning THIS WILL GET SLOWER) int HowManyRotationsToCheck = 360 / degreeIncrement; Plane BoxBottom; float DistanceFromBoxBottomTosop; List <RotationAndDistanceValues> ToCheck = new List <RotationAndDistanceValues>(); //we'll check 8 rotations for now, replace the 45 later if we want to adjust the amount of checks //get rotations and distance values for 360/increment number of rotations around just the Y axis //we want to check all of these first so that the object is prioritized to be placed "upright" for (int i = 0; i < HowManyRotationsToCheck; i++) { oabb.enabled = true; if (i > 0) { sop.transform.Rotate(new Vector3(0, degreeIncrement, 0), Space.Self); //ToCheck[i].rotation = sop.transform.rotation; Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); } else { //no rotate change just yet, check the first position Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); //was using rsp.point BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); DistanceFromBoxBottomTosop = BoxBottom.GetDistanceToPoint(sop.transform.position); ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); } oabb.enabled = false; } //continue to check rotations about the X and Z axes if the object doesn't have to be placed upright if (!AlwaysPlaceUpright) { //ok now try if the X and Z local axis are rotated if it'll fit //these values can cause the object to be placed at crazy angles, so we'll check these last for (int i = 0; i < HowManyRotationsToCheck; i++) { oabb.enabled = true; if (i > 0) { sop.transform.Rotate(new Vector3(0, degreeIncrement, 0), Space.Self); Quaternion oldRotation = sop.transform.rotation; //now add more points by rotating the x axis at this current y rotation for (int j = 0; j < HowManyRotationsToCheck; j++) { sop.transform.Rotate(new Vector3(degreeIncrement, 0, 0), Space.Self); Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); } sop.transform.rotation = oldRotation; //now add EVEN more points by rotating the z axis at this current y rotation for (int j = 0; j < HowManyRotationsToCheck; j++) { sop.transform.Rotate(new Vector3(0, 0, degreeIncrement), Space.Self); Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); } sop.transform.rotation = oldRotation; } oabb.enabled = false; } } foreach (RotationAndDistanceValues quat in ToCheck) { //if spawn area is clear, spawn it and return true that we spawned it if (CheckSpawnArea(sop, rsp.Point + rsp.ParentSimObjPhys.transform.up * (quat.distance + yoffset), quat.rotation, false)) { //now to do a check to make sure the sim object is contained within the Receptacle box, and doesn't have //bits of it hanging out //Check the ReceptacleBox's Sim Object component to see what Type it is. Then check to //see if the type is the kind where the Object placed must be completely contained or just the bottom 4 corners contained int HowManyCornersToCheck = 0; if (ReceptacleRestrictions.OnReceptacles.Contains(rsp.ParentSimObjPhys.ObjType)) { //check that only the bottom 4 corners are in bounds HowManyCornersToCheck = 4; } if (ReceptacleRestrictions.InReceptacles.Contains(rsp.ParentSimObjPhys.ObjType)) { //check that all 8 corners are within bounds HowManyCornersToCheck = 8; } if (ReceptacleRestrictions.InReceptaclesThatOnlyCheckBottomFourCorners.Contains(rsp.ParentSimObjPhys.ObjType)) { //only check bottom 4 corners even though the action is PlaceIn HowManyCornersToCheck = 4; } int CornerCount = 0; //Plane rspPlane = new Plane(rsp.Point, rsp.ParentSimObjPhys.transform.up); //now check the corner count for either the 4 lowest corners, or all 8 corners depending on Corner Count //attmpt to sort corners so that first four corners are the corners closest to the spawn point we are checking against SpawnCorners.Sort(delegate(Vector3 p1, Vector3 p2) { //sort by making a plane where rsp.point is, find the four corners closest to that point //return rspPlane.GetDistanceToPoint(p1).CompareTo(rspPlane.GetDistanceToPoint(p2)); //^ this ended up not working because if something is placed at an angle this no longer makes sense... return(Vector3.Distance(p1, rsp.Point).CompareTo(Vector3.Distance(p2, rsp.Point))); // return Vector3.Distance(new Vector3(0, p1.y, 0), new Vector3(0, rsp.Point.y, 0)).CompareTo( // Vector3.Distance(new Vector3(0, p2.y, 0), new Vector3(0, rsp.Point.y, 0))); }); //ok so this is just checking if there are enough corners in the Receptacle Zone to consider it placed correctly. //originally this looped up to i < HowManyCornersToCheck, but if we just check all the corners, regardless of //sort order, it seems to bypass the issue above of how to sort the corners to find the "bottom" 4 corners, so uh // i guess this might just work without fancy sorting to determine the bottom 4 corners... especially since the "bottom corners" starts to lose meaning as objects are rotated for (int i = 0; i < 8; i++) { if (rsp.Script.CheckIfPointIsInsideReceptacleTriggerBox(SpawnCorners[i])) { CornerCount++; } } //if not enough corners are inside the receptacle, abort if (CornerCount < HowManyCornersToCheck) { sop.transform.rotation = originalRot; sop.transform.position = originalPos; return(false); } //one final check, make sure all corners of object are "above" the receptacle box in question, so we //dont spawn stuff half on a table and it falls over foreach (Vector3 v in SpawnCorners) { if (!rsp.Script.CheckIfPointIsAboveReceptacleTriggerBox(v)) { sop.transform.rotation = originalRot; sop.transform.position = originalPos; return(false); } } //translate position of the target sim object to the rsp.Point and offset in local y up sop.transform.position = rsp.Point + rsp.ReceptacleBox.transform.up * (quat.distance + yoffset);//rsp.Point + sop.transform.up * DistanceFromBottomOfBoxToTransform; sop.transform.rotation = quat.rotation; //set true if we want objects to be stationary when placed. (if placed on uneven surface, object remains stationary) //if false, once placed the object will resolve with physics (if placed on uneven surface object might slide or roll) if (PlaceStationary == true) { //make object being placed kinematic true sop.GetComponent <Rigidbody>().collisionDetectionMode = CollisionDetectionMode.Discrete; sop.GetComponent <Rigidbody>().isKinematic = true; //check if the parent sim object is one that moves like a drawer - and would require this to be parented //if(rsp.ParentSimObjPhys.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanOpen)) sop.transform.SetParent(rsp.ParentSimObjPhys.transform); //if this object is a receptacle and it has other objects inside it, drop them all together if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { PhysicsRemoteFPSAgentController agent = GameObject.Find("FPSController").GetComponent <PhysicsRemoteFPSAgentController>(); agent.DropContainedObjectsStationary(sop);//use stationary version so that colliders are turned back on, but kinematics remain true } //if the target receptacle is a pickupable receptacle, set it to kinematic true as will sence we are placing stationary if (rsp.ParentSimObjPhys.PrimaryProperty == SimObjPrimaryProperty.CanPickup) { rsp.ParentSimObjPhys.GetComponent <Rigidbody>().isKinematic = true; } } //place stationary false, let physics drop everything too else { //if not placing stationary, put all objects under Objects game object GameObject topObject = GameObject.Find("Objects"); //parent to the Objects transform sop.transform.SetParent(topObject.transform); Rigidbody rb = sop.GetComponent <Rigidbody>(); rb.isKinematic = false; rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic; //if this object is a receptacle and it has other objects inside it, drop them all together if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { PhysicsRemoteFPSAgentController agent = GameObject.Find("FPSController").GetComponent <PhysicsRemoteFPSAgentController>(); agent.DropContainedObjects(sop); } } sop.isInAgentHand = false;//set agent hand flag #if UNITY_EDITOR //Debug.Log(sop.name + " succesfully spawned in " +rsp.ParentSimObjPhys.name + " at coordinate " + rsp.Point); #endif return(true); } } //reset rotation if no valid spawns found //sop.transform.rotation = originalRot; //oh now we couldn't spawn it, all the spawn areas were not clear sop.transform.rotation = originalRot; sop.transform.position = originalPos; return(false); }
IEnumerator PresentOverTime() { if (TargetTranfsorm == null) { TargetTranfsorm = transform; } initialPosition = transform.position; initialRotation = transform.rotation; Vector3 cameraPosition = Camera.main.transform.position; Vector3 cameraForward = Camera.main.transform.forward; // Adjust the forward so we're only orienting in the Y axis if (OrientYAxisOnly) { cameraForward.y = 0f; cameraForward.Normalize(); } Quaternion targetRotation = Quaternion.LookRotation(cameraForward, Vector3.up); Vector3 targetPosition = cameraPosition + (cameraForward * PresentationDistance) + new Vector3(0.0f, -0.1f, 0.0f); inPosition = false; float normalizedProgress = 0f; float startTime = Time.time; while (!inPosition) { // Move the object directly in front of player normalizedProgress = (Time.time - startTime) / TravelTime; TargetTranfsorm.position = Vector3.Lerp(initialPosition, targetPosition, SmoothPosition.Evaluate(normalizedProgress)); if (OrientToCamera) { TargetTranfsorm.rotation = Quaternion.Lerp(TargetTranfsorm.rotation, targetRotation, Time.deltaTime * 10f); } inPosition = Vector3.Distance(TargetTranfsorm.position, targetPosition) < 0.05f; yield return(null); } while (!returning) { // Wait to be told to return yield return(null); } // Move back to our initial position inPosition = false; normalizedProgress = 0f; startTime = Time.time; while (normalizedProgress < 1f) { normalizedProgress = (Time.time - startTime) / TravelTime; TargetTranfsorm.position = Vector3.Lerp(targetPosition, initialPosition, SmoothPosition.Evaluate(normalizedProgress)); if (OrientToCamera) { TargetTranfsorm.rotation = Quaternion.Lerp(TargetTranfsorm.rotation, initialRotation, Time.deltaTime * 10f); } inPosition = Vector3.Distance(TargetTranfsorm.position, initialPosition) < 0.05f; yield return(null); } TargetTranfsorm.position = initialPosition; TargetTranfsorm.rotation = initialRotation; presenting = false; returning = false; yield break; }
public void Use(Client client, string commandName, string[] tokens) { Vector3 facing = new Vector3(client.Owner.Yaw, client.Owner.Pitch); Vector3 start = new Vector3(client.Owner.Position.X, client.Owner.Position.Y + client.Owner.EyeHeight, client.Owner.Position.Z); Vector3 end = facing * 100 + start; if (end.Y < 0) { end = end * (Math.Abs(end.Y) / start.Y); end.Y = 0; } if (tokens.Length == 0) { // Ray trace out along client facing direction RayTraceHitBlock hit = client.Owner.World.RayTraceBlocks(new AbsWorldCoords(start), new AbsWorldCoords(end)); if (hit == null) client.SendMessage(String.Format("No block targetted within {0} metres", start.Distance(end))); else { client.SendMessage(String.Format("{0} metres to {1}", start.Distance(hit.Hit), hit.ToString())); } } else if (tokens[0] == "destroy") // destroy the targetted block { RayTraceHitBlock hit = client.Owner.World.RayTraceBlocks(new AbsWorldCoords(start), new AbsWorldCoords(end)); if (hit != null) { client.Owner.World.SetBlockAndData(hit.TargetBlock, 0, 0); } } else if (tokens[0] == "pink") // make the targetted block pink wool { RayTraceHitBlock hit = client.Owner.World.RayTraceBlocks(new AbsWorldCoords(start), new AbsWorldCoords(end)); if (hit != null) { client.Owner.World.SetBlockAndData(hit.TargetBlock, 35, 6); } } else if (tokens[0] == "perf") // performance check { DateTime startTime = DateTime.Now; RayTraceHitBlock hit = null; for (int i = 0; i < 1000; i++) { hit = client.Owner.World.RayTraceBlocks(new AbsWorldCoords(start), new AbsWorldCoords(end)); } DateTime endTime = DateTime.Now; if (hit != null) { client.SendMessage(String.Format("Time to ray trace {0} metres (with hit):", start.Distance(hit.Hit))); } else { client.SendMessage(String.Format("Time to ray trace {0} metres:", start.Distance(end))); } client.SendMessage(((endTime - startTime).TotalMilliseconds / 1000.0).ToString() + " ms"); } }
//------- public Verlet(Plant.InitPoint[] init_data, Transform parent) { _parent = parent; // init from init data //-------------------------------------------------- _points = new Point[init_data.Length]; for (int i = 0; i < init_data.Length; ++i) { if (init_data[i].parent < 0) { init_data[i].is_fixed = true; } // transform init_data[i].pos *= Plant.SCALE; _points[i] = new Point(); _points[i].curr_mat.SetTRS(init_data[i].pos, Quaternion.identity, Vector3.one); _points[i].prev_mat = _points[i].curr_mat; _points[i].is_fixed = init_data[i].is_fixed; } BetterList <ConstraintPosition> new_const_pos = new BetterList <ConstraintPosition>(); for (int i = 0; i < init_data.Length; ++i) { if (init_data[i].parent >= 0) { ConstraintPosition cp = new ConstraintPosition(); cp.index_0 = i; cp.index_1 = init_data[i].parent; new_const_pos.Add(cp); } } _pos_constraints = new ConstraintPosition[0]; if (new_const_pos.size > 0) { _pos_constraints = new_const_pos.ToArray(); } BetterList <ConstraintSoft> new_const_soft = new BetterList <ConstraintSoft>(); for (int i = 0; i < init_data.Length; ++i) { if (init_data[i].soft_clamp) { ConstraintSoft cs = new ConstraintSoft(); cs.index_0 = i; cs.index_parent = init_data[i].parent; cs.min_dist = init_data[i].soft_min * Plant.SCALE; cs.max_dist = init_data[i].soft_max * Plant.SCALE; new_const_soft.Add(cs); } } _soft_constraints = new ConstraintSoft[0]; if (new_const_soft.size > 0) { _soft_constraints = new_const_soft.ToArray(); } //-------------------------------------------------- for (int i = 0; i < _pos_constraints.Length; ++i) { Vector3 p0 = _points[_pos_constraints[i].index_0].curr_mat.GetColumn(3); Vector3 p1 = _points[_pos_constraints[i].index_1].curr_mat.GetColumn(3); float d = Vector3.Distance(p0, p1); _pos_constraints[i].rest_length = d; } for (int i = 0; i < _soft_constraints.Length; ++i) { Vector3 p0 = _points[_soft_constraints[i].index_0].curr_mat.GetColumn(3); Vector3 p1 = _points[_soft_constraints[i].index_parent].curr_mat.GetColumn(3); Vector3 offset = p0 - p1; _soft_constraints[i].target_offset = offset; } }
public static bool JinxTrap(Vector3 castposition) { return ObjectManager.Get<Obj_AI_Base>() .Where(a => a.BaseSkinName == "JinxMine").Any(a => castposition.Distance(a.Position) <= 300); }
public static bool CaitTrap(Vector3 castposition) { return ObjectManager.Get<Obj_AI_Base>() .Where(a => a.BaseSkinName == "CaitlynTrap").Any(a => castposition.Distance(a.Position) <= 250); }
private static bool Shroomed(Vector3 castposition) { return ObjectManager.Get<Obj_AI_Minion>() .Where(a => a.Name == "Noxious Trap").Any(a => castposition.Distance(a.Position) <= 300); }
public static bool UnderEnemyTurret(Vector3 pos) { return ObjectManager.Get<Obj_AI_Turret>().Any(t => t.IsEnemy && !t.IsDead && pos.Distance(t) <= 900); }
public static bool InSpawnPoint(Vector3 pos) { return ObjectManager.Get<Obj_SpawnPoint>().Any(x => pos.Distance(x) < 800 && x.IsEnemy); }
/// <summary> /// Returns true if there is a Wall between X pos and Y pos. /// </summary> public static bool AnyWallInBetween(Vector3 startPos, Vector3 endPos) { for (var i = 0; i < startPos.Distance(endPos); i++) { if (NavMesh.GetCollisionFlags(startPos.Extend(endPos, i)) == CollisionFlags.Wall) { return true; } } return false; }
public float EuclidDist(Vertex a, Vertex b) { Vector3 posA = a.transform.position; Vector3 posB = b.transform.position; return Vector3.Distance(posA, posB); }
public static bool InRange(Vector3 pos1, Vector3 pos2, float range) { return Vector3.Distance(pos1,pos2) <= range*Grid.SCALE; //return (int)(Mathf.Abs(pos1.x-pos2.x)+0.5f) <= (int)(range*Grid.SCALE) && (int)(Mathf.Abs(pos1.z-pos2.z)+0.5f) <= (int)(range*Grid.SCALE); }
/*--------------------------------------------------------------------------------------*/ /* */ /* FixedUpdate: Runs every fixed interval. Interval can be changed in Unity. */ /* */ /*--------------------------------------------------------------------------------------*/ void FixedUpdate() { if (!NextLevel.loadingLevel.isLoading) { if (target == null) { if (!_SerahcingForPlayer) { _SerahcingForPlayer = true; StartCoroutine(SearchForPlayer()); } return; } if (path == null) { return; } if (_CurrentWayPoint >= path.vectorPath.Count) { if (pathIsEnded) { return; } pathIsEnded = true; return; } pathIsEnded = false; // Only move when active if (!isOff) { // Movement when player is in sight or when not in the light if ((tag != "Enemy_BLCK" || !inLight) && followPlayer) { // Finds direction to next way point Vector3 direction = (path.vectorPath [_CurrentWayPoint] - transform.position).normalized; direction *= speed * Time.fixedDeltaTime; // Moves the AI _Rigidbody2D.AddForce(direction, fMode); float distance = Vector3.Distance(transform.position, path.vectorPath [_CurrentWayPoint]); if (distance < nextWayPointDistance) { _CurrentWayPoint++; return; } } // Movement for YELLOW enemies (left and right) if (!followPlayer && tag == "Enemy_YLLW") { Vector2 lineCastPosition = transform.position.toVector2() - transform.right.toVector2() * _Width + Vector2.up * _Height; bool isGrounded = Physics2D.Linecast(lineCastPosition, lineCastPosition + Vector2.down, enemyMask); bool isBlocked = Physics2D.Linecast(lineCastPosition, lineCastPosition - transform.right.toVector2() * 0.05f, enemyMask); // If not grounded or blocked then turn around if (!isGrounded || isBlocked) { Vector3 currentRotation = transform.eulerAngles; currentRotation.y += 180; transform.eulerAngles = currentRotation; } // Always move "forward" when not following player Vector2 newVelcotiy = _Rigidbody2D.velocity; newVelcotiy.x = -transform.right.x * moveSpeed * Time.fixedDeltaTime; _Rigidbody2D.velocity = newVelcotiy; } // Movement for CYAN enemies (up and down) if (!followPlayer && tag == "Enemy_CYAN") { Vector2 lineCastPosition = transform.position.toVector2() - transform.right.toVector2() * 0.0f * _Width + Vector2.up * _Height; bool isBlockedBottom = Physics2D.Linecast(lineCastPosition, lineCastPosition + Vector2.down * 0.9f, enemyMask); bool isBlockedTop = Physics2D.Linecast(lineCastPosition, lineCastPosition + Vector2.up * 0.05f, enemyMask); // If not grounded or bloacked then turn around if (isBlockedBottom || isBlockedTop) { moveSpeed *= -1; } // Always move forward when not following player Vector2 newVelcotiy = _Rigidbody2D.velocity; newVelcotiy.y = -transform.up.y * moveSpeed * Time.fixedDeltaTime; _Rigidbody2D.velocity = newVelcotiy; } } } }
// Function that locks on the closest enemy available. If there are no enemies available, just center the camera. void LockEnemy() { if (m_LockableEnemies.Count != 0) { float closestDistance = float.MaxValue; float enemyDistance; foreach (Transform enemy in m_LockableEnemies) { enemyDistance = Vector3.Distance(m_PlayerTransform.position, enemy.position); if (closestDistance > enemyDistance) { if (!Physics.Raycast(enemy.position, m_PlayerTransform.position - enemy.position, Vector3.Distance(GlobalData.PlayerTransform.position, enemy.position), (1 << LayerMask.NameToLayer("Environment")))) { closestDistance = enemyDistance; GlobalData.LockedEnemyTransform = enemy; } } } if (GlobalData.LockedEnemyTransform != null) { GlobalData.IsEnemyLocked = true; } else { GlobalData.CenterCamera(); } } else { GlobalData.CenterCamera(); } }
// Update is called once per frame void Update() { if (_focus == null) { return; } float currentSpeed = _carController.m_curSpeed; currentSpeed = Mathf.Min(currentSpeed, _fastestSpeed); currentSpeed = Mathf.Max(currentSpeed, _slowestSpeed); float speedDiff = _fastestSpeed - _slowestSpeed; float speedProp = (currentSpeed - _slowestSpeed) / speedDiff; float height = Mathf.Lerp(_slowestHeight, _fastestHeight, speedProp); float distance = Mathf.Lerp(_slowestDistance, _fastestDistance, speedProp); if (_carController) { _averageSpeed += _carController.m_curSpeed; _averageSpeed /= 2.0f; } _dummyTransform.position = _focus.transform.position + (_focus.transform.up * height) - (_focus.transform.forward * distance); _dummyTransform.LookAt(_focus.transform.position, _focus.transform.up); RaycastHit hit; if (Physics.Raycast(_focus.transform.position + _focus.transform.up, -_dummyTransform.forward, out hit, Vector3.Distance(_dummyTransform.position, _focus.transform.position), ~9, QueryTriggerInteraction.Ignore)) { Debug.Log(hit.collider.gameObject); _dummyTransform.position = hit.point + (_focus.transform.forward * _wallAvoidDist); _dummyTransform.LookAt(_focus.transform, _focus.transform.up); } _dummyTransform.Rotate(new Vector3(-1, 0, 0), _forwardTilt); if (_useSmoothing) { float maxMove = _averageSpeed * _maxMoveDelta * Time.deltaTime; float maxTurn = _averageSpeed * _maxTurnDelta * Time.deltaTime; transform.position = Vector3.MoveTowards(transform.position, _dummyTransform.position, maxMove); transform.rotation = Quaternion.RotateTowards(transform.rotation, _dummyTransform.rotation, maxTurn); } else { transform.position = _dummyTransform.position; transform.rotation = _dummyTransform.rotation; } }
public bool IsOnLeaderSight() { return(Vector3.Distance(leader.transform.position, boid.transform.position) < leader_sight_radius || Vector3.Distance(ahead, boid.transform.position) < leader_sight_radius); }
private float GetTargetDistance() { return(Mathf.Abs(Vector3.Distance(transform.position, target.transform.position))); }
public bool InAARange(Vector3 point) { if (!getCheckBoxItem("AAcheck")) return true; if (Orbwalker.LastTarget != null && Orbwalker.LastTarget.Type == GameObjectType.AIHeroClient) { return point.Distance(Orbwalker.LastTarget.Position) < Player.AttackRange; } return point.CountEnemiesInRange(Player.AttackRange) > 0; }
// Update is called once per frame void Update() { if (startingSlow < 1f) { startingSlow += Time.deltaTime / 4f; } Vector3 averagePosition = Vector3.zero; int numDead = 0; float maxDistance = 0f; for (int i = 0; i < targets.Length; i++) { for (int j = 0; j < targets.Length; j++) { if (targets[i].GetComponent <PlayerLife>().Alive&& targets[j].GetComponent <PlayerLife>().Alive) { if (Vector3.Distance(targets[i].position, targets[j].position) > maxDistance) { maxDistance = Vector3.Distance(targets[i].position, targets[j].position); } } } } foreach (Transform t in targets) { if (t.gameObject.activeSelf && t.GetComponent <PlayerLife>().Alive) { averagePosition += t.position; } else { numDead++; } } if (targets.Length <= numDead) { return; } averagePosition /= (targets.Length - numDead); GetComponent <Camera>().fieldOfView = LevelManager.instance.BeatValue(0f) / 2f + initialFOV; transform.GetChild(0).GetComponent <Camera>().fieldOfView = LevelManager.instance.BeatValue(0f) / 2f + initialFOV; transform.localPosition = Vector3.MoveTowards(transform.localPosition, averagePosition + offset * (maxDistance / 35f), Time.deltaTime * Vector3.Distance(transform.localPosition, averagePosition + offset * (maxDistance / 35f)) / 2f); lookPosition = Vector3.MoveTowards(lookPosition, averagePosition, Time.deltaTime * Vector3.Distance(lookPosition, averagePosition)); transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(lookPosition - transform.position), Time.deltaTime * Quaternion.Angle(transform.rotation, Quaternion.LookRotation(lookPosition - transform.position)) * startingSlow); }
private bool GetIsInRange(Transform targetTransform) { return(Vector3.Distance(this.transform.position, targetTransform.position) < currentWeaponConfig.GetRange()); }
void Update() { if (Vector3.Distance(transform.position, player.position ) > maxDistance || Time.realtimeSinceStartup > timer + 1 ) { Destroy(gameObject); } }
private void Update() { if (!this.ManuallyAdjusted) { if (this.Clock.PresentTime / 60f > 8f && this.Clock.PresentTime / 60f < 15.5f) { if (!this.Closed) { this.PlayAudio(); this.Closed = true; if (this.EmergencyDoor.enabled) { this.EmergencyDoor.enabled = false; } } } else if (this.Closed) { this.PlayAudio(); this.Closed = false; if (!this.EmergencyDoor.enabled) { this.EmergencyDoor.enabled = true; } } } if (this.StudentManager.Students[97] != null) { if (this.StudentManager.Students[97].CurrentAction == StudentActionType.AtLocker && this.StudentManager.Students[97].Routine && this.StudentManager.Students[97].Alive) { if (Vector3.Distance(this.StudentManager.Students[97].transform.position, this.StudentManager.Podiums.List[0].position) < 0.1f) { if (this.ManuallyAdjusted) { this.ManuallyAdjusted = false; } this.Prompt.enabled = false; this.Prompt.Hide(); } else { this.Prompt.enabled = true; } } else { this.Prompt.enabled = true; } } else { this.Prompt.enabled = true; } if (this.Prompt.Circle[0].fillAmount == 0f) { this.Prompt.Circle[0].fillAmount = 1f; this.PlayAudio(); this.EmergencyDoor.enabled = !this.EmergencyDoor.enabled; this.ManuallyAdjusted = true; this.Closed = !this.Closed; if (this.StudentManager.Students[97] != null && this.StudentManager.Students[97].Investigating) { this.StudentManager.Students[97].StopInvestigating(); } } if (!this.Closed) { if (this.RightGate.localPosition.x != 7f) { this.RightGate.localPosition = new Vector3(Mathf.MoveTowards(this.RightGate.localPosition.x, 7f, Time.deltaTime), this.RightGate.localPosition.y, this.RightGate.localPosition.z); this.LeftGate.localPosition = new Vector3(Mathf.MoveTowards(this.LeftGate.localPosition.x, -7f, Time.deltaTime), this.LeftGate.localPosition.y, this.LeftGate.localPosition.z); if (!this.AudioPlayed && this.RightGate.localPosition.x == 7f) { this.RightGateAudio.clip = this.StopOpen; this.LeftGateAudio.clip = this.StopOpen; this.RightGateAudio.Play(); this.LeftGateAudio.Play(); this.RightGateLoop.Stop(); this.LeftGateLoop.Stop(); this.AudioPlayed = true; return; } } } else if (this.RightGate.localPosition.x != 2.325f) { if (this.RightGate.localPosition.x < 2.4f) { this.Crushing = true; } this.RightGate.localPosition = new Vector3(Mathf.MoveTowards(this.RightGate.localPosition.x, 2.325f, Time.deltaTime), this.RightGate.localPosition.y, this.RightGate.localPosition.z); this.LeftGate.localPosition = new Vector3(Mathf.MoveTowards(this.LeftGate.localPosition.x, -2.325f, Time.deltaTime), this.LeftGate.localPosition.y, this.LeftGate.localPosition.z); if (!this.AudioPlayed && this.RightGate.localPosition.x == 2.325f) { this.RightGateAudio.clip = this.StopOpen; this.LeftGateAudio.clip = this.StopOpen; this.RightGateAudio.Play(); this.LeftGateAudio.Play(); this.RightGateLoop.Stop(); this.LeftGateLoop.Stop(); this.AudioPlayed = true; this.Crushing = false; } } }
//In essence, sets isSelected on zombies under various mouse click related conditions. //Also moves the camera according to virtual axes Horizontal and Vertical. void Update() { //Set infect. if (Input.GetAxis("Infect") != 0f) { foreach (Transform zombie in ListOfZombies) { if (zombie.GetComponent <HumanoidHandler>().isSelected) { zombie.GetComponent <HumanoidHandler>().isInfecting = true; } } } if (Input.GetAxis("Lite Atk") != 0f) { foreach (Transform zombie in ListOfZombies) { if (zombie.GetComponent <HumanoidHandler>().isSelected) { zombie.GetComponent <HumanoidHandler>().CurrUsingAttack = HumanoidHandler.StateCharacterAtkUsing.WeakAttack; } } } else if (Input.GetAxis("Mid Atk") != 0f) { foreach (Transform zombie in ListOfZombies) { if (zombie.GetComponent <HumanoidHandler>().isSelected) { zombie.GetComponent <HumanoidHandler>().CurrUsingAttack = HumanoidHandler.StateCharacterAtkUsing.MediumAttack; } } } else if (Input.GetAxis("Hvy Atk") != 0f) { foreach (Transform zombie in ListOfZombies) { if (zombie.GetComponent <HumanoidHandler>().isSelected) { zombie.GetComponent <HumanoidHandler>().CurrUsingAttack = HumanoidHandler.StateCharacterAtkUsing.StrongAttack; } } } //Deselect. if (Input.GetMouseButton(1)) { foreach (Transform zombie in ListOfZombies) { zombie.GetComponent <HumanoidHandler>().isSelected = false; } } #region Zombie Type Select and Deselect if (Input.GetAxis("Strong") != 0f) { foreach (Transform zombie in ListOfZombies) { if (zombie.GetComponent <HumanoidHandler>().CurrZombType == HumanoidHandler.StateZombieType.Strong) { zombie.GetComponent <HumanoidHandler>().isSelected = true; } } } if (Input.GetAxis("Sneaky") != 0f) { foreach (Transform zombie in ListOfZombies) { if (zombie.GetComponent <HumanoidHandler>().CurrZombType == HumanoidHandler.StateZombieType.Sneeky) { zombie.GetComponent <HumanoidHandler>().isSelected = true; } } } if (Input.GetAxis("Fast") != 0f) { foreach (Transform zombie in ListOfZombies) { if (zombie.GetComponent <HumanoidHandler>().CurrZombType == HumanoidHandler.StateZombieType.Fast) { zombie.GetComponent <HumanoidHandler>().isSelected = true; } } } #endregion #region Camera Controls //Translation: Dolly forward and back for the Up and down keys. if (Input.GetAxis("Vertical") < 0) { if (Input.GetAxis("Look Up/Down") == 0f || Input.GetAxis("Mouse ScrollWheel") < 0f) { Camera.mainCamera.transform.Translate(Vector3.back, Space.World); } else { Camera.mainCamera.transform.Rotate(Vector3.left); } if (Camera.mainCamera.transform.rotation.x > 90) { Camera.mainCamera.transform.Rotate(Camera.mainCamera.transform.rotation.x - 90, 0, 0); } } else if (Input.GetAxis("Vertical") > 0) { if (Input.GetAxis("Look Up/Down") == 0f || Input.GetAxis("Mouse ScrollWheel") > 0f) { Camera.mainCamera.transform.Translate(Vector3.forward, Space.World); } else { Camera.mainCamera.transform.Rotate(Vector3.right); } if (Camera.mainCamera.transform.rotation.x < 0) { Camera.mainCamera.transform.Rotate(-Camera.mainCamera.transform.rotation.x, 0, 0); } } #endregion #region Mouse-Related Selection //Left or Right Shift or Ctrl make this true. if (Input.GetAxis("Multiselect") == 0f) { multiSelect = false; } else { multiSelect = true; } if (Input.GetMouseButtonDown(0)) //Click start. { //Debug.Log ("In click start."); anchorPosition = Input.mousePosition; } else if (Input.GetMouseButton(0)) //Dragging. { #region Dragging box selection. //Draw a rectangle from the anchorPosition to the current mousePosition. //But only if the distance between them is over the rectMinSize amount. if (Vector3.Distance(anchorPosition, Input.mousePosition) > rectMinSize) { //Probably will need to make four of these depending on where Input.mousePosition is relative to anchorpos. //i.e. Do a difference of the positions and check signs of x and y components. (0,0) is bottom left corner. //Debug.Log ("In Dragging, Also Rect Draw"); if (anchorPosition.x < Input.mousePosition.x) //If startclick is left of currMousePoint. { if (anchorPosition.y < Input.mousePosition.y) //If startclick is below currMousePoint. i.e. startclick BL, currMousePoint TR. { selectionBox = Rect.MinMaxRect(anchorPosition.x, Screen.height - Input.mousePosition.y, Input.mousePosition.x, Screen.height - anchorPosition.y); } else //If startclick is above currMousePoint, i.e. startclick TL, currMousePoint BR. { selectionBox = Rect.MinMaxRect(anchorPosition.x, Screen.height - anchorPosition.y, Input.mousePosition.x, Screen.height - Input.mousePosition.y); } } else //If startclick is right of currMousePoint. { if (anchorPosition.y < Input.mousePosition.y) //If startclick is below currMousePoint, i.e. startclick BR, currMousePoint TL. { selectionBox = Rect.MinMaxRect(Input.mousePosition.x, Screen.height - Input.mousePosition.y, anchorPosition.x, Screen.height - anchorPosition.y); } else //If startclick is above currMousePoint, i.e. startclick TR, currMousePoint BL. { selectionBox = Rect.MinMaxRect(Input.mousePosition.x, Screen.height - anchorPosition.y, anchorPosition.x, Screen.height - Input.mousePosition.y); } } drawBox = true; } #endregion } else if (Input.GetMouseButtonUp(0)) //Click release. { //Debug.Log (selectionBox); if (selectionBox == new Rect(-1, -1, -1, -1)) //Just because you can't set Rect to null. { //Debug.Log ("Normal Click"); #region Normal click logic goes here, i.e. no drag select. marker.renderer.enabled = false; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Cast the click as a ray into the scene... RaycastHit hit; if (Physics.Raycast(ray, out hit, Mathf.Infinity)) { //Debug.Log ("The tag of the transform that the click collided with is: " + hit.transform.tag); //Debug.Log ("The layer of the transform that the click collided with is: " + hit.transform.gameObject.layer); if (hit.transform.tag == "Human" || hit.transform.tag == "Construct") { foreach (Transform zombie in ListOfZombies) { if (zombie.GetComponent <HumanoidHandler>().isSelected) { zombie.GetComponent <AIPath>().target = hit.transform; } } } else if (hit.transform.tag == "Zombie") { //See Input Manager, it means Left/Right Ctrl/Shift is NOT down. Then we deselect all zombies. if (!multiSelect) { foreach (Transform zombie in ListOfZombies) { zombie.GetComponent <HumanoidHandler>().isSelected = false; } } //If selected, deselect; if not selected, select! //Debug.Log ("1: " + hit.transform.GetComponent<HumanoidHandler>().isSelected); hit.transform.GetComponent <HumanoidHandler>().isSelected = !hit.transform.GetComponent <HumanoidHandler>().isSelected; //Debug.Log ("2: " + hit.transform.GetComponent<HumanoidHandler>().isSelected); } //Indices of Ground&Obstacles layers are 8&9, so this means if we have clicked nothing else but the ground/obstacles. //Note that Constructs have already been taken of, so these are non-destrucible obstructions like trees and whatnot. else if (hit.transform.gameObject.layer == 8 || hit.transform.gameObject.layer == 9) { marker.renderer.enabled = true; marker.position = hit.point; foreach (Transform zombie in ListOfZombies) { HumanoidHandler hh = zombie.GetComponent <HumanoidHandler>(); if (hh.isSelected) { hh.emptyTarget.position = hit.point; hh.Target = hh.emptyTarget; //Keeps zombie from being distracted while walking to target. hh.isTargeting = true; } } } } else { foreach (Transform zombie in ListOfZombies) { zombie.GetComponent <HumanoidHandler>().isSelected = false; } } #endregion } else { //Translate the positions of every zombie in the scene into a screen point. //If the point is inside the rectangle, then set the current loop iteration's zombie's isSelected = true. foreach (Transform zombie in HumanoidHandler.ListOfZombies) { //Debug.Log (Camera.main.WorldToScreenPoint(zombie.position)); Vector3 derp = Camera.main.WorldToScreenPoint(zombie.position); derp.y = Screen.height - derp.y; if (selectionBox.Contains(derp)) { zombie.GetComponent <HumanoidHandler>().isSelected = true; } else { if (!multiSelect) { zombie.GetComponent <HumanoidHandler>().isSelected = false; } } } selectionBox = new Rect(-1, -1, -1, -1); //At the end. } } #endregion }
IEnumerator FlyToTarget(Vector3 target) { if (Random.value < .5) { GetComponent <AudioSource>().PlayOneShot(flyAway1, .1f); } else { GetComponent <AudioSource>().PlayOneShot(flyAway2, .1f); } flying = true; landing = false; onGround = false; GetComponent <Rigidbody>().isKinematic = false; GetComponent <Rigidbody>().velocity = Vector3.zero; GetComponent <Rigidbody>().drag = 0.5f; anim.applyRootMotion = false; anim.SetBool(flyingBoolHash, true); anim.SetBool(landingBoolHash, false); //Wait to apply velocity until the bird is entering the flying animation while (anim.GetCurrentAnimatorStateInfo(0).nameHash != flyAnimationHash) { yield return(0); } //birds fly up and away from their perch for 1 second before orienting to the next target GetComponent <Rigidbody>().AddForce((transform.forward * 50.0f * controller.birdScale) + (transform.up * 100.0f * controller.birdScale)); float t = 0.0f; while (t < 1.0f) { if (!paused) { t += Time.deltaTime; if (t > .2f && !solidCollider.enabled && controller.collideWithObjects) { solidCollider.enabled = true; } } yield return(0); } //start to rotate toward target Vector3 vectorDirectionToTarget = (target - transform.position).normalized; Quaternion finalRotation = Quaternion.identity; Quaternion startingRotation = transform.rotation; distanceToTarget = Vector3.Distance(transform.position, target); Vector3 forwardStraight; //the forward vector on the xz plane RaycastHit hit; Vector3 tempTarget = target; t = 0.0f; //if the target is directly above the bird the bird needs to fly out before going up //this should stop them from taking off like a rocket upwards if (vectorDirectionToTarget.y > .5f) { tempTarget = transform.position + (new Vector3(transform.forward.x, .5f, transform.forward.z) * distanceToTarget); while (vectorDirectionToTarget.y > .5f) { //Debug.DrawLine (tempTarget,tempTarget+Vector3.up,Color.red); vectorDirectionToTarget = (tempTarget - transform.position).normalized; finalRotation = Quaternion.LookRotation(vectorDirectionToTarget); transform.rotation = Quaternion.Slerp(startingRotation, finalRotation, t); anim.SetFloat(flyingDirectionHash, FindBankingAngle(transform.forward, vectorDirectionToTarget)); t += Time.deltaTime * 0.5f; GetComponent <Rigidbody>().AddForce(transform.forward * 70.0f * controller.birdScale * Time.deltaTime); //Debug.DrawRay (transform.position,transform.forward,Color.green); vectorDirectionToTarget = (target - transform.position).normalized; //reset the variable to reflect the actual target and not the temptarget if (Physics.Raycast(transform.position, -Vector3.up, out hit, 0.15f * controller.birdScale) && GetComponent <Rigidbody>().velocity.y < 0) { //if the bird is going to collide with the ground zero out vertical velocity if (!hit.collider.isTrigger) { GetComponent <Rigidbody>().velocity = new Vector3(GetComponent <Rigidbody>().velocity.x, 0.0f, GetComponent <Rigidbody>().velocity.z); } } if (Physics.Raycast(transform.position, Vector3.up, out hit, 0.15f * controller.birdScale) && GetComponent <Rigidbody>().velocity.y > 0) { //if the bird is going to collide with something overhead zero out vertical velocity if (!hit.collider.isTrigger) { GetComponent <Rigidbody>().velocity = new Vector3(GetComponent <Rigidbody>().velocity.x, 0.0f, GetComponent <Rigidbody>().velocity.z); } } //check for collisions with non trigger colliders and abort flight if necessary if (controller.collideWithObjects) { forwardStraight = transform.forward; forwardStraight.y = 0.0f; //Debug.DrawRay (transform.position+(transform.forward*.1f),forwardStraight*.75f,Color.green); if (Physics.Raycast(transform.position + (transform.forward * .15f * controller.birdScale), forwardStraight, out hit, .75f * controller.birdScale)) { if (!hit.collider.isTrigger) { AbortFlyToTarget(); } } } yield return(null); } } finalRotation = Quaternion.identity; startingRotation = transform.rotation; distanceToTarget = Vector3.Distance(transform.position, target); //rotate the bird toward the target over time while (transform.rotation != finalRotation || distanceToTarget >= 1.5f) { if (!paused) { distanceToTarget = Vector3.Distance(transform.position, target); vectorDirectionToTarget = (target - transform.position).normalized; if (vectorDirectionToTarget == Vector3.zero) { vectorDirectionToTarget = new Vector3(0.0001f, 0.00001f, 0.00001f); } finalRotation = Quaternion.LookRotation(vectorDirectionToTarget); transform.rotation = Quaternion.Slerp(startingRotation, finalRotation, t); anim.SetFloat(flyingDirectionHash, FindBankingAngle(transform.forward, vectorDirectionToTarget)); t += Time.deltaTime * 0.5f; GetComponent <Rigidbody>().AddForce(transform.forward * 70.0f * controller.birdScale * Time.deltaTime); if (Physics.Raycast(transform.position, -Vector3.up, out hit, 0.15f * controller.birdScale) && GetComponent <Rigidbody>().velocity.y < 0) { //if the bird is going to collide with the ground zero out vertical velocity if (!hit.collider.isTrigger) { GetComponent <Rigidbody>().velocity = new Vector3(GetComponent <Rigidbody>().velocity.x, 0.0f, GetComponent <Rigidbody>().velocity.z); } } if (Physics.Raycast(transform.position, Vector3.up, out hit, 0.15f * controller.birdScale) && GetComponent <Rigidbody>().velocity.y > 0) { //if the bird is going to collide with something overhead zero out vertical velocity if (!hit.collider.isTrigger) { GetComponent <Rigidbody>().velocity = new Vector3(GetComponent <Rigidbody>().velocity.x, 0.0f, GetComponent <Rigidbody>().velocity.z); } } //check for collisions with non trigger colliders and abort flight if necessary if (controller.collideWithObjects) { forwardStraight = transform.forward; forwardStraight.y = 0.0f; //Debug.DrawRay (transform.position+(transform.forward*.1f),forwardStraight*.75f,Color.green); if (Physics.Raycast(transform.position + (transform.forward * .15f * controller.birdScale), forwardStraight, out hit, .75f * controller.birdScale)) { if (!hit.collider.isTrigger) { AbortFlyToTarget(); } } } } yield return(0); } //keep the bird pointing at the target and move toward it float flyingForce = 50.0f * controller.birdScale; while (true) { if (!paused) { //do a raycast to see if the bird is going to hit the ground if (Physics.Raycast(transform.position, -Vector3.up, 0.15f * controller.birdScale) && GetComponent <Rigidbody>().velocity.y < 0) { GetComponent <Rigidbody>().velocity = new Vector3(GetComponent <Rigidbody>().velocity.x, 0.0f, GetComponent <Rigidbody>().velocity.z); } if (Physics.Raycast(transform.position, Vector3.up, out hit, 0.15f * controller.birdScale) && GetComponent <Rigidbody>().velocity.y > 0) { //if the bird is going to collide with something overhead zero out vertical velocity if (!hit.collider.isTrigger) { GetComponent <Rigidbody>().velocity = new Vector3(GetComponent <Rigidbody>().velocity.x, 0.0f, GetComponent <Rigidbody>().velocity.z); } } //check for collisions with non trigger colliders and abort flight if necessary if (controller.collideWithObjects) { forwardStraight = transform.forward; forwardStraight.y = 0.0f; //Debug.DrawRay (transform.position+(transform.forward*.1f),forwardStraight*.75f,Color.green); if (Physics.Raycast(transform.position + (transform.forward * .15f * controller.birdScale), forwardStraight, out hit, .75f * controller.birdScale)) { if (!hit.collider.isTrigger) { AbortFlyToTarget(); } } } vectorDirectionToTarget = (target - transform.position).normalized; finalRotation = Quaternion.LookRotation(vectorDirectionToTarget); anim.SetFloat(flyingDirectionHash, FindBankingAngle(transform.forward, vectorDirectionToTarget)); transform.rotation = finalRotation; GetComponent <Rigidbody>().AddForce(transform.forward * flyingForce * Time.deltaTime); distanceToTarget = Vector3.Distance(transform.position, target); if (distanceToTarget <= 1.5f * controller.birdScale) { solidCollider.enabled = false; if (distanceToTarget < 0.5f * controller.birdScale) { break; } else { GetComponent <Rigidbody>().drag = 2.0f; flyingForce = 50.0f * controller.birdScale; } } else if (distanceToTarget <= 5.0f * controller.birdScale) { GetComponent <Rigidbody>().drag = 1.0f; flyingForce = 50.0f * controller.birdScale; } } yield return(0); } anim.SetFloat(flyingDirectionHash, 0); //initiate the landing for the bird to finally reach the target Vector3 vel = Vector3.zero; flying = false; landing = true; solidCollider.enabled = false; anim.SetBool(landingBoolHash, true); anim.SetBool(flyingBoolHash, false); t = 0.0f; GetComponent <Rigidbody>().velocity = Vector3.zero; //tell any birds that are in the way to move their butts Collider[] hitColliders = Physics.OverlapSphere(target, 0.05f * controller.birdScale); for (int i = 0; i < hitColliders.Length; i++) { if (hitColliders[i].tag == "lb_bird" && hitColliders[i].transform != transform) { hitColliders[i].SendMessage("FlyAway"); } } //this while loop will reorient the rotation to vertical and translate the bird exactly to the target startingRotation = transform.rotation; transform.localEulerAngles = new Vector3(0.0f, transform.localEulerAngles.y, 0.0f); finalRotation = transform.rotation; transform.rotation = startingRotation; while (distanceToTarget > 0.05f * controller.birdScale) { if (!paused) { transform.rotation = Quaternion.Slerp(startingRotation, finalRotation, t * 4.0f); transform.position = Vector3.SmoothDamp(transform.position, target, ref vel, 0.5f); t += Time.deltaTime; distanceToTarget = Vector3.Distance(transform.position, target); if (t > 2.0f) { break; //failsafe to stop birds from getting stuck } } yield return(0); } GetComponent <Rigidbody>().drag = .5f; GetComponent <Rigidbody>().velocity = Vector3.zero; anim.SetBool(landingBoolHash, false); landing = false; transform.localEulerAngles = new Vector3(0.0f, transform.localEulerAngles.y, 0.0f); transform.position = target; anim.applyRootMotion = true; onGround = true; }
private void OnTriggerStay(Collider other) { if (((IN_GAME_MAIN_CAMERA.gametype != GAMETYPE.MULTIPLAYER) || base.transform.root.gameObject.GetPhotonView().isMine) && this.active_me) { if (other.gameObject.tag == "playerHitbox") { if (LevelInfo.getInfo(FengGameManagerMKII.level).pvp) { float b = 1f - (Vector3.Distance(other.gameObject.transform.position, base.transform.position) * 0.05f); b = Mathf.Min(1f, b); HitBox component = other.gameObject.GetComponent<HitBox>(); if ((((component != null) && (component.transform.root != null)) && (component.transform.root.GetComponent<HERO>().myTeam != this.myTeam)) && !component.transform.root.GetComponent<HERO>().isInvincible()) { if (IN_GAME_MAIN_CAMERA.gametype == GAMETYPE.SINGLE) { if (!component.transform.root.GetComponent<HERO>().isGrabbed) { Vector3 vector = component.transform.root.transform.position - base.transform.position; component.transform.root.GetComponent<HERO>().die((Vector3) (((vector.normalized * b) * 1000f) + (Vector3.up * 50f)), false); } } else if (((IN_GAME_MAIN_CAMERA.gametype == GAMETYPE.MULTIPLAYER) && !component.transform.root.GetComponent<HERO>().HasDied()) && !component.transform.root.GetComponent<HERO>().isGrabbed) { component.transform.root.GetComponent<HERO>().markDie(); object[] parameters = new object[5]; Vector3 vector2 = component.transform.root.position - base.transform.position; parameters[0] = (Vector3) (((vector2.normalized * b) * 1000f) + (Vector3.up * 50f)); parameters[1] = false; parameters[2] = this.viewID; parameters[3] = this.ownerName; parameters[4] = false; component.transform.root.GetComponent<HERO>().photonView.RPC("netDie", PhotonTargets.All, parameters); } } } } else if (other.gameObject.tag == "erenHitbox") { if ((this.dmg > 0) && !other.gameObject.transform.root.gameObject.GetComponent<TITAN_EREN>().isHit) { other.gameObject.transform.root.gameObject.GetComponent<TITAN_EREN>().hitByTitan(); } } else if (other.gameObject.tag == "titanneck") { HitBox item = other.gameObject.GetComponent<HitBox>(); if (((item != null) && this.checkIfBehind(item.transform.root.gameObject)) && !this.currentHits.Contains(item)) { item.hitPosition = (Vector3) ((base.transform.position + item.transform.position) * 0.5f); this.currentHits.Add(item); if (IN_GAME_MAIN_CAMERA.gametype == GAMETYPE.SINGLE) { if ((item.transform.root.GetComponent<TITAN>() != null) && !item.transform.root.GetComponent<TITAN>().hasDie) { Vector3 vector3 = this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().main_object.rigidbody.velocity - item.transform.root.rigidbody.velocity; int num2 = (int) ((vector3.magnitude * 10f) * this.scoreMulti); num2 = Mathf.Max(10, num2); GameObject.Find("MultiplayerManager").GetComponent<FengGameManagerMKII>().netShowDamage(num2); if (num2 > (item.transform.root.GetComponent<TITAN>().myLevel * 100f)) { item.transform.root.GetComponent<TITAN>().die(); if (PlayerPrefs.HasKey("EnableSS") && (PlayerPrefs.GetInt("EnableSS") == 1)) { GameObject.Find("MainCamera").GetComponent<IN_GAME_MAIN_CAMERA>().startSnapShot(item.transform.position, num2, item.transform.root.gameObject, 0.02f); } GameObject.Find("MultiplayerManager").GetComponent<FengGameManagerMKII>().playerKillInfoSingleUpdate(num2); } } } else if (!PhotonNetwork.isMasterClient) { if (item.transform.root.GetComponent<TITAN>() != null) { if (!item.transform.root.GetComponent<TITAN>().hasDie) { Vector3 vector4 = this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().main_object.rigidbody.velocity - item.transform.root.rigidbody.velocity; int num3 = (int) ((vector4.magnitude * 10f) * this.scoreMulti); num3 = Mathf.Max(10, num3); if (num3 > (item.transform.root.GetComponent<TITAN>().myLevel * 100f)) { if (PlayerPrefs.HasKey("EnableSS") && (PlayerPrefs.GetInt("EnableSS") == 1)) { GameObject.Find("MainCamera").GetComponent<IN_GAME_MAIN_CAMERA>().startSnapShot(item.transform.position, num3, item.transform.root.gameObject, 0.02f); item.transform.root.GetComponent<TITAN>().asClientLookTarget = false; } object[] objArray2 = new object[] { base.transform.root.gameObject.GetPhotonView().viewID, num3 }; item.transform.root.GetComponent<TITAN>().photonView.RPC("titanGetHit", item.transform.root.GetComponent<TITAN>().photonView.owner, objArray2); } } } else if (item.transform.root.GetComponent<FEMALE_TITAN>() != null) { Vector3 vector5 = this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().main_object.rigidbody.velocity - item.transform.root.rigidbody.velocity; int num4 = (int) ((vector5.magnitude * 10f) * this.scoreMulti); num4 = Mathf.Max(10, num4); if (!item.transform.root.GetComponent<FEMALE_TITAN>().hasDie) { object[] objArray3 = new object[] { base.transform.root.gameObject.GetPhotonView().viewID, num4 }; item.transform.root.GetComponent<FEMALE_TITAN>().photonView.RPC("titanGetHit", item.transform.root.GetComponent<FEMALE_TITAN>().photonView.owner, objArray3); } } else if ((item.transform.root.GetComponent<COLOSSAL_TITAN>() != null) && !item.transform.root.GetComponent<COLOSSAL_TITAN>().hasDie) { Vector3 vector6 = this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().main_object.rigidbody.velocity - item.transform.root.rigidbody.velocity; int num5 = (int) ((vector6.magnitude * 10f) * this.scoreMulti); num5 = Mathf.Max(10, num5); object[] objArray4 = new object[] { base.transform.root.gameObject.GetPhotonView().viewID, num5 }; item.transform.root.GetComponent<COLOSSAL_TITAN>().photonView.RPC("titanGetHit", item.transform.root.GetComponent<COLOSSAL_TITAN>().photonView.owner, objArray4); } } else if (item.transform.root.GetComponent<TITAN>() != null) { if (!item.transform.root.GetComponent<TITAN>().hasDie) { Vector3 vector7 = this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().main_object.rigidbody.velocity - item.transform.root.rigidbody.velocity; int num6 = (int) ((vector7.magnitude * 10f) * this.scoreMulti); num6 = Mathf.Max(10, num6); if (num6 > (item.transform.root.GetComponent<TITAN>().myLevel * 100f)) { if (PlayerPrefs.HasKey("EnableSS") && (PlayerPrefs.GetInt("EnableSS") == 1)) { GameObject.Find("MainCamera").GetComponent<IN_GAME_MAIN_CAMERA>().startSnapShot(item.transform.position, num6, item.transform.root.gameObject, 0.02f); } item.transform.root.GetComponent<TITAN>().titanGetHit(base.transform.root.gameObject.GetPhotonView().viewID, num6); } } } else if (item.transform.root.GetComponent<FEMALE_TITAN>() != null) { if (!item.transform.root.GetComponent<FEMALE_TITAN>().hasDie) { Vector3 vector8 = this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().main_object.rigidbody.velocity - item.transform.root.rigidbody.velocity; int num7 = (int) ((vector8.magnitude * 10f) * this.scoreMulti); num7 = Mathf.Max(10, num7); if (PlayerPrefs.HasKey("EnableSS") && (PlayerPrefs.GetInt("EnableSS") == 1)) { GameObject.Find("MainCamera").GetComponent<IN_GAME_MAIN_CAMERA>().startSnapShot(item.transform.position, num7, null, 0.02f); } item.transform.root.GetComponent<FEMALE_TITAN>().titanGetHit(base.transform.root.gameObject.GetPhotonView().viewID, num7); } } else if ((item.transform.root.GetComponent<COLOSSAL_TITAN>() != null) && !item.transform.root.GetComponent<COLOSSAL_TITAN>().hasDie) { Vector3 vector9 = this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().main_object.rigidbody.velocity - item.transform.root.rigidbody.velocity; int num8 = (int) ((vector9.magnitude * 10f) * this.scoreMulti); num8 = Mathf.Max(10, num8); if (PlayerPrefs.HasKey("EnableSS") && (PlayerPrefs.GetInt("EnableSS") == 1)) { GameObject.Find("MainCamera").GetComponent<IN_GAME_MAIN_CAMERA>().startSnapShot(item.transform.position, num8, null, 0.02f); } item.transform.root.GetComponent<COLOSSAL_TITAN>().titanGetHit(base.transform.root.gameObject.GetPhotonView().viewID, num8); } this.showCriticalHitFX(other.gameObject.transform.position); } } else if (other.gameObject.tag == "titaneye") { if (!this.currentHits.Contains(other.gameObject)) { this.currentHits.Add(other.gameObject); GameObject gameObject = other.gameObject.transform.root.gameObject; if (gameObject.GetComponent<FEMALE_TITAN>() != null) { if (IN_GAME_MAIN_CAMERA.gametype == GAMETYPE.SINGLE) { if (!gameObject.GetComponent<FEMALE_TITAN>().hasDie) { gameObject.GetComponent<FEMALE_TITAN>().hitEye(); } } else if (!PhotonNetwork.isMasterClient) { if (!gameObject.GetComponent<FEMALE_TITAN>().hasDie) { object[] objArray5 = new object[] { base.transform.root.gameObject.GetPhotonView().viewID }; gameObject.GetComponent<FEMALE_TITAN>().photonView.RPC("hitEyeRPC", PhotonTargets.MasterClient, objArray5); } } else if (!gameObject.GetComponent<FEMALE_TITAN>().hasDie) { gameObject.GetComponent<FEMALE_TITAN>().hitEyeRPC(base.transform.root.gameObject.GetPhotonView().viewID); } } else if (gameObject.GetComponent<TITAN>().abnormalType != AbnormalType.TYPE_CRAWLER) { if (IN_GAME_MAIN_CAMERA.gametype == GAMETYPE.SINGLE) { if (!gameObject.GetComponent<TITAN>().hasDie) { gameObject.GetComponent<TITAN>().hitEye(); } } else if (!PhotonNetwork.isMasterClient) { if (!gameObject.GetComponent<TITAN>().hasDie) { object[] objArray6 = new object[] { base.transform.root.gameObject.GetPhotonView().viewID }; gameObject.GetComponent<TITAN>().photonView.RPC("hitEyeRPC", PhotonTargets.MasterClient, objArray6); } } else if (!gameObject.GetComponent<TITAN>().hasDie) { gameObject.GetComponent<TITAN>().hitEyeRPC(base.transform.root.gameObject.GetPhotonView().viewID); } this.showCriticalHitFX(other.gameObject.transform.position); } } } else if ((other.gameObject.tag == "titanankle") && !this.currentHits.Contains(other.gameObject)) { this.currentHits.Add(other.gameObject); GameObject obj3 = other.gameObject.transform.root.gameObject; Vector3 vector10 = this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().main_object.rigidbody.velocity - obj3.rigidbody.velocity; int num9 = (int) ((vector10.magnitude * 10f) * this.scoreMulti); num9 = Mathf.Max(10, num9); if ((obj3.GetComponent<TITAN>() != null) && (obj3.GetComponent<TITAN>().abnormalType != AbnormalType.TYPE_CRAWLER)) { if (IN_GAME_MAIN_CAMERA.gametype == GAMETYPE.SINGLE) { if (!obj3.GetComponent<TITAN>().hasDie) { obj3.GetComponent<TITAN>().hitAnkle(); } } else { if (!PhotonNetwork.isMasterClient) { if (!obj3.GetComponent<TITAN>().hasDie) { object[] objArray7 = new object[] { base.transform.root.gameObject.GetPhotonView().viewID }; obj3.GetComponent<TITAN>().photonView.RPC("hitAnkleRPC", PhotonTargets.MasterClient, objArray7); } } else if (!obj3.GetComponent<TITAN>().hasDie) { obj3.GetComponent<TITAN>().hitAnkle(); } this.showCriticalHitFX(other.gameObject.transform.position); } } else if (obj3.GetComponent<FEMALE_TITAN>() != null) { if (IN_GAME_MAIN_CAMERA.gametype == GAMETYPE.SINGLE) { if (other.gameObject.name == "ankleR") { if ((obj3.GetComponent<FEMALE_TITAN>() != null) && !obj3.GetComponent<FEMALE_TITAN>().hasDie) { obj3.GetComponent<FEMALE_TITAN>().hitAnkleR(num9); } } else if ((obj3.GetComponent<FEMALE_TITAN>() != null) && !obj3.GetComponent<FEMALE_TITAN>().hasDie) { obj3.GetComponent<FEMALE_TITAN>().hitAnkleL(num9); } } else if (other.gameObject.name == "ankleR") { if (!PhotonNetwork.isMasterClient) { if (!obj3.GetComponent<FEMALE_TITAN>().hasDie) { object[] objArray8 = new object[] { base.transform.root.gameObject.GetPhotonView().viewID, num9 }; obj3.GetComponent<FEMALE_TITAN>().photonView.RPC("hitAnkleRRPC", PhotonTargets.MasterClient, objArray8); } } else if (!obj3.GetComponent<FEMALE_TITAN>().hasDie) { obj3.GetComponent<FEMALE_TITAN>().hitAnkleRRPC(base.transform.root.gameObject.GetPhotonView().viewID, num9); } } else if (!PhotonNetwork.isMasterClient) { if (!obj3.GetComponent<FEMALE_TITAN>().hasDie) { object[] objArray9 = new object[] { base.transform.root.gameObject.GetPhotonView().viewID, num9 }; obj3.GetComponent<FEMALE_TITAN>().photonView.RPC("hitAnkleLRPC", PhotonTargets.MasterClient, objArray9); } } else if (!obj3.GetComponent<FEMALE_TITAN>().hasDie) { obj3.GetComponent<FEMALE_TITAN>().hitAnkleLRPC(base.transform.root.gameObject.GetPhotonView().viewID, num9); } this.showCriticalHitFX(other.gameObject.transform.position); } } } }
// Update is called once per frame void Update() { movement = Vector3.zero; // ОПРЕДЕЛЕНИЕ ТОЧКИ ДВИЖЕНИЯ if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject()) { Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition); RaycastHit mouseHit; if (Physics.Raycast(ray, out mouseHit)) { GameObject hitObject = mouseHit.transform.gameObject; if (hitObject.layer == LayerMask.NameToLayer("Ground")) { _targetPos = mouseHit.point; _curSpeed = moveSpeed; } } } // ПОВОРОТ if (_targetPos != Vector3.one) { Vector3 adjustedPos = new Vector3(_targetPos.x, transform.position.y, _targetPos.z); Quaternion targetRot = Quaternion.LookRotation(adjustedPos - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, targetRot, rotSpeed * Time.deltaTime); // ДВИЖЕНИЕ movement = _curSpeed * Vector3.forward; movement = transform.TransformDirection(movement); if (Vector3.Distance(_targetPos, transform.position) < targetBuffer) { _curSpeed -= deceleration * Time.deltaTime; if (_curSpeed <= 0) _targetPos = Vector3.one; } } _animator.SetFloat("Speed", movement.sqrMagnitude); // РАСПОЗНОВАНИЕ ПОВЕРХНОСТИ bool hitGround = false; RaycastHit hit; if (_vertSpeed < 0 && Physics.Raycast(transform.position, Vector3.down, out hit)) { float check = // РАССТОЯНИЕ ЧУТЬ ВЫХОДИТ ЗА ГРАНИЦЫ КАПСУЛЫ (_charController.height + _charController.radius) / 1.9f; hitGround = hit.distance <= check; } // СОСТОЯНИЯ: // 1) ПЕРСОНАЖ ПРЫГАЕТ: _vertSpeed > 0 // 2) ПЕРСОНАЖ СТОИТ НА КРАЮ: // hitGround == false && _charController.isGrounded == true // 3) ПЕРСОНАЖ СТОИТ НА ПОВЕРХНОСТИ: hitGround == true; // ДВИЖЕНИЕ ПО ВЕРТИКАЛИ // СТОИТ НА ПОВЕРХНОСТИ ИЛИ ПРЫГАЕТ if (hitGround) { //if (Input.GetButtonDown("Jump")) // _vertSpeed = jumpSpeed; //else //{ _vertSpeed = minFall; _animator.SetBool("Jumping", false); //} } else { _vertSpeed += gravity * 5 * Time.deltaTime; if (_vertSpeed < terminalVelocity) _vertSpeed = terminalVelocity; if (_contact != null) _animator.SetBool("Jumping", true); // СТОИТ НА КРАЮ if (_charController.isGrounded) { if (Vector3.Dot(movement, _contact.normal) < 0) { movement = _contact.normal * moveSpeed; } else { movement += _contact.normal * moveSpeed; } } } movement.y = _vertSpeed; movement *= Time.deltaTime; //Debug.Log(movement.x + ", " + movement.z); _charController.Move(movement); }
private bool AtWaypoint() { float distanceToWaypoint = Vector3.Distance(GetCurrentWaypoint(), transform.position); return(distanceToWaypoint < waypointTolerance); }
private void FixedUpdate() { //Lock the Roombas to the ground, don't let them rotate so they'll fly away or go through the floor. if (transform.localPosition.y != 1) { transform.localPosition = new Vector3(transform.localPosition.x, 1, transform.localPosition.z); } if (transform.localRotation.x + transform.localRotation.z != 0) { transform.localRotation = new Quaternion(0, transform.localRotation.y, 0, transform.localRotation.w); } switch (state) { case State.Rotating: transform.Rotate(Vector3.up * rotationSpeed); break; case State.Moving: if (!keepMoving) { Collider[] nearbyDirt = Physics.OverlapSphere(transform.position, dirtCheckRadius, dirtLayer, QueryTriggerInteraction.Collide); if (nearbyDirt.Length > 0) { GameObject target = nearbyDirt[0].gameObject; float distance = Vector3.Distance(transform.position, target.transform.position); for (int i = 1; i < nearbyDirt.Length; i++) { float tempDistance = Vector3.Distance(transform.position, nearbyDirt[i].transform.position); if (tempDistance < distance) { distance = tempDistance; target = nearbyDirt[i].gameObject; } } if (currentTarget != target) { currentTarget = target; state = State.Following; } } else if (nearbyDirt.Length == 1) { if (currentTarget != nearbyDirt[0].gameObject) { currentTarget = nearbyDirt[0].gameObject; state = State.Following; } } else { currentTarget = null; } } transform.Translate(Vector3.forward * speed * Time.deltaTime); break; case State.Following: //Check if front of roomba is within '5' degrees of facing the object dead on. If it is, move forward. // if it isn't, Rotate toward target. if (currentTarget == null || Vector3.Distance(transform.position, currentTarget.transform.position) < followingThreshhold || currentTarget.activeInHierarchy == false) { currentTarget = null; state = State.Moving; } else { Vector3 heading = (new Vector3(currentTarget.transform.position.x, currentTarget.transform.position.y, transform.position.z) - transform.position).normalized; //if(transform.rotation != Quaternion.Euler(heading)) if (Vector3.Distance(transform.forward, heading) > .05f) { transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(transform.forward, (heading), rotationSpeed * Time.deltaTime, .1f), transform.up); } else { transform.Translate(Vector3.forward * speed * Time.deltaTime); } } break; case State.Dead: break; default: break; } }
/// <summary> /// Follows the target, lerping the position or not based on what's been defined in the inspector /// </summary> protected virtual void FollowTargetPosition() { if (Target == null) { return; } if (!FollowPosition) { return; } _newTargetPosition = Target.position + Offset; if (!FollowPositionX) { _newTargetPosition.x = _initialPosition.x; } if (!FollowPositionY) { _newTargetPosition.y = _initialPosition.y; } if (!FollowPositionZ) { _newTargetPosition.z = _initialPosition.z; } float trueDistance = 0f; _direction = (_newTargetPosition - this.transform.position).normalized; trueDistance = Vector3.Distance(this.transform.position, _newTargetPosition); float interpolatedDistance = trueDistance; if (InterpolatePosition) { switch (FollowPositionMode) { case FollowModes.MMLerp: interpolatedDistance = MMMaths.Lerp(0f, trueDistance, FollowPositionSpeed, Time.deltaTime); interpolatedDistance = ApplyMinMaxDistancing(trueDistance, interpolatedDistance); this.transform.Translate(_direction * interpolatedDistance, Space.World); break; case FollowModes.RegularLerp: interpolatedDistance = Mathf.Lerp(0f, trueDistance, Time.deltaTime * FollowPositionSpeed); interpolatedDistance = ApplyMinMaxDistancing(trueDistance, interpolatedDistance); this.transform.Translate(_direction * interpolatedDistance, Space.World); break; case FollowModes.MMSpring: _newPosition = this.transform.position; MMMaths.Spring(ref _newPosition, _newTargetPosition, ref _velocity, PositionSpringDamping, PositionSpringFrequency, FollowPositionSpeed, Time.deltaTime); if (_localSpace) { this.transform.localPosition = _newPosition; } else { this.transform.position = _newPosition; } break; } } else { interpolatedDistance = ApplyMinMaxDistancing(trueDistance, interpolatedDistance); this.transform.Translate(_direction * interpolatedDistance, Space.World); } if (AnchorToInitialPosition) { if (Vector3.Distance(this.transform.position, _initialPosition) > MaxDistanceToAnchor) { if (_localSpace) { this.transform.localPosition = _initialPosition + Vector3.ClampMagnitude(this.transform.localPosition - _initialPosition, MaxDistanceToAnchor); } else { this.transform.position = _initialPosition + Vector3.ClampMagnitude(this.transform.position - _initialPosition, MaxDistanceToAnchor); } } } }
public void UpdatePath(bool keepOldIfNotFound) { if (m_IsInitialized) { NavMeshPath path = new NavMeshPath(); Vector3 startPosition = ARSpaceToUnity(m_ARSpace.transform, m_ARSpace.initialOffset, m_CameraTransform.position); Vector3 targetPosition = ARSpaceToUnity(m_ARSpace.transform, m_ARSpace.initialOffset, m_TargetTransform.position); Vector3 currentPositionInUnitySpace = ARSpaceToUnity(m_ARSpace.transform, m_ARSpace.initialOffset, m_CameraTransform.position); Vector3 delta = targetPosition - currentPositionInUnitySpace; float distanceToTarget = new Vector3(delta.x, 0f, delta.z).magnitude; if (!m_NavigationArrived && distanceToTarget < navigationManager.arrivedDistanceThreshold) { m_NavigationArrived = true; navigationManager.DisplayArrivedNotification(); return; } if (NavMesh.CalculatePath(startPosition, targetPosition, NavMesh.AllAreas, path)) { if (!m_NavigationStarted) { navigationManager.DisplayNavigation(); m_NavigationStarted = true; m_NavigationArrived = false; } m_IsNavigating = true; List <Vector3> corners = new List <Vector3>(path.corners); List <Vector3> collapsedCorners = new List <Vector3>(); for (int i = 0; i < corners.Count; i++) { corners[i] = corners[i] + new Vector3(0f, m_yOffset, 0f); corners[i] = UnityToARSpace(m_ARSpace.transform, m_ARSpace.initialOffset, corners[i]); } for (int i = 0; i < corners.Count - 1; i++) { Vector3 cp = corners[i]; Vector3 np = corners[i + 1]; float threshold = 0.75f; if (Vector3.Distance(cp, np) > threshold) { collapsedCorners.Add(cp); //Debug.DrawLine(cp, cp + Vector3.up, Color.red); } } collapsedCorners.Add(corners[corners.Count - 1]); m_PathMeshGenerator.GeneratePath(collapsedCorners, m_ARSpace.transform.up); // update compass m_Arrow direction if (m_Arrow != null && !m_Arrow.activeInHierarchy) { m_Arrow.SetActive(true); } if (corners.Count > 1 && m_ArrowDirection != null) { Vector3 nextPoint = new Vector3(corners[1].x, Camera.main.transform.position.y, corners[1].z); m_ArrowDirection.LookAt(nextPoint, Vector3.up); } } else { if (!keepOldIfNotFound) { navigationManager.DisplayPathNotFoundNotification(); } } } }
private static int GetEnemys(AIHeroClient target) { int Enemys = 0; foreach (AIHeroClient enemys in ObjectManager.Get <AIHeroClient>()) { var pred = R.GetPrediction(enemys, true); if (pred.Hitchance >= HitChance.High && !enemys.IsMe && enemys.IsEnemy && Vector3.Distance(Player.Position, pred.UnitPosition) <= R.Range) { Enemys = Enemys + 1; } } return(Enemys); }
public float DistanceFromTarget(Vector3 target, float[] angles) { Vector3 point = ForwardKinematics(angles); return(Vector3.Distance(point, target)); }
public void Attack(int reduceGold, int reduceDiamond) { if (timeVal > 20) { transform.LookAt(playerTransform); transform.eulerAngles += new Vector3(90, -90, 0); isAttack = true; timeVal = 0; } else { timeVal += Time.deltaTime; } if (isAttack) { gameObjectAni.SetBool("isAttack", true); transform.position = Vector3.Lerp(transform.position, playerTransform.position, 1 / Vector3.Distance(transform.position, playerTransform.position) * Time.deltaTime * moveSpeed); if (Vector3.Distance(transform.position, playerTransform.position) <= 4) { if (reduceGold != 0) { Gun.Instance.GoldChange(reduceGold); } if (reduceDiamond != 0) { Gun.Instance.DiamandsChange(reduceDiamond); } gameObjectAni.SetBool("isAttack", false); isAttack = false; Gun.Instance.BossAttack(); rotateTime = 0; Invoke("ReturnAngle", 4); } } }
void moveUnit() { // The path that the unit will go through when trying to move if (path.Count > 0) { BaseTile checkBaseTile = path.Peek(); Vector3 target = checkBaseTile.transform.position; // Calculate the Units position on top of the tile target.y = transform.position.y; if (Vector3.Distance(transform.position, target) >= moveSpeed * Time.deltaTime) { // calcualtes both the direction and the speed calculateHeading(target); // moves the unit Vector3 direction = checkBaseTile.transform.position; direction.y = transform.position.y; transform.LookAt(direction); transform.Rotate(transform.up, 0f); // The speed of unit is affected by time transform.position += velocity * Time.deltaTime; } else { // call fog of war if (unitType == UnitTypes.King || unitType == UnitTypes.Hawk) { gameManager.gameMap.revealTiles(transform.position); } // direction of Unit // Player reaches center of tile and looks for next tile in list transform.position = target; path.Pop(); } } else { // if kraken lands on tile with another object delete object if (unitType == UnitTypes.Monster) { // if Monster is on tile of unit destroy the unit if (targetTile.unitOnTile == UnitTypes.Elephant || targetTile.unitOnTile == UnitTypes.Beaver || targetTile.unitOnTile == UnitTypes.Hawk) { RaycastHit hit; if (Physics.Raycast(targetTile.transform.position, Vector3.up, out hit, 1)) { if (hit.collider.GetComponent <BaseUnit>() != null) { Debug.Log(targetTile.unitOnTile); Destroy(hit.collider.gameObject); } } } // Player 2 Wins if Octopus is on the kings tile else if (targetTile.unitOnTile == BaseUnit.UnitTypes.King) { gameManager.gameMap.gameManager.player2Win(); } } // changes tile state (what unit is on the tile) currentTile.newUnitOnTile(UnitTypes.None); targetTile.newUnitOnTile(unitType); // Makes unit visible if (targetTile.gameObject.layer == 8) { foreach (Transform part in GetComponentsInChildren <Transform>()) { part.gameObject.layer = 8; } } // Makes unit invisible if (targetTile.gameObject.layer == 9) { foreach (Transform part in GetComponentsInChildren <Transform>()) { part.gameObject.layer = 9; } } // changes state moving = false; targetTile = null; currentTile = null; } }
// Update is called once per frame void Update() { debugdoor1 = door1Open["Take 001"].time; debugdoor2 = door2Open["Take 001"].time; door1Look = cameraCollider.GetComponent <collision>().door1look; door2Look = cameraCollider.GetComponent <collision>().door2look; float airlockDist = Vector3.Distance(Player.transform.position, airlockCollider.transform.position); // Determines if character is in air lock if (airlockDist < dist) { airlockActivated = true; } else { airlockActivated = false; } // Resets the door material if (door1Look == false) { doorBackground1.GetComponent <MeshRenderer>().material = doorPassive; } if (door2Look == false) { doorBackground2.GetComponent <MeshRenderer>().material = doorPassive; } // Resets the press A text if (door1Look == false) { pressA.SetActive(false); } if (door2Look == false) { pressA.SetActive(false); } // Activates airlock animation if within range, visible, and press A if (airlockActivated == true && playerInside == false) { if (door2Look == true) { pressA.SetActive(true);//Display Press A in canvas doorBackground2.GetComponent <MeshRenderer>().material = doorActive; //if (OVRInput.GetUp(OVRInput.Button.One)) if (Input.GetMouseButtonUp(0)) { triggerDoor2 = true; pressA.SetActive(false); } } } if (triggerDoor2 == true) { airlockText.SetActive(true); door1Open["Take 001"].speed = -1.0f; // close door 1 door1Open.Play(); if (door1Open["Take 001"].time <= 0.0f) { airlockText.SetActive(false); door2Open["Take 001"].speed = 1.0f;// Open door 2 door2Open.Play(); } if (door2Open["Take 001"].time >= 1.0f) { triggerDoor2 = false; playerInside = true; sandStorm.SetActive(false); exterior.SetActive(false); interior.SetActive(true); } } if (airlockDist < dist && playerInside == true) { if (door1Look == true) { pressA.SetActive(true); //Display press A in canvas doorBackground1.GetComponent <MeshRenderer>().material = doorActive; //if (OVRInput.GetUp(OVRInput.Button.One)) if (Input.GetMouseButtonUp(0)) { triggerDoor1 = true; pressA.SetActive(false); } } } if (triggerDoor1 == true) { airlockText.SetActive(true); door2Open["Take 001"].speed = -1.0f; door2Open.Play(); if (door2Open["Take 001"].time <= 0.0f) { airlockText.SetActive(false); door1Open["Take 001"].speed = 1.0f; door1Open.Play(); } triggerDoor1 = false; playerInside = false; exterior.SetActive(true); interior.SetActive(false); } }
void StartSpawnNpcAmmo() { if (XkGameCtrl.CheckNpcIsMoveToCameraBack(transform)) { return; } if (AudioNpcFire != null) { if (AudioNpcFire.isPlaying) { AudioNpcFire.Stop(); } AudioNpcFire.Play(); } GameObject obj = null; Transform tran = null; if (AmmoLiZiPrefab != null && AmmoLiZiObj == null) { obj = (GameObject)Instantiate(AmmoLiZiPrefab, AmmoSpawnTran.position, AmmoSpawnTran.rotation); tran = obj.transform; tran.parent = XkGameCtrl.NpcAmmoArray; AmmoLiZiObj = obj; XkGameCtrl.CheckObjDestroyThisTimed(obj); } if (AmmoPrefab == null) { return; } PlayerAmmoCtrl ammoPlayerScript = AmmoPrefab.GetComponent <PlayerAmmoCtrl>(); if (ammoPlayerScript != null && !XkGameCtrl.GetInstance().IsCartoonShootTest) { return; } obj = GetNpcAmmoFromList(AmmoSpawnTran); if (obj == null) { return; } tran = obj.transform; tran.parent = XkGameCtrl.NpcAmmoArray; NpcAmmoCtrl AmmoScript = obj.GetComponent <NpcAmmoCtrl>(); if (AmmoScript != null) { AmmoScript.SetNpcScriptInfo(NpcScript); AmmoScript.SetIsAimFeiJiPlayer(IsAimFeiJiPlayer); for (int i = 0; i < AmmoSpawnArray.Length; i++) { if (AmmoSpawnArray[i] != null) { obj = (GameObject)Instantiate(AmmoPrefab, AmmoSpawnArray[i].position, AmmoSpawnArray[i].rotation); tran = obj.transform; tran.parent = XkGameCtrl.NpcAmmoArray; AmmoScript = obj.GetComponent <NpcAmmoCtrl>(); AmmoScript.SetNpcScriptInfo(NpcScript); AmmoScript.SetIsAimFeiJiPlayer(IsAimFeiJiPlayer); } } } else { PlayerAmmoCtrl ammoScript = obj.GetComponent <PlayerAmmoCtrl>(); if (ammoScript != null) { Vector3 startPos = tran.position; Vector3 firePos = tran.position; Vector3 ammoForward = tran.forward; firePos = Random.Range(300f, 400f) * ammoForward + startPos; float fireDisVal = Vector3.Distance(firePos, startPos); RaycastHit hit; LayerMask FireLayer = XkGameCtrl.GetInstance().PlayerAmmoHitLayer; if (Physics.Raycast(startPos, ammoForward, out hit, fireDisVal, FireLayer.value)) { //Debug.Log("Unity:"+"npc fire PlayerAmmo, fire obj -> "+hit.collider.name); firePos = hit.point; XKNpcHealthCtrl healthScript = hit.collider.GetComponent <XKNpcHealthCtrl>(); if (healthScript != null) { healthScript.OnDamageNpc(ammoScript.DamageNpc, PlayerEnum.Null); } BuJiBaoCtrl buJiBaoScript = hit.collider.GetComponent <BuJiBaoCtrl>(); if (buJiBaoScript != null) { buJiBaoScript.RemoveBuJiBao(PlayerEnum.Null); //buJiBaoScript } } ammoScript.StartMoveAmmo(firePos, PlayerEnum.Null); } } }
private static void WardBush(Vector3 from, Vector3 endPosition) { if (!MenuExtensions.GetItemValue<bool>("iseriesr.vayne.misc.condemn.wardbush")) { return; } var wardSlot = Items.GetWardSlot(); if (wardSlot != null) { var wardPos = from.Extend(endPosition, from.Distance(endPosition) - 65f); if (NavMesh.IsWallOfGrass(wardPos, 65)) { if (Items.CanUseItem(wardSlot.Slot)) { Items.UseItem(wardSlot.Slot, wardPos); } } } }
// Method: "GetClosestFlightToDestination(Vector3 destination)" // What it Does: Returns the string name of the closest flightmaster to player desired Vector3 destination // Purpose: Sometimes the player wishes to travel to another zone, but only has the destination. // This could be useful at times when the destination is know, the player is far away, but // the exact ideal flightmaster is not known. This finds it for you. public static string GetClosestFlightToDestination(Vector3 destination) { int continentID = API.Me.ContinentID; string closestName = ""; Vector3 closestPosition; List<object> zones = new List<object>(); if (continentID == 1116) { zones = DraenorZones.GetEveryFlightMaster(); } if (zones.Count > 0) { closestName = (string)zones[0]; closestPosition = new Vector3((float)zones[1],(float)zones[2],(float)zones[3]); Vector3 temp; for (int i = 6; i < zones.Count - 5; i = i + 6) { temp = new Vector3((float)zones[i+1],(float)zones[i+2],(float)zones[i+3]); if (destination.Distance(temp) < destination.Distance(closestPosition)) { closestName = (string) zones[i]; closestPosition = temp; } } } return closestName; }