Inheritance: MonoBehaviour
 void Start()
 {
     m_Seeker = GetComponent<Seeker>();
     m_Seeker.pathCallback += OnPathComplete;
     m_Path = GetComponent<AIPath>();
     m_Path.MoveComplete += OnMoveComplete;
 }
示例#2
0
    protected virtual void Start()
    {
        timeToAttack = 0.5f;
        offsetMove = 1.0f;
        offsetLoot = 2.5f;
        myTransformPosition = new GameObject().transform;
        myTransformPosition.position = stayAt;

        //Debug.Log ("Ma Target est : " + target);

        parentGO = gameObject.transform.parent.gameObject;
        scriptPath = parentGO.GetComponent<AIPath>();

        //Debug.Log ("Mon parent est : " + parentGO.name + " Target : " + scriptPath.target);

        renderer.material.color = myColor;
        mustAttack = true;
        lifeToBack = 50;
        life = 100.0f;
        lifeMax = 100.0f;
        distanceToAttack = 10.0f; // Distance pour un CAC

        Vector3 pos = transform.position;

        LifeCapsule l = new LifeCapsule(pos);
        lifeCapsule = l.lifeC;
    }
示例#3
0
 public void FollowPath()
 {
     string json = Json.Serialize(GetPathDict ());
     AIPath p = new AIPath(json);
     p.SetContext(center.GetComponent<RectTransform>().anchoredPosition,0f,onscreenRadius);
     ai.StartFollowingPath(p);
 }
示例#4
0
文件: AIWorker.cs 项目: pbostrm/ceres
    public void DeliverWaypointPath(AIPath path)
    {
        waitingForWayPoints = false;

        if (activeWork == null)
        {
            DebugOutput.Shout("DeliverWaypointPath# activeWork is NULL");
            SetActiveWork(null);

        }
        else
        {
            if (path.successfulPath)
            {
                wayPoints = path.waypoints;

            }
            else if (path.outOfRange)
            {
                activeWork.assignedWorker = null;
                SetActiveWork(null);
            }
            else if (path.inaccessible)
            {
                activeWork.assignedWorker = null;
                SetActiveWork(null);
            }
        }
    }
示例#5
0
	void Start()
	{
		GameObject goItemManager = GameObject.FindGameObjectsWithTag("GameManager").FirstOrDefault( (go) => go.name == "Item Manager" );
		if( null == goItemManager )
			Debug.LogError( "Failed to find Item Manager game object");
		else
			m_Inventory = new Inventory( goItemManager.GetComponent<InventoryManager>() );

		m_Path = GetComponent<AIPath>();
		m_Seeker = GetComponent<Seeker>();

		// Find the start locator and set our position/orientation
		if( !string.IsNullOrEmpty( m_StartLocatorName ) )
		{
			GameObject[] locators = GameObject.FindGameObjectsWithTag( "Locator" );
			if( locators.Length > 0 )
			{
				GameObject startLocator = locators.FirstOrDefault( (i) => { return i.name == m_StartLocatorName; } );

				if( null != startLocator )
				{
					transform.position = startLocator.transform.position;
					transform.rotation = startLocator.transform.rotation;
				}
			}
		}
	}
 void Start()
 {
     anim = GetComponent<Animator>();
     cont = GetComponent<CharacterController>();
     currentMovement = GetComponent<AIPath>();
     isShiftDown = false;
     slowMoTime = 0f;
 }
示例#7
0
	void Awake()
	{
	    _myTransform = GetComponent<Transform>();
	    _myAiPath = GetComponent<AIPath>();
	    
	    _spawnPointManager = GameObject.Find("SpawnPoints").GetComponent<SpawnPointManager>();
	    
    }
示例#8
0
 void Awake()
 {
     agentObject = gameObject.transform.parent.gameObject;
     walker = (AIPath)agentObject.GetComponent("AIPath");
     agentComponent = (Agent)agentObject.GetComponent("Agent");
     walkSound = (AudioSource)gameObject.AddComponent("AudioSource");
     pathLine = agentObject.GetComponent<LineRenderer>();
     hasArrived = false;
 }
示例#9
0
 public void FollowPath(AIPath path)
 {
     if(rt == null){
         rt = GetComponent<RectTransform>();
     }
     Vector2 target = path.PathFollowingTarget(rt.anchoredPosition,lookAhead);
     pftarget = target;
     Seek (target);
 }
 // Use this for initialization
 void Start()
 {
     AI = this.GetComponent<AIPath>();
     Reflex_Count = Reflex_Set;
     Mode = "Sleep";
     AI.target = GameObject.Find("Player").transform;
     AI.canMove = false;
     AI.canSearch = false;
     enable = false;
 }
示例#11
0
    void Awake()
    {
        //Find the agent movement controller attached
        _agentPathfinder = GetComponent<AIPath>();

        //When an agent spawns, he should start by wandering
        aState = agentState.Wandering;

        //When an agent spawns, start updating his hunger level
        updateHunger();
    }
示例#12
0
 // Use this for initialization
 void Start()
 {
     playerControl = GetComponent<PlayerControl>();
     playerTransform = gameObject.transform;
     enemy = GameObject.FindGameObjectWithTag("Enemy");
     path = enemy.GetComponent<AIPath>();
     enemyControl = enemy.GetComponent<EnemyControl>();
     duration = gem.duration;
     startTime = Time.time + 2;
     check = true;
 }
示例#13
0
 void Awake()
 {
     agentObject = gameObject.transform.parent.gameObject;
     walker = (AIPath)agentObject.GetComponent("AIPath");
     agentComponent = (Agent)agentObject.GetComponent("Agent");
     walkSound = (AudioSource)gameObject.AddComponent("AudioSource");
     pathLine = agentObject.GetComponent<LineRenderer>();
     //Set speed of agent depending on its energy
     //walker.speed = 0.1f * agentComponent.GetEnergy();
     walker.speed = 10;
     hasArrived = false;
 }
 void OnTriggerEnter(Collider other)
 {
     if (other.gameObject.tag == "builder" && other.gameObject.GetComponent<AIPath>().target == transform)
     {
         unit = other.transform;
         //Destroy(other.gameObject);
         //other.gameObject.GetComponent<AIPath>().canSearch = false;
         //unitMR = unit.GetComponent<MeshRenderer>();
         //unitMR.enabled = false;
         unitPath = unit.GetComponent<AIPath>();
         unitPath.enabled = false;
     }
 }
 public override void OnStartServer()
 {
     this.AI = GetComponent<AIPath>();
     this.hearingCollider = GetComponent<SphereCollider>();
     this.capsuleCollider = GetComponent<CapsuleCollider>();
     this.forwardHash = Animator.StringToHash("Forward");
     this.turnHash = Animator.StringToHash("Turn");
     this.toChaseHash = Animator.StringToHash("ToChase");
     this.NearEnemies = new List<IControllerPlayer>();
     this.seeker = GetComponent<Seeker>();
     this.RVOController = GetComponent<RVOController>();
     this.MaxSpeedRVO = RVOController.maxSpeed;
 }
示例#16
0
    void Start()
    {
        aiPath = GetComponent<AIPath>();
        targetWayPointIndex = 0;
        aiPath.speed = Speed;
        alarmRadiusGO = transform.FindChild("AlarmRad").gameObject;
        alarmRadiusGO.transform.localScale *= AlarmRadius*2;
        alarmBar = transform.Find("alarm_timer/alarm bar").gameObject;
        SetNewTarget();
        seePlayer = false;

        playerPos = GameObject.FindGameObjectWithTag("Player").transform;
    }
    void Start()
    {
        myTransformPosition = new GameObject().transform;
        myTransformPosition.position = new Vector3(0.0f,0.0f,0.0f);

        Debug.Log ("Ma Target est : " + target);

        parentGO = gameObject.transform.parent.gameObject;
        scriptPath = parentGO.GetComponent<AIPath>();

        Debug.Log ("Mon parent est : " + parentGO.name + " Target : " + scriptPath.target);

        renderer.material.color = myColor;

        Vector3 pos = transform.position;

        LifeCapsule l = new LifeCapsule(pos);
        lifeCapsule = l.lifeC;

        chests = GameObject.FindGameObjectsWithTag ("ChestTAG");
    }
示例#18
0
	// Use this for initialization
	void Start () {

		player 		= GameObject.FindGameObjectWithTag("Player");
		manager 	= GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
	
		m_Pos 		= transform.position;
		m_Target 	= player.transform.position;
		m_Velocity 	= Vector3.zero;
		maxVelocity = new Vector3(5.0f, 5.0f, 5.0f);

		m_Speed 	= 50.0f;

		controller = GetComponent<CharacterController>();
		seek = GetComponent<Seeker>();
		seek.StartPath(m_Pos, m_Target, OnPathComplete);
		//seek.pathCallback += OnPathComplete;
		//seek.StartPath(m_Pos, m_Target, OnPathComplete);
		p = GetComponent<AIPath> ();
		p.target = player.transform;

		isPissed = false;
	}
示例#19
0
    void Start()
    {
        canvas = GetComponentInChildren<Canvas>();
        canvas.enabled = false;
        currentHealth = startingHealth;
        healthSlider.maxValue = startingHealth;
        anim = spider.animation;
        anim["Death"].wrapMode = WrapMode.Once;
        anim["Walk"].wrapMode = WrapMode.Loop;
        anim["Run"].wrapMode = WrapMode.Loop;
        anim["Attack"].wrapMode = WrapMode.Loop;
        aiPath = GetComponent<AIPath>();
        players = GameObject.FindGameObjectsWithTag("player");
        StartCoroutine(SearchForTarget());
        trans = transform;
        healthSliderTransform = healthSlider.transform;
        healthSlider.value = currentHealth;
        growthSliderTransform = growthSlider.transform;
        growthSlider.maxValue = growthRate;
        growthSlider.value = 0;

        gSliderOffset = trans.position - growthSliderTransform.position;
        hSliderOffset = trans.position - healthSliderTransform.position;

        audio = GetComponents<AudioSource>();
        shriek = audio[0];
        roar = audio[1];

        if (isSoldier || isQueen)
        {
            roar.Play();
            growthParticles.Play();
        }

        fill = healthSlider.GetComponentsInChildren<UnityEngine.UI.Image>()
            .FirstOrDefault(t => t.name == "Fill");

    }
示例#20
0
 public override void Awake()
 {
     base.Awake();
     if (_pathfinder == null)
     {
         _pathfinder = gameObject.AddComponent<AIPath>();
         _pathfinder.transform.parent = transform;
     }
 }
示例#21
0
文件: EnemyAI.cs 项目: tlight6/cyborg
    public void setSpeed(float newSpeed)
    {
        AIPath ai = GetComponent <AIPath>();

        ai.speed = newSpeed;
    }
示例#22
0
        // Assign the objects in a list to the FormationGridPoint(s) in the gridPoints list
        public bool AssignObjectsToGrid(List <GameObject> list)
        {
            bool result = true;

            if (list.Count > gridPoints.Count)
            {
                Debug.LogWarning("FormationGrid.AssignObjectsToGrid(): too many objects for this grid.");
                result = false;
            }

            for (int i = 0; i < list.Count; i++)
            {
                if (i < gridPoints.Count)
                {
                    GameObject go = list[i];

                    // Now check if the required components are available so we can move the objects
                    if (movementType == MovementType.CharacterController)
                    {
                        CharacterController cc = go.GetComponent <CharacterController>();
                        if (!cc)
                        {
                            Debug.LogError("FormationGrid.AssignObjectsToGrid(): GameObject to be assigned does not have the required CharacterController for this movement type.");
                        }
                    }
                    else if (movementType == MovementType.RigidBody)
                    {
                        Rigidbody rb = go.GetComponent <Rigidbody>();
                        if (!rb)
                        {
                            Debug.LogError("FormationGrid.AssignObjectsToGrid(): GameObject to be assigned does not have the required RigidBody for this movement type.");
                        }
                    }



#if T7T_ASTAR
                    AIPath aip = go.GetComponent <AIPath>();
                    if (aip)
                    {
                        FormationGridPoint fgp = gridPoints[i];
                        fgp.AssignUnit(go);

                        aip.target  = fgp.GetTransform();
                        aip.canMove = true;

                        Debug.Log("FormationGrid.AssignObjectsToGrid(): Assigned new target to object " + go.transform.name);
                    }
                    else
                    {
                        Debug.LogWarning("FormationGrid.AssignObjectsToGrid(): Assigned Object [" + go.transform.name + "] has no AIPath component.");
                        result = false;
                    }
#else
                    NavMeshAgent nma = go.GetComponent <NavMeshAgent>();
                    if (nma)
                    {
                        FormationGridPoint fgp = gridPoints[i];
                        fgp.AssignUnit(go);

                        nma.destination = fgp.GetPosition();

                        Debug.Log("FormationGrid.AssignObjectsToGrid(): Assigned new target to object " + go.transform.name);
                    }
                    else
                    {
                        Debug.LogWarning("FormationGrid.AssignObjectsToGrid(): Assigned Object [" + go.transform.name + "] has no Navmesh component.");
                        result = false;
                    }
#endif
                }
            }

            return(result);
        }
 void OnEnable()
 {
     path_target = (AIPath)target;
 }
示例#24
0
 public override void OnAwake()
 {
     ai     = GetComponent <AIPath>();
     seeker = GetComponent <Seeker>();
 }
示例#25
0
 // Called before Start
 private void Awake()
 {
     aIPath   = GetComponent <AIPath>();
     animator = GetComponent <Animator>();
 }
示例#26
0
 void Awake()
 {
     ai     = GetComponent <AIPath>();
     seeker = GetComponent <Seeker>();
 }
示例#27
0
 private void Awake()
 {
     aiPath = GetComponent <AIPath>();
     aIDestinationSetter = GetComponent <AIDestinationSetter>();
 }
示例#28
0
 private void Start()
 {
     sRenderer = GetComponent <SpriteRenderer>();
     aiPath    = GetComponent <AIPath>();
 }
示例#29
0
 // Start is called before the first frame update
 void Start()
 {
     aip = GetComponent <AIPath>();
 }
示例#30
0
 private void Awake()
 {
     _animator       = GetComponent <Animator>();
     _playerMovement = GetComponent <PlayerMovement>();
     aiPath          = GetComponent <AIPath>();
 }
示例#31
0
    public void setSpawnTag()
    {
        totalWaves = 10;
        GameObject[] tempPoints;
        pointCount = 0;

        pathPoints = new AIPath();

            string tag;

            tag = "0AI_Path1";
            tempPoints = GameObject.FindGameObjectsWithTag(tag);

            pointCount = tempPoints.Length;
            pathPoints = new AIPath(pointCount);

            for (int i = 0; i < pointCount; i++)
            {
                pathPoints.setPoint(i, tempPoints[i].GetComponent<Transform>().position);

            }
    }
示例#32
0
 public void Initilise(float initialMovementSpeed)
 {
     _ai = GetComponent<AIPath>();
     _moveSpeed = new ModifiableStat(initialMovementSpeed);
 }
示例#33
0
    protected override void Start()
    {
        base.Start();
        SelectableList.AddSelectableEntity(this);
        if (tag != "Mob")
            Debug.LogWarning(gameObject.ToString() + "'s tag is not set to Mob!");
        if (gameObject.layer != 11)
            Debug.LogWarning(gameObject.ToString() + "'s layer is not set to Object!");
        if (transform.FindChild("_lineOfSight") == null)
            Debug.LogWarning(gameObject.ToString() + "'s does not have a Line of Sight transform!");
        _healthPivot = transform.FindChild("_healthPivot");
        if (_healthPivot == null)
            Debug.LogWarning(gameObject.ToString() + "'s does not have a '_healthPivot' transform!");

        if (HUDRoot.go == null)
        {
            Debug.LogWarning("Hud Root is null!");
        }
        else
        {
            GameObject child = NGUITools.AddChild(HUDRoot.go, prefab);
            // Make the UI follow the target
            child.AddComponent<UIFollowTarget>().target = _healthPivot;
        }

        rigidbody.isKinematic = true;
        Hp = maxHp;
        _aiPath = GetComponent<AIPath>();
        _selectedTransform = transform.FindChild("_selectedTransform");
        if (_selectedTransform == null)
            Debug.LogWarning(gameObject.ToString() + "does not have a select transform, don't forget to add one!");
        SelectableList.AddSelectableEntity(this);
        _resource = GetComponent<Resource>();

        // Set Speed
        AIPath.speed = skills.speed;
        skills.actionSpeed = 0.5f;
    }
示例#34
0
 public override void OnAwake()
 {
     myHero   = GetComponent <ServerLifeNpc>();
     pathFind = myHero.pathFinding;
 }
 // Start is called before the first frame update
 void Start()
 {
     destinationSetter = GetComponent <AIDestinationSetter>();
     aIPath            = GetComponent <AIPath>();
 }
示例#36
0
 public override void Start(ControlledDivision Host)
 {
     _ai = Host.Controller.GetComponent <AIPath>();
     MoveToTarget(Host);
     base.Start(Host);
 }
示例#37
0
文件: EnemyAI.cs 项目: tlight6/cyborg
    public void changeTarget(Transform newTarget)
    {
        AIPath ai = GetComponent <AIPath>();

        ai.updateTarget(newTarget);
    }
示例#38
0
    private bool detectPlayer = false;// Start is called before the first frame update

    private void Start()
    {
        AiPath        = GetComponent <AIPath>();
        PiranhaPatrol = GetComponent <PiranhaPatrol>();
    }
示例#39
0
    public void nextCheckpoint()
    {
        if (_moveState == AIState.Search)
        {
            return;
        }
        #region LoopPath
        if (PathwayCount <= Pathways.Count - 1)
        {
            Path = Pathways[PathwayCount];
            if (Path == null)
            {
                return;
            }
            AIPath CheckpointScript = Path.GetComponent<AIPath>();

            switch (PathType[PathwayCount])
            {

                case 0:
                    if (CheckpointCount < CheckpointScript.getPoints().Count)
                    {
                        string CheckpointCountString = CheckpointCount.ToString();
                        ChangeNavPoint(CheckpointCountString, CheckpointScript.getPoints()[CheckpointCount]);
                        if (CheckpointCount != CheckpointScript.getPoints().Count)
                        {
                            CheckpointCount++;
                        }
                    }
                    else
                    {
                        if (PathwayCount != Pathways.Count - 1)
                        {
                            PathwayCount++;
                            CheckpointCount = 0;
                        }
                        else
                        {
                            return;
                        }
                    }
                    break;

                case 1:
                    if (LoopCount <= nofLoops[PathwayCount])
                    {
                        if (CheckpointCount < CheckpointScript.getPoints().Count)
                        {
                            string CheckpointCountString = CheckpointCount.ToString();
                            ChangeNavPoint(CheckpointCountString, CheckpointScript.getPoints()[CheckpointCount]);
                            if (CheckpointCount != CheckpointScript.getPoints().Count)
                            {
                                CheckpointCount++;
                            }
                        }
                        else
                        {
                            CheckpointCount = 0;

                            if (!infinite[PathwayCount])
                            {
                                LoopCount++;
                            }
                        }
                    }
                    else
                    {
                        PathwayCount++;
                        CheckpointCount = 0;
                        LoopCount = 1;
                    }
                    break;

                case 2:
                    if (LoopCount <= nofLoops[PathwayCount])
                    {
                        if ((CheckpointCount < CheckpointScript.getPoints().Count) && (back == false))
                        {
                            string CheckpointCountString = CheckpointCount.ToString();
                            ChangeNavPoint(CheckpointCountString, CheckpointScript.getPoints()[CheckpointCount]);
                            if (CheckpointCount != CheckpointScript.getPoints().Count)
                            {
                                CheckpointCount++;
                            }
                        }
                        else
                        {
                            if (CheckpointCount > 0)
                            {
                                back = true;
                                CheckpointCount--;
                                string CheckpointCountString = CheckpointCount.ToString();
                                ChangeNavPoint(CheckpointCountString, CheckpointScript.getPoints()[CheckpointCount]);

                            }
                            else
                            {
                                back = false;

                                if (!infinite[PathwayCount])
                                {
                                    LoopCount++;
                                }
                            }
                        }
                    }
                    else
                    {
                        PathwayCount++;
                        CheckpointCount = 0;
                        LoopCount = 1;
                    }
                    break;

                case 3:
                    if (CheckpointCount < CheckpointScript.getPoints().Count)
                    {
                        string CheckpointCountString = CheckpointCount.ToString();
                        ChangeNavPoint(CheckpointCountString, CheckpointScript.getPoints()[CheckpointCount]);
                    }
                    break;
            }
        }
        else
        {

        }
    }
示例#40
0
    private void Update()
    {
        if (helpTime > 0 && targetPriority < 3)
        {//주변에 아군 챔피언이 맞았으면 헬프타임이 3이 된다.
            helpTime -= Time.deltaTime;
            if (helpTime <= 0)
            {     //헬프타임이 처음 뜬 지 3초가 지났다
                if (!enemiesList.Contains(nowTarget))
                { //적이 범위를 벗어났다 => 타겟 초기화
                    nowTarget = null;
                }
                else
                { //적이 범위 안에 아직 있다 => 3초 더 팬다
                    helpTime += 3;
                }
            }
        }
        if (enemiesList.Count > 0)
        {
            bool check = false;
            if (nowTarget == null)
            {//주변에 적이 있는데 내가 타겟이 아예 없다 = 타겟팅 하자
                check = true;
            }
            else if (nowTarget.tag.Equals("WayPoint"))
            {//주변에 적이 있는데 잡은 타겟이 웨이포인트거나, 액티브 펄스다 = 타겟팅 하자
                check = true;
            }
            else if (!nowTarget.activeInHierarchy)
            {
                check = true;
                enemiesList.Remove(nowTarget);
            }
            if (check)
            {//주변에 적 있는데 타겟팅 안한거 확인. 타겟팅 하자.
                TargetSearch();
            }
            if (nowTarget.tag != "WayPoint")
            {//현재 타겟이 웨이포인트가 아닌 공격할 대상이다.
                if (TheAIPath == null)
                {
                    TheAIPath = myMinion.GetComponent <AIPath>();
                }
                float a = Vector3.Distance(nowTarget.transform.position, myMinion.transform.position);
                //if ((nowTarget.transform.position - myMinion.transform.position).sqrMagnitude > AtkRange)
                float atkRevision = 0;
                if (nowTarget.tag.Equals("Tower") && AtkRange < 5)
                {
                    atkRevision = 3f;
                }
                tempVec1   = nowTarget.transform.position;
                tempVec2   = myMinion.transform.position;
                tempVec1.y = 0;
                tempVec2.y = 0;
                if (Vector3.Distance(tempVec1, tempVec2) > AtkRange + atkRevision)
                {         //공격 범위 밖에 적이 있다.
                    if (!TheAIPath.canMove)
                    {     //이동 안한다고 해뒀던 상황이면
                        if (AtkCoroutine != null)
                        { //공격을 끈 후
                            StopCoroutine(AtkCoroutine);
                            AtkCoroutine = null;
                        }
                        Anim.SetBool("walking", true);//이동을 풀어준다.
                        TheAIPath.canMove   = true;
                        TheAIPath.canSearch = true;
                    }
                }
                else
                {//공격 범위 안에 적이 있다.
                    if (TheAIPath.canMove)
                    {
                        Anim.SetBool("walking", false);
                        TheAIPath.canMove   = false;
                        TheAIPath.canSearch = false;
                        AtkCoroutine        = StartCoroutine(AtkMotion());
                        myMinion.transform.DOLookAt(nowTarget.transform.position, 1);
                    }
                }
            }
        }
        else if (nowTarget != null)
        {     //주변에 적이 없는데 내가 타겟을 가지고 있다.
            if (nowTarget.tag != "WayPoint")
            { //거기다 타겟이 웨이포인트가 아니다.
                if (!TheAIPath.canMove)
                {
                    TheAIPath.canMove   = true;
                    TheAIPath.canSearch = true;
                    Anim.SetBool("walking", true);
                    if (AtkCoroutine != null)
                    {//공격을 끈 후
                        StopCoroutine(AtkCoroutine);
                        AtkCoroutine = null;
                    }
                }
                nowTarget        = MoveTarget; // 그럼 타겟을 깔끔하게 새로 잡자.
                TheAIDest.target = nowTarget.transform;
            }
        }
        else
        {
            if (MoveTarget != null)
            {
                nowTarget        = MoveTarget;
                TheAIDest.target = nowTarget.transform;
            }
        }

        //if (enemiesList.Count > 0)
        //{
        //    if (nowTarget == null)
        //    {
        //        MoveTarget = TheAIDest.target.gameObject;
        //        float dist = 1000000, nowD;
        //        for (int i = 0; i < enemiesList.Count; ++i)
        //        {
        //            nowD = (enemiesList[i].transform.position - transform.position).sqrMagnitude;
        //            if (dist > nowD)
        //            {
        //                dist = nowD;
        //                nowTarget = enemiesList[i];
        //            }
        //        }
        //        TheAIDest.target = nowTarget.transform;
        //    }
        //    else if (!nowTarget.activeInHierarchy)
        //        RemoveNowTarget();
        //}



        //if (nowTarget != null)
        //{
        //    if ((nowTarget.transform.position - transform.position).sqrMagnitude > AtkRange)
        //    {//이동
        //        if (AtkCoroutine != null)
        //        {
        //            StopCoroutine(AtkCoroutine);
        //            AtkCoroutine = null;
        //        }
        //        if (!TheAIPath.canMove)
        //        {
        //            Anim.SetBool("walking", true);
        //            TheAIPath.canMove = true;
        //            TheAIPath.canSearch = true;
        //        }
        //    }
        //    else
        //    {//공격
        //        if (TheAIPath.canMove)
        //        {
        //            Anim.SetBool("walking", false);
        //            TheAIPath.canMove = false;
        //            TheAIPath.canSearch = false;
        //            AtkCoroutine = StartCoroutine(AtkMotion());
        //            transform.DOLookAt(nowTarget.transform.position, 1);
        //        }
        //    }
        //}
        //else if (!TheAIPath.canMove)
        //{
        //    TheAIPath.canMove = true;
        //    TheAIPath.canSearch = true;
        //    nowTarget = MoveTarget;
        //    TheAIDest.target = nowTarget.transform;
        //}
    }
示例#41
0
 /// <summary>
 /// Resets the internal patrol logic. Recommended to use when the data.path is changed
 /// </summary>
 public void ResetPath()
 {
     targetPathNode = null;
     patrolPath     = null;
 }
示例#42
0
 private void Start()
 {
     _aiPath = GetComponent <AIPath>();
 }
示例#43
0
	public void StartNewPath()
	{
		seek = GetComponent<Seeker>();
		seek.StartPath(m_Pos, m_Target, OnPathComplete);
		p = GetComponent<AIPath> ();
		p.target = player.transform;
	}
示例#44
0
        ///<inheritdoc/>
        public override void Update()
        {
            //Check if player visible, and switch to attention state if so
            AISensors.VisionResult visionResult = entity.Sensors.CheckVision();
            if (visionResult.playerVisible)
            {
                if (entity.Data.currentPlayerSpotWaitTime > 0)
                {
                    entity.Data.currentPlayerSpotWaitTime -= Time.deltaTime;
                }
                else
                {
                    entity.Data.lastSeenPlayerPosition = Player.Instance.transform.position;
                    controller?.SwitchState(controller?.attentionState);
                    return;
                }
            }
            else
            {
                if (entity.Data.currentPlayerSpotWaitTime < entity.Data.PlayerSpotWaitTime)
                {
                    entity.Data.currentPlayerSpotWaitTime += Time.deltaTime;
                }
            }

            if (visionResult.attentionPoint != null)
            {
                entity.Attention();
                entity.assignedZone.PropogatePlayerPosition(visionResult.attentionPoint.position);
                visionResult.attentionPoint.gameObject.SetActive(false);
                return;
            }

            if (visionResult.fearPoint != null)
            {
                AIUtils.InitiateFear(entity, visionResult.fearPoint);
            }

            if (!entity.InFear)
            {
                //Patrol routine
                if (entity.Data.Path != null)
                {
                    //Select target point
                    patrolPath = entity.Data.Path;
                    if (targetPathNode == null)
                    {
                        targetPathNode = entity.Data.Path.Next(out AIPath newPath);
                        if (newPath != null)
                        {
                            entity.Data.Path = newPath;
                        }
                        if (targetPathNode != null)
                        {
                            entity.Data.pointWaitTime = targetPathNode.WaitTime;
                        }
                    }
                    else
                    {
                        //Movement to target point, stay and rotate towards point direction if wait time is > 0
                        controller?.MoveTo(targetPathNode.Pos);
                        if (Vector3.Distance(entity.transform.position, targetPathNode.Pos) < 0.75f)
                        {
                            entity.Data.pointWaitTime -= Time.deltaTime;
                            if (entity.Data.pointWaitTime > 0f)
                            {
                                controller?.RotateTo(targetPathNode.Dir);
                            }
                            else
                            {
                                targetPathNode = null;
                            }
                        }
                    }
                }
                else
                {
                    //Move to spawn point if no path
                    controller?.MoveTo(entity.Data.spawnPoint);
                    if (Vector3.Distance(entity.transform.position, entity.Data.spawnPoint) < 0.75f)
                    {
                        controller?.RotateTo(lastDir);
                    }
                }
            }

            //Sleep routine
            entity.Data.waitForSleep -= Time.deltaTime;
            if (entity.Data.waitForSleep <= 0f)
            {
                controller?.Sleep();
            }
        }
示例#45
0
 void Awake()
 {
     this.aiPath = this.gameObject.GetComponent<AIPath> ();
     this.levelManager = GameObject.FindWithTag ("LevelManager").GetComponent<LevelManager> ();
     this.initialPosition = this.levelManager.PositionToMatrix (this.transform.position);
     this.aiPath.enabled = false;
     Transform wormTransform = this.transform.Find ("worm");
     if (wormTransform != null) {
         this.worm = wormTransform.gameObject;
     }
 }
示例#46
0
 public virtual void Set(AIPath path)
 {
     Set(path.GetPath());
 }
示例#47
0
 // Use this for initialization
 public void Start()
 {
     SetRole (defaultRole);
     nameGenerator = new NameGenerator ();
     staffName = Helper.GenerateName (male, Random.Range (2,3));
     TakeOwnership ();
     myPath = GetComponent<AIPath>();
     myWaypoint = GetComponentInChildren<StaffWaypoint>();
 }
示例#48
0
 // Use this for initialization
 void Start()
 {
     male = Helper.RandomBool ();
     patientName = Helper.GenerateName (male, Random.Range (2,3));
     RandomCondition ();
     myPath = GetComponent<AIPath>();
     EnterClinic();
 }
示例#49
0
    public void StartMoving()
    {
        //Debug.Log ("start moving called on " + this.ToString());
        ConfigureEnemy ();
        steering = gameObject.AddComponent<Steering>() as Steering;
        steering.enemy = this;
        float speedMult = 1f/(impactTime/NORMAL_IMPACT_TIME);
        steering.maxSpeed = speedMult * NORMAL_SPEED;
        steering.referenceMaxSpeed = steering.maxSpeed;
        steering.maxAccel = steering.maxSpeed/FRAMES_FROM_ZERO_TO_MAX;
        steering.referenceMaxAccel = steering.maxAccel;
        path = AIPath.CreatePathFromJSONFilename(moverType);
        path.SetDialDimensions(Dial.spawnLayer.anchoredPosition,Dial.FULL_LENGTH);
        path.SetAngle(GetStartingTrackAngle() + (-trackLane*15f) + moverLaneOverride);
        steering.StartFollowingPath(path);
        /*List<Vector2> pathlist = path.GetPathAsListOfVectors();
        foreach(Vector2 node in pathlist){ //path visualization
            GameObject dot = new GameObject();
            Image dimg = dot.AddComponent<Image>() as Image;
            dot.transform.SetParent(Dial.unmaskedLayer,false);
            dot.GetComponent<RectTransform>().sizeDelta = new Vector2(5f,5f);
            dot.GetComponent<RectTransform>().anchoredPosition = node;
        }*/
        //some scaling- could maybe be done through transform.scale, but I don't trust Unity to handle the collider
        ScaleEnemy();
        spawned = true;
        moving = true;

        //float angle = Mathf.Atan2(rt.anchoredPosition.y , rt.anchoredPosition.x);
        //ySpeed = Mathf.Sin (angle) * speed;
        //xSpeed = Mathf.Cos (angle) * speed;
    }
示例#50
0
	void Awake() {
		timeWaited = timeToWait;
		vision = GetComponent<CreatureSight>();
		cam = visionCamera.GetComponent<CameraTexture>();
		lastPosMarker = new GameObject(name+"  Last Known Position Marker");
		aiPath = GetComponent<AIPath>();
		anim = GetComponent<Animator>();

		anim.SetBool("Enraged", false);
		anim.SetBool("Run", false);
		anim.SetBool("Walk", false);
		anim.SetBool("Attack", false);
		anim.SetBool("Search", false);
		anim.SetBool("Absorb", false);

		GetNearestWaypoint();
	}
示例#51
0
 // Use this for initialization
 void Start()
 {
     path = gameObject.GetComponent<AIPath>();
     prevSpeed = path.speed;
     path.speed = prevSpeed * factor;
 }
示例#52
0
 public AIDestinationPointScanner(AIPath aiPath)
 {
     _aiPath = aiPath;
 }
示例#53
0
 public virtual void Awake()
 {
     CM   = GetComponent <CharacterMovement>();
     path = GetComponent <AIPath>();
 }
示例#54
0
        // Update is called once per frame
        void Update()
        {
            if (anchor == null)
            {
                return;
            }

            if (state == FormationStates.Form)
            {
                for (int i = 0; i < gridPoints.Count; i++)
                {
                    FormationGridPoint fgp = gridPoints[i];
                    if (fgp != null)
                    {
                        if (fgp.IsUnitAssigned())
                        {
                            FormationUnitAnimation formationUnitAnimation = fgp.GetFormationUnitAnimation();
                            if (formationUnitAnimation)
                            {
                                GameObject go = fgp.GetAssignedUnit();
                                if (go)
                                {
#if T7T_ASTAR
                                    AIPath aip = go.GetComponent <AIPath>();
                                    formationUnitAnimation.velocity = aip.CalculateVelocity(Vector3.zero); // obselete but velocity property is not available.
#else
                                    NavMeshAgent nma = go.GetComponent <NavMeshAgent>();
                                    formationUnitAnimation.velocity = nma.velocity;
#endif
                                }
                            }
                        }
                    }
                }
            }

            if (state == FormationStates.Move)
            {
                if ((oldPosition - anchorPosition).sqrMagnitude > 0.001f * 0.001f)  // TODO: potentially we can do this by checking if target has been reached
                {
                    positionDirty = true;
                }
                else
                {
                    positionDirty = false;
                }

                if (Mathf.Abs(anchorRotation.eulerAngles.y - oldRotation) > 0.01f)
                {
                    rotationDirty = true;
                }
                else
                {
                    rotationDirty = false;
                }

                Quaternion target = anchorRotation;
                if (rotationDirty)
                {
                    transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smoothRotation);
                }

                // Rotate the units at grid points to align with anchor rotation:
                // TODO: can we check when not to run this by means of "fully rotated" units?
                if (formationAnchor != null)
                {
                    // Vector3 velocity = formationAnchor.GetVelocity();

                    for (int i = 0; i < gridPoints.Count; i++)
                    {
                        FormationGridPoint fgp = gridPoints[i];
                        if (fgp != null)
                        {
                            if (fgp.IsUnitAssigned())
                            {
                                GameObject au = fgp.GetAssignedUnit();

                                au.transform.rotation = Quaternion.Slerp(au.transform.rotation, target, Time.deltaTime * smoothRotation);
                            }
                        }
                    }
                }



                if (positionDirty)
                {
                    transform.position = anchorPosition;    // Move the Formation to Anchor position. TODO: If dampening needed, do Lerp here.

                    if (randomizeOffset > 0.0F)
                    {                                       // Randomize the positions slightly if enabled
                        reRandomizeOffsets += Time.deltaTime;

                        if (reRandomizeOffsets > reRandomizeNextTime)      // ReRandomize the gridpoints every 3 seconds
                        {
                            reRandomizeOffsets  = 0.0F;
                            reRandomizeNextTime = reRandomizeTimeMin + (reRandomizeTimeMax - reRandomizeTimeMin) * Random.value;

                            for (int i = 0; i < gridPoints.Count; i++)
                            {
                                FormationGridPoint fgp = gridPoints[i];
                                fgp.RandomizePosition();
                            }
                        }
                    }

                    CalculatePositionsAllGridPoints();      // Calculate all Grid Points relative to the Anchor which has moved by means of A*Pathfinfing.
                }



                // Now move the units (assigned to grid positions) towards their grid position:

                // TODO: Add a check here to stop if all units have arrived.

                if (formationAnchor != null)
                {
                    float   endReachedDistance = formationAnchor.endReachedDistance;
                    Vector3 vlcity             = formationAnchor.GetVelocity();

                    //DebugPanel.Log("Anchor velocity", "Anchor", vlcity.magnitude);


                    for (int i = 0; i < gridPoints.Count; i++)
                    {
                        FormationGridPoint fgp = gridPoints[i];
                        if (fgp != null)
                        {
                            if (fgp.IsUnitAssigned())
                            {
                                switch (movementType)
                                {
                                case MovementType.RigidBody:
                                    // Do nothing since in case of rigidbody we use FixedUpdate() instead of Update()
                                    //MoveUnitsRigidBodyMode(i, fgp, vlcity, endReachedDistance);
                                    break;

                                case MovementType.CharacterController:
                                    MoveUnitsCharacterControllerMode(i, fgp, vlcity, endReachedDistance);
                                    break;

                                default:
                                    Debug.LogError("FormationGrid.Update(): Unknown movementType");
                                    break;
                                }


                                FormationUnitAnimation formationUnitAnimation = fgp.GetFormationUnitAnimation();
                                if (formationUnitAnimation)
                                {
                                    formationUnitAnimation.velocity = fgp.GetAssignedVelocity();
                                    //DebugPanel.Log("FUA.velocity", "Unit Animation", fgp.GetAssignedVelocity());
                                }
                            }
                        }

                        oldPosition = anchorPosition;
                        oldRotation = transform.rotation.eulerAngles.y;
                    }
                }
            }

            if (state == FormationStates.Disband)
            {
                if (disbandTimer == 0.0f)
                {
                    // set the directions for each assigned unit
                    for (int i = 0; i < gridPoints.Count; i++)
                    {
                        FormationGridPoint fgp = gridPoints[i];
                        if (fgp != null)
                        {
                            if (fgp.IsUnitAssigned())
                            {
                                fgp.SetDisbandDesitination(disbandRadius, mask);
                                fgp.SetPositionToDisband(mask);
                            }
                        }
                    }
                    ChangeMoveStateOnGridObjects(true);
                    disbanded = false;
                }


                // start a timer, for x seconds have the assigned units move into a random direction
                disbandTimer += Time.deltaTime;
                if (disbandTimer < disbandDuration)
                {
                    // Move them

                    //DebugPanel.Log("disbandtimer", "disband", disbandTimer);
                }
                else
                {
                    if (!disbanded)
                    {
                        ChangeMoveStateOnGridObjects(false);
                        ChangeAnimationStateOnGridObjects(false);
                        disbanded = true;
                    }
                }
            }
        }
 public CircularWaypointMotionProvider(AIPath path, AIDestinationSetter destinationSetter, Transform self, IEnumerable <Transform> waypoints)
     : base(path, destinationSetter, self, waypoints)
 {
 }
示例#56
0
 // Start is called before the first frame update
 void Start()
 {
     agent = GetComponent <AIPath>();
     speed = agent.maxSpeed;
 }
示例#57
0
 private void Start()
 {
     aiPath           = GetComponent <AIPath>();
     aiPath.isStopped = true;
 }
示例#58
0
 void Start()
 {
     animator = GetComponent <Animator>();
     path     = GetComponentInParent <AIPath> ();
 }
示例#59
0
        public void AddPlayers(MSGPlayer player, OnlinePlayer p)
        {
            if (Players.ContainsKey(player.user))
            {
                return;
            }
            if (MPManager.Client != null && player.user == MPManager.Client.UserName)
            {
                return;                                                                       //do not add self//WARNING: may need to worry about train number here
            }
            if (p == null)
            {
                p = new OnlinePlayer(null, null);
            }
            p.url = player.url;
            p.LeadingLocomotiveID = player.leadingID;
            p.con  = MPManager.Simulator.BasePath + "\\TRAINS\\CONSISTS\\" + player.con;
            p.path = MPManager.Simulator.RoutePath + "\\PATHS\\" + player.path;
            Train train = new Train(MPManager.Simulator);

            train.TrainType = Train.TRAINTYPE.REMOTE;
            if (MPManager.IsServer()) //server needs to worry about correct train number
            {
            }
            else
            {
                train.Number = player.num;
            }
            if (player.con.Contains("tilted"))
            {
                train.IsTilting = true;
            }
            int direction = player.dir;

            train.travelled        = player.Travelled;
            train.TrainMaxSpeedMpS = player.trainmaxspeed;

            if (MPManager.IsServer())
            {
                try
                {
                    AIPath aiPath = new AIPath(MPManager.Simulator.TDB, MPManager.Simulator.TSectionDat, p.path, MPManager.Simulator.TimetableMode);
                }
                catch (Exception) { MPManager.BroadCast((new MSGMessage(player.user, "Warning", "Server does not have path file provided, signals may always be red for you.")).ToString()); }
            }

            try
            {
                train.RearTDBTraveller = new Traveller(MPManager.Simulator.TSectionDat, MPManager.Simulator.TDB.TrackDB.TrackNodes, player.Location, direction == 1 ? Traveller.TravellerDirection.Forward : Traveller.TravellerDirection.Backward);
            }
            catch (Exception e)
            {
                if (MPManager.IsServer())
                {
                    MPManager.BroadCast((new MSGMessage(player.user, "Error", "MultiPlayer Error:" + e.Message)).ToString());
                }
                else
                {
                    throw new Exception();
                }
            }
            for (var i = 0; i < player.cars.Length; i++)// cars.Length-1; i >= 0; i--) {
            {
                string   wagonFilePath = MPManager.Simulator.BasePath + @"\trains\trainset\" + player.cars[i];
                TrainCar car           = null;
                try
                {
                    car            = RollingStock.Load(MPManager.Simulator, wagonFilePath);
                    car.CarLengthM = player.lengths[i] / 100.0f;
                }
                catch (Exception error)
                {
                    System.Console.WriteLine(error.Message);
                    car = MPManager.Instance().SubCar(wagonFilePath, player.lengths[i]);
                }
                if (car == null)
                {
                    continue;
                }
                bool flip = true;
                if (player.flipped[i] == 0)
                {
                    flip = false;
                }
                car.Flipped = flip;
                car.CarID   = player.ids[i];
                train.Cars.Add(car);
                car.Train = train;
                MSTSWagon w = (MSTSWagon)car;
                if (w != null)
                {
                    w.SignalEvent((player.pantofirst == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 1);
                    w.SignalEvent((player.pantosecond == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 2);
                    w.SignalEvent((player.pantothird == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 3);
                    w.SignalEvent((player.pantofourth == 1 ? PowerSupplyEvent.RaisePantograph : PowerSupplyEvent.LowerPantograph), 4);
                }
            }// for each rail car

            if (train.Cars.Count == 0)
            {
                throw (new Exception("The train of player " + player.user + " is empty from "));
            }

            p.Username        = player.user;
            train.ControlMode = Train.TRAIN_CONTROL.EXPLORER;
            train.CheckFreight();
            train.InitializeBrakes();
            bool canPlace = true;

            Train.TCSubpathRoute tempRoute = train.CalculateInitialTrainPosition(ref canPlace);
            if (tempRoute.Count == 0 || !canPlace)
            {
                MPManager.BroadCast((new MSGMessage(p.Username, "Error", "Cannot be placed into the game")).ToString());//server will broadcast this error
                throw new InvalidDataException("Remote train original position not clear");
            }

            train.SetInitialTrainRoute(tempRoute);
            train.CalculatePositionOfCars();
            train.ResetInitialTrainRoute(tempRoute);

            train.CalculatePositionOfCars();
            train.AITrainBrakePercent = 100;

            //if (MPManager.Instance().AllowedManualSwitch) train.InitializeSignals(false);
            for (int iCar = 0; iCar < train.Cars.Count; iCar++)
            {
                var car = train.Cars[iCar];
                if (car.CarID == p.LeadingLocomotiveID)
                {
                    train.LeadLocomotive = car;
                    (train.LeadLocomotive as MSTSLocomotive).Headlight    = player.headlight;
                    (train.LeadLocomotive as MSTSLocomotive).UsingRearCab = player.frontorrearcab == "R" ? true : false;
                }
                if (car is MSTSLocomotive && MPManager.IsServer())
                {
                    MPManager.Instance().AddOrRemoveLocomotive(player.user, train.Number, iCar, true);
                }
            }
            if (train.LeadLocomotive == null)
            {
                train.LeadNextLocomotive();
                if (train.LeadLocomotive != null)
                {
                    p.LeadingLocomotiveID = train.LeadLocomotive.CarID;
                }
                else
                {
                    p.LeadingLocomotiveID = "NA";
                }
            }

            if (train.LeadLocomotive != null)
            {
                train.Name = train.GetTrainName(train.LeadLocomotive.CarID);
            }
            else if (train.Cars != null && train.Cars.Count > 0)
            {
                train.Name = train.GetTrainName(train.Cars[0].CarID);
            }
            else if (player != null && player.user != null)
            {
                train.Name = player.user;
            }

            if (MPManager.IsServer())
            {
                train.InitializeSignals(false);
            }
            p.Train = train;

            Players.Add(player.user, p);
            MPManager.Instance().AddOrRemoveTrain(train, true);
        }
示例#60
0
    public void SetMovePosition(Vector3 movePosition)
    {
        AIPath aIPath = GetComponent <AIPath>();

        aIPath.destination = movePosition;
    }