Questions in topic: "chase"http://answers.unity.com/questions/topics/single/3022.html
The latest questions for the topic "chase"How do I get my AI to chase the player?,How do I go from patrolling to chasing the player?http://answers.unity.com/questions/1625325/how-do-i-get-my-ai-to-chase-the-playerhow-do-i-go.html
I am new to Unity and Scripting. So far I have a code to where my AI makes a patrol around my Nav Mesh. I want to have it chase the player and attack the player when the player comes into a certain range, but return to patrolling once the player gets out of that range. This is for an Oculus project. Any help is greatly appreciated. Here is the code I have so far:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class NPCSimplePatrol : MonoBehaviour
{
//Dictates whether the agent waits on each node
[SerializeField]
bool _patrolWaiting;
//The total time we wait at each node
[SerializeField]
float _totalWaitTime = 3f;
//The probability of switching direction
[SerializeField]
float _switchProbability = 0.2f;
//The list of all patrol nodes to visit
[SerializeField]
List<Waypoint> _patrolPoints;
//Private variables for base behaviour
NavMeshAgent _navMeshAgent;
int _currentPatrolIndex;
bool _travelling;
bool _waiting;
bool _patrolForward;
float _waitTimer;
public Transform player;
static Animator anim;
//Use this for initialization
public void Start()
{
anim = GetComponent<Animator>();
_navMeshAgent = this.GetComponent<NavMeshAgent>();
if(_navMeshAgent == null)
{
Debug.LogError("The nav mesh agent component is not attached to " + gameObject.name);
}
else
{
if(_patrolPoints != null && _patrolPoints.Count >= 2)
{
_currentPatrolIndex = 0;
SetDestination();
}
else
{
Debug.Log("Insufficient patrol points for basic patrolling behaviour.");
}
}
}
public void Update()
{
//Check if we're close to destination
if (_travelling && _navMeshAgent.remainingDistance <= 1.0f)
{
_travelling = false;
//If we're going to wait, then wait
if (_patrolWaiting)
{
_waiting = true;
_waitTimer = 0f;
}
else
{
ChangePatrolPoint();
SetDestination();
}
}
//Instead if we're waiting
if (_waiting)
{
anim.SetBool("IsIdle", true);
anim.SetBool("IsWalking", false);
anim.SetBool("IsAttacking", false);
_waitTimer += Time.deltaTime;
if (_waitTimer >= _totalWaitTime)
{
_waiting = false;
ChangePatrolPoint();
SetDestination();
anim.SetBool("IsIdle", false);
anim.SetBool("IsWalking", true);
anim.SetBool("IsAttacking", false);
}
}
}
private void SetDestination()
{
if (_patrolPoints != null)
{
Vector3 targetVector = _patrolPoints[_currentPatrolIndex].transform.position;
_navMeshAgent.SetDestination(targetVector);
_travelling = true;
}
}
/// <summary>
/// Selects a new patrol point in the available list but
/// also with a small probability allows for us to move forward or backwards
/// </summary>
private void ChangePatrolPoint()
{
if(UnityEngine.Random.Range(0f, 1f) <= _switchProbability)
{
_patrolForward = !_patrolForward;
}
if (_patrolForward)
{
_currentPatrolIndex = (_currentPatrolIndex + 1) % _patrolPoints.Count;
}
else
{
if(--_currentPatrolIndex < 0)
{
_currentPatrolIndex = _patrolPoints.Count - 1;
}
}
}
}c#aipatrolchaseWed, 24 Apr 2019 02:02:33 GMTADay0RememberChase script. I added a FOV now he won't engagehttp://answers.unity.com/questions/1607981/chase-script-i-added-a-fov-now-he-wont-engage.html
My chase script was working okay until I added a fov of <30. Now he doesn't engage me anymore. Another thing I was wondering about - Before I added in the FOV and he was chasing me around his walking animation was really clunky. Very hit/ miss. For the most part he was sliding. Is this because I chose to slow of a walking animation? Or maybe I should slow down his movement speed?
Thank you!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Chase : MonoBehaviour
{
public Transform player; //Access Player character
static Animator anim; //Access animator
//Initalization
void Start()
{ //Animator
anim = GetComponent<Animator>();
}
//Update is called once per frame
void Update()
{ //Enemy attack range and field of view
Vector3 direction = player.position - this.transform.position;
float angle = Vector3.Angle(direction, this.transform.forward);
if (Vector3.Distance(player.position, this.transform.position) < 10 && angle <30)
{
direction.y = 0;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation, Quaternion.LookRotation(direction), 0.1f);
anim.SetBool("isIdle", false);
if (direction.magnitude > 2)
{ //Enemy walks within range to attack
this.transform.Translate(0, 0, 0.05f);
anim.SetBool("isWalking", true);
anim.SetBool("isAttacking", false);
}
else
{ //Enemy is within range //Stops walking and attacks
anim.SetBool("isAttacking", true);
anim.SetBool("isWalking", false);
}
}
else
{
anim.SetBool("isIdle", true);
anim.SetBool("isWalking", false);
anim.SetBool("isAttacking", false);
}
}
}c#aistuckfovchaseSat, 02 Mar 2019 04:10:48 GMTinaudiblefuzzEnemy chase script // No longer attackinghttp://answers.unity.com/questions/1605694/enemy-chase-script-no-longer-attacking.html
My enemy chase script was up and running when I get within 10 units he chases me down. I added in a fov so he'll engage when within 30 degrees. He's no longer attacking at all. I messed something up... I don't know what. Any ideas? - Thanks!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Chase : MonoBehaviour
{
public Transform player; //Access Player character
static Animator anim; //Access animator
void Start() //Initalization
{
anim = GetComponent<Animator>();
}
void Update() //Update is called once per frame
{
Vector3 direction = player.position - this.transform.position;
float angle = Vector3.Angle(direction, this.transform.forward);
if (Vector3.Distance(player.position, this.transform.position) < 10 && angle <30)
{
direction.y = 0;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation, Quaternion.LookRotation(direction), 0.1f);
anim.SetBool("isIdle", false);
if (direction.magnitude > 2)
{
this.transform.Translate(0, 0, 0.05f);
anim.SetBool("isWalking", true);
anim.SetBool("isAttacking", false);
}
else
{
anim.SetBool("isAttacking", true);
anim.SetBool("isWalking", false);
}
}
else
{
anim.SetBool("isIdle", true);
anim.SetBool("isWalking", false);
anim.SetBool("isAttacking", false);
}
}
}c#aienemy aichaseSun, 24 Feb 2019 01:34:16 GMTinaudiblefuzztrying to do pathfinding for my guard in 2d gridhttp://answers.unity.com/questions/1590616/trying-to-do-pathfinding-for-my-guard-in-2d-grid.html
so i been trying to make a stealth game for a game jam and i'm trying to make it so the guard follows the player and it's grid base, but i been trying to all night and day and still haven't found a salutation to my problem, can anyone help? i tryed Astar library and all i got was this ![alt text][1]
[1]: https://media.discordapp.net/attachments/343317866646470656/534684189048569856/line.JPGpathfindingtilemapmovmentchaseWed, 16 Jan 2019 02:29:20 GMTArmyAntsStudiosNavMeshAgent isn't chasing the playerhttp://answers.unity.com/questions/1573330/navmeshagent-isnt-chasing-the-player.html
Hi. I am trying to make an enemy chasing. But the enemy doens't recognize the player at all. Just goes somewhere and stays. ![alt text][1]
Here is my inspector and code:
` public GameObject target;
private NavMeshAgent agent;
void Start()
target = GameObject.Find("Player");
agent = GetComponent<NavMeshAgent>();}
void Update(){
agent.destination = target.transform.position; }`
[1]: /storage/temp/128050-ss.pngainavmeshnavmeshagentbakechaseTue, 20 Nov 2018 03:21:40 GMTjudasPriest_How to chase and change material,How to chase an object and change material on touch with AI?http://answers.unity.com/questions/1570141/how-to-chase-and-change-materialhow-to-chase-an-ob.html
I am trying to make purple capsules chase after yellow capsules, then when a purple touches a yellow, the yellow capsule turns to purple and chase after other yellow capsules (like a zombie infection).
Te only problem is that I have no idea of what I am doing. I don't now how to talk to unity. The only thing I know is that if it is purple then it chases after yellow, if it touches yellow then yellow turns to purple and back to square one.
Somebody told me I could use tags and even tough I googled some answers or something that could help me, nothing works.
Please help....please
please ,I am trying to make purple capsules chase after yellow capsules, and when they "catch" them the yellow capsules will turn to purple capsules and now go and chase other yellow capsules (like zombies)
The only problem is that I have no idea of what I am doing. I thought I could do it with tags. The objects whit "Purple" tag should chase the ones with "Yellow" Tag and when they touch then the object with "Yellow" tag will change to "Purple" and adopt the purple capsule functions (chasing and transforming other yellow capsules)unity 5materialaichangechaseFri, 09 Nov 2018 02:56:53 GMTfridaaznarHow do I make it so that a walking animation plays for the enemy AT THE SAME TIME it is moving toward the player?http://answers.unity.com/questions/1514914/how-do-i-make-it-so-that-a-walking-animation-plays.html
I have been stuck on this for a while. I have it so that "isKinematic" starts out as true for the enemy's rigidbodies until (you shoot its colliders and) it dies as a ragdoll. When it dies, "isKinematic" turnes false, and its animator turns off.
I'm having trouble because in order to make the enemy's walk animation play, "isKinematic" must = true, but also, if "isKinematic" = true, then I can't code it to move toward the player.
Also, I should probably let you guys know that I can't use the method where you make a parent for the enemy and put the walking code on that parent (for reasons too long to explain). I pretty much need it so that the code to make the enemy move is on the enemy game object that the animator is present on.animationaienemyfollowchaseWed, 06 Jun 2018 05:36:49 GMTb2hinkleCoroutine never stops...http://answers.unity.com/questions/1472354/coroutine-never-stops.html
<br>Hi.
<br>I made two Coroutines.
<br>One for wander and one for chase.
<br>I used all kind of code to make wander stops when chasing, but it almost never chases player and wander.
<br>I used yield break, yield return null, stopcoroutine, named it with string, etc...
<br>But it never stops wandering..
<br>I just let them yield break to see if it will make my wandering stops, but it doesn't!!
<br>Here is my code.
<br>Help me God bless you all.
public Transform sight;
public GameObject Player;
NavMeshAgent navMeshAgent;
NavMeshPath path;
public float timeForNewPath;
Vector3 target;
bool inCoRoutine;
bool chasing;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent> ();
path = new NavMeshPath ();
chasing = false;
navMeshAgent.speed = speedController.speedValue;
}
void Update()
{
// Two CoRoutines with chasing and wandering.
if (!inCoRoutine && !chasing)
{
StartCoroutine ("Wandering");
StopCoroutine ("Chase");
}
if (chasing)
{
StartCoroutine ("Chase");
StopCoroutine ("Wandering");
}
//This is for move animation.
if (navMeshAgent.velocity.magnitude > 1.0f)
{
anim.SetBool ("IsWalking", true);
}
else
{
anim.SetBool ("IsWalking", false);
}
}
Vector3 getNewRandomPosition()
{
float x = Random.Range (-45, -5);
float y = Random.Range (-0.2f, 0.2f);
float z = Random.Range (-33, 25);
Vector3 pos = new Vector3 (x, y, z);
return pos;
}
IEnumerator Wandering()
{
if (!chasing)
{
inCoRoutine = true;
yield return new WaitForSeconds (timeForNewPath);
GetNewPath ();
inCoRoutine = false;
}
if (chasing)
{
yield break;
}
}
IEnumerator Chase()
{
if (chasing)
{
GetNewPath ();
yield return new WaitForSeconds (timeForNewPath);
target = Player.transform.position;
navMeshAgent.SetDestination (target);
}
if (!chasing)
{
yield break;
}
}
void GetNewPath()
{
if (!chasing)
{
target = getNewRandomPosition ();
navMeshAgent.SetDestination (target);
}
else if (chasing)
{
target = Player.transform.position;
navMeshAgent.SetDestination (target);
}
}
void OnTriggerStay()
{
Ray ray = new Ray (sight.position, sight.forward);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 30.0f))
{
sight.LookAt (Player.transform.position);
if (hit.transform.CompareTag ("Player"))
{
chasing = true;
Debug.Log ("Hello");
}
else
{
chasing = false;
Debug.Log ("No");
}
}
}
void OnTriggerExit()
{
chasing = false;
}
}yieldienumeratorboolchasewanderFri, 23 Feb 2018 09:12:10 GMTPaincideStudioAI chase/follow problemhttp://answers.unity.com/questions/1469732/ai-chasefollow-problem.html
<br>Hi I made a script which AI wanders and when see player, it starts to chase player.
<br>But it never chase the player even though it see the player.
<br>I'm trying to make AI raycasts player.
<br>Here is the script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class BeuBaeMovement : MonoBehaviour {
public GameObject B;
public GameObject Player;
NavMeshAgent navMeshAgent;
NavMeshPath path;
public float timeForNewPath;
bool inCoRoutine;
Vector3 target;
bool validPath;
public Animator anim;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent> ();
path = new NavMeshPath ();
}
void Update()
{
if (!inCoRoutine)
StartCoroutine (DoSomething ());
if (navMeshAgent.velocity.magnitude > 1.0f)
{
anim.SetBool ("IsWalking", true);
}
else
{
anim.SetBool ("IsWalking", false);
}
Vector3 left15Degs = Quaternion.Euler (0, -15, 0) * transform.forward;
Ray ray = new Ray(B.transform.position, left15Degs);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 3.0f))
{
if (hit.collider.CompareTag("Player"))
{
navMeshAgent.destination = Player.transform.position;
}
}
}
Vector3 getNewRandomPosition()
{
float x = Random.Range (-120, 120);
float z = Random.Range (-120, 120);
Vector3 pos = new Vector3 (x, 0, z);
return pos;
}
IEnumerator DoSomething()
{
inCoRoutine = true;
yield return new WaitForSeconds (timeForNewPath);
GetNewPath ();
validPath = navMeshAgent.CalculatePath (target,path);
while (!validPath)
{
yield return new WaitForSeconds (0.01f);
GetNewPath ();
validPath = navMeshAgent.CalculatePath (target,path);
}
inCoRoutine = false;
}
void GetNewPath()
{
target = getNewRandomPosition ();
navMeshAgent.SetDestination (target);
}
}raycastainavmeshchaseSat, 17 Feb 2018 06:45:04 GMTPaincideStudioHow to change enemy's Direction on FiniteStateMachine???http://answers.unity.com/questions/1437306/how-to-change-enemys-direction-on-finitestatemachi.html
Hello coders.. just a quick question to make:
I have a small terrain with a character that is moving on it(user input- keyboard&mouse), and i also have a enemy object that has a Finite state machine.
However, I think the State Machine is working fine from IDLE to PATROL and back.
public enum State { IDLE, PATROL, CHASE} //ALL STATES IN ENUM
public State myState; //ONE STATE
private bool alive;
public GameObject[] wayPoints;
private int wayPointIndex = 0; //Store the current index of waypoints
void Start()
{
StartCoroutine("FiniteStateMachine"); //Call State Machine
}
IEnumerator FiniteStateMachine()
{
//While the tiger is alive do switch statement for the State Machine
while (alive)
{
switch (myState)
{
case State.IDLE:
Idle(); //Tiger Is not Moving
break;
case State.PATROL:
Patrol(); //Tiger Is Moving from Waypoint to Waypoint
break;
case State.CHASE:
Chase(); //Tiger Is Chasing the Character
break;
}
yield return null;
} //End of While Loop
----------
How should i change the Enemy's direction when the States are changing since it has a different direction for wayPoints and different direction for the target using Vector 3 for both cases.
----------
private Vector3 wayPointDirection; //Use for the Way Points (PATROL State)
private Vector3 targetDirection; //Use for the target (CHASE State)
If you have a question ill be happy to answer asap. and i will really appreciate it if you guys will help me out fix this issue. :))directionwaypointpatrolchasefinite-state-machineThu, 30 Nov 2017 20:29:02 GMTloizos-95bEnemy shaking when following playerhttp://answers.unity.com/questions/1402882/enemy-shaking-when-following-player.html
Alright! I have a issue with my enemy. Whenever I get withing a "chase" distance(which is in float), it it supposed to follow the player. Which it does. However, when it chases the player, it starts to shake/wobble. I am not sure what is causing this but I'll link a video demostrating what I mean. And the code to the EnemyAI as well.
P.S I am using a NavMeshAgent which rotates to the player with transform.LookAt(player) and a transform.forward.(You can see this is `void Chase()`
-Video: https://streamable.com/fijld
(Don't mind the enemy stopping at a waypoint, it's because of the (stopping distance) > (when to go to next point.)
Have a nice day!
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI: MonoBehaviour {
#region Variables
[Header ("Navigation Variables")]
public Transform[] waypoints;
private int wayPointIndex = 0;
public NavMeshAgent agent;
[Header("Chase Variables")]
public Transform player;
public float chaseSpeed;
public float attackDist;
public float chaseDist;
public float stopChaseDist;
float checkForPlayer = 0;
[Header("Attack Variables")]
public float damage;
public float range;
public Camera enemyCamera;
public float timeBetweenEnemyAttack;
float timer;
#endregion
void Start ()
{
agent = GetComponent<NavMeshAgent>();
agent.autoBraking = false;
}
void FixedUpdate ()
{
timer += Time.deltaTime;
if(!agent.pathPending && agent.remainingDistance < 0.5f)
{
GoToNextPoint();
}
if (player == null)
{
FindPlayer();
return;
}
float dist = Vector3.Distance(transform.position, player.position);
if (dist > chaseDist && dist < stopChaseDist)
{
Chase();
//Debug.Log(dist);
}
if (dist < attackDist && timer >= timeBetweenEnemyAttack)
{
Attack();
}
}
public void GoToNextPoint()
{
if (waypoints.Length == 0)
return;
agent.destination = waypoints[wayPointIndex].position;
wayPointIndex = Random.Range(0, waypoints.Length);
}
void Chase()
{
transform.LookAt(player);
transform.position += transform.forward * chaseSpeed * Time.deltaTime;
// Vector3 targetDir = player.position - transform.position;
//targetDir.y = 0;
// Debug.Log("Start chase!");
}
void Attack()
{
timer = 0f;
RaycastHit hit;
transform.LookAt(player);
//Debug.Log("Attack Player!");
if (Physics.Raycast(enemyCamera.transform.position, enemyCamera.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Debug.DrawLine(enemyCamera.transform.position, hit.point);
PlayerHealth Player = hit.transform.GetComponent<PlayerHealth>();
if (Player != null)
{
Player.TakeDamage(damage);
}
}
}
void FindPlayer()
{
if (checkForPlayer <= Time.time)
{
GameObject searchResult = GameObject.FindGameObjectWithTag("Player");
if (searchResult != null)
player = searchResult.transform;
checkForPlayer = Time.time + 0.5f;
}
}
}enemynavmeshagentchaseTue, 05 Sep 2017 12:39:35 GMTXerofaHow to make my enemy discover, chase and lose player.http://answers.unity.com/questions/1399966/how-to-make-my-enemy-discover-chase-and-lose-playe.html
I have been try to find and try the code from google and unity3d.com, but still cannot work, maybe i dun understand.
The code i using now is
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GuardMovement : MonoBehaviour
{
//public float speed;
Rigidbody2D rb;
private Animator animator;
protected Vector3 velocity;
public Transform _transform;
public float distance = 5f;
public float speed = 1f;
Vector3 _originalPosition;
bool isGoingLeft = false;
public float distFromStart;
/*private float movespd = 1.0f;
//private int dir = -1;
public const float TurnLimit = 3.5f, CheckLimit = 2.0f;
public bool detect_player = false;
public bool after_chase = false;
public bool checkplayerloc = false;
public bool dirCheck = false;
public bool chgdir = false;
public enum State{Patrol, ChasePlayer, ReturnToOriloc};
public State behaviourState;
private Rigidbody2D enemy_rb2d;
private Vector3 oriloc;
private Vector2 newposition;
//private float checktime = CheckLimit;
//turntime = TurnLimit,*/
private Transform player;
void Start ()
{
rb = GetComponent <Rigidbody2D> ();
animator = this.GetComponent<Animator> ();
_originalPosition = gameObject.transform.position;
_transform = GetComponent<Transform>();
velocity = new Vector3(speed,0,0);
_transform.Translate ( velocity.x*Time.deltaTime,0,0);
player = GameObject.FindGameObjectWithTag ("Player").transform;
//oriloc = transform.position;
//behaviourState = State.Patrol;
//enemy_rb2d = gameObject.GetComponent<Rigidbody2D> ();
}
void Update ()
{
distFromStart = transform.position.x - _originalPosition.x;
if (isGoingLeft)
{
// If gone too far, switch direction
if (distFromStart < -distance)
SwitchDirection ();
_transform.Translate (-velocity.x * Time.deltaTime, 0, 0);
if (distFromStart < 3)
{
animator.SetInteger ("Direction", 3);
}
}
else
{
// If gone too far, switch direction
if (distFromStart > distance)
SwitchDirection ();
_transform.Translate (velocity.x * Time.deltaTime, 0, 0);
if (distFromStart > -3)
{
animator.SetInteger ("Direction", 1);
}
}
}
void SwitchDirection()
{
isGoingLeft = !isGoingLeft;
//TODO: Change facing direction, animation, etc
}
}
How do i put the code inside my code that the enemy have chase my character in a certain distance, after that distance enemy will go back to it own certain area continuous walk around in that area.enemy2d-platformerdistancepathfindingchaseMon, 28 Aug 2017 18:03:53 GMTchinjlMy sphere collider doesn't detect my player!http://answers.unity.com/questions/1392881/my-sphere-collider-doesnt-detect-my-player.html
Hello and thank you for your time!
I have attached an empty child object to my zombie, an it is called PlayerSensor. It has a sphere collider into it, and it is inTrigger and radius 4. The idea is to switch to chase state in the finite state machine when this "playerSensor" detects our player.
However I am having trouble. Currently it doesn't detect the player and just detects the bullet but not when it enters into the 4m spheric perimeter but into the zombie's hit box itself.
Could you help me please?
Also as further reference I provide pictures:
![PLAYER][1]
![ZOMBIE][2]
[1]: /storage/temp/99754-player.png
[2]: /storage/temp/99755-zombie.png
"PlayerSensor"
http://imgur.com/V5eF3uh
Chase coroutine!
IEnumerator Chase(){
while (currentState == state.Chase) {
towardsTarget = currentTarget.position - transform.position;
MoveTowards (towardsTarget);
if (towardsTarget.magnitude > maxChaseDistance)
ChangeState (state.Wander);
yield return 0;
}
}
When event activates:
void OnTriggerEnter(Collider other){
Debug.Log (other.name+" detectado");
if(other.CompareTag("Player")){
Debug.Log ("PLAYEEER detectado");
currentTarget=other.transform;
ChangeState(state.Chase);
}
}
Debug log after testing:
http://imgur.com/evpftWm
Video tutorial I am following:
https://www.youtube.com/watch?v=3m4U_YgQtvQ&list=PLrvYYIXHycoogAkWSut5OTty_ujdNDV8u&index=18
THANK you for your time, I need some advice!chaseSat, 12 Aug 2017 16:14:27 GMTenoyCheck if player is in enemys fov?http://answers.unity.com/questions/1317739/check-if-player-is-in-enemys-fov.html
Hey there,
i'd like to let my enemy start chasing the player when he is in his fov (~180°).
The enemy is flying btw.
I read about using Physics.OverlapSphere
Anyone got a solution for this? I don't want to use triggers because it really annoying adding all those triggers to my different kind of enemies.
My idea is making an 180° raycast on the ground (from the position of the enemy) and check if the player got hitted too! If true the enemy should directly face the player and send out a standard raycast to check if there is an object between both (the player is hidden).
But how to make a 180° hit check?
Greetsraycastenemy aioverlapfovchaseThu, 23 Feb 2017 21:26:13 GMTJannickLC# Enemy AI, when player is not visible i want the Enemy to chase the player for a few more seconds and then stop.http://answers.unity.com/questions/1310775/c-enemy-ai-when-player-is-not-visible-i-want-the-e.html
The enemy is sitting and if a player interacts with it it chases the player and if it cannot find the player in a **few seconds** the enemy will go sit again, **the script works** but i can't make the ai wait for a few seconds. *any tips?*
using UnityEngine;
using System.Collections;
public class SittingEnemyAI : MonoBehaviour {
[Header("Transforms")]
public Transform ChairPoint;
public Transform player;
public Transform Front;
[Header("Sight Range")]
public float Range;
[HideInInspector]
public Animator anim;
[HideInInspector]
private NavMeshAgent agent;
[HideInInspector]
public bool Patrolling;
private bool lost;
void Awake ()
{
agent = GetComponent<NavMeshAgent>();
anim = GetComponentInChildren<Animator> ();
Patrolling = true;
}
void Update ()
{
if (Patrolling == true)
{
lost = false;
Lost ();
}
if (lost == true)
{
StartCoroutine (StillLooking ());
}
//Debug.DrawRay (Front.position, Front.forward * Range);
RaycastHit hit;
Ray View = new Ray (Front.position, Front.forward);
if (Physics.Raycast (View, out hit, Range))
{
if (hit.collider.tag == "Player")
{
Chasing ();
StopCoroutine (StillLooking ());
}
else
{
if (Patrolling == false)
{
lost = true;
}
}
}
else
{
if (Patrolling == false)
{
lost = true;
}
}
if (anim.GetCurrentAnimatorStateInfo (0).IsName ("sit_to_stand"))
{
anim.SetBool ("StandUp", false);
}
if (anim.GetCurrentAnimatorStateInfo (0).IsName ("Running"))
{
Chasing ();
}
if (anim.GetCurrentAnimatorStateInfo (0).IsName ("Walk"))
{
agent.destination = ChairPoint.position;
Patrolling = true;
}
if (anim.GetCurrentAnimatorStateInfo (0).IsName ("looking_around"))
{
agent.destination = this.transform.position;
anim.SetBool ("StandUp", false);
}
if (anim.GetCurrentAnimatorStateInfo (0).IsName ("Typing"))
{
transform.rotation = ChairPoint.transform.rotation;
}
}
public void Chasing()
{
anim.SetBool ("Chase", true);
agent.destination = player.position;
agent.speed = 3.0f;
agent.angularSpeed = 360.0f;
Vector3 lookAtPosition = player.position;
lookAtPosition.y = transform.position.y;
transform.LookAt (lookAtPosition);
anim.SetBool ("Sit", false);
Patrolling = false;
}
void Lost()
{
anim.SetBool ("Chase", false);
agent.speed = 0.5f;
Patrolling = true;
}
void OnTriggerEnter(Collider collider)
{
if (collider.tag == "EnemySit")
{
anim.SetBool ("Sit", true);
}
}
IEnumerator StillLooking()
{
Chasing ();
yield return new WaitForSeconds (3);
Lost ();
lost = false;
Patrolling = true;
}
}playeraiwaitforsecondsai problemschaseThu, 09 Feb 2017 15:54:07 GMTMickeyAnimNavMeshAgent not moving at given speedhttp://answers.unity.com/questions/1310160/navmeshagent-not-moving-at-given-speed.html
Hey there,
I have a problem with my NavMeshAgent and the movement of 3D models.
I have two gameobjects (3d model guards) that have exactly the same movement settings but move differently. Additionally, I don't know if that's related, the navmeshagent.distance of one of the guards is 'infinity' at some points.
Scenario:
![alt text][1]
So what happens in short:
I attract the attention of guard 1 which then begins to chase me (state = CHASE). After a while he calls out for help which makes the other guards run to the position guard 1 passed on to them (state = SEARCH).
While guard 1 still happily chases me at the intended speed, the other guards keep moving at the walking speed but the animation is the one for running (which looks pretty silly of course...).
After approximately 2/3 of the way they also begin running at full speed as intended.
Every variable I can think of is correctly set but the agent just won't move correctly. I've read that addind a coroutine can enhance the behaviour of a NavMeshAgent? Had no luck with that though.
Any suggestions?
Cheers,
Dan
[1]: /storage/temp/87587-scenario.png
**EDIT:** I've also now tested the actual speed of the guard while moving to the given position. With this code:
private Vector3 previousPosition;
public float curSpeed;
void Update()
{
Vector3 curMove = transform.position - previousPosition;
curSpeed = curMove.magnitude / Time.deltaTime;
previousPosition = transform.position;
}
It is pretty accurately the same as what the navmeshagent shows in the inspector. So the speed is at 1 but the guard is obviously not moving that fast! What the....!?!?navmeshagentpathfindingbug-perhapschasefinite-state-machineTue, 07 Feb 2017 21:07:03 GMTDaDarkDanHow to make "enemy" have a frustum(cone) view and not a circle radiushttp://answers.unity.com/questions/1306016/how-to-make-enemy-have-a-frustumcone-view-and-not.html
So I have an enemy script, and it works perfectly, but the only thing I don't like about it is that it chases the player when it's in a circle radius that I can change. I want to make it a cone shaped view where the enemy can only see the player. Similar to the radius, but not a circle AROUND the enemy. but ahead of the enemy in a certain direction. I am also using an array to detect if there are walls in the way. Here is the code for the following part. (Of course the script has more code)
Vector3 difference = playerTransform.position - transform.position;
bool hit = Physics.Raycast(transform.position, difference.normalized, difference.magnitude, 9);
Debug.DrawRay(transform.position, difference, Color.red);
if (difference.sqrMagnitude < distanceUntilChase && !targetPlayer.isInBush && !hit) // Conditions to follow the player
{
// Chasing player
goneImage.SetActive(false);
StartCoroutine(AlertNotice());
coroutineRunAlert = true;
coroutineRunGone = false;
rb.velocity = difference.normalized * chaseSpeed;
rotZTarget = Mathf.Atan2(-difference.x, -difference.z) * Mathf.Rad2Deg; // Calculates the angle between angle and enemy (from difference)]
lastSeenTime = Time.time + timeUntilPatrol;
lastSeenPosition = playerTransform.position;
//timeUntilNextPoint = Mathf.Infinity;
}
This is what I have: ![alt text][1]
And this is what I want: ![alt text][2]
The blue square is the player, the red square is the enemy, and the black outlines represent the radius.
[1]: /storage/temp/86963-whatihave.png
[2]: /storage/temp/86964-whatiwant.pngc#raycastplayeraichaseMon, 30 Jan 2017 07:49:55 GMTSpid3rtechMake enemy's weapon chase a game objecthttp://answers.unity.com/questions/1294995/unity-steamvr-make-enemy-chase-playereven-if-the-p.html
Would it be possible if anyone could help me with a code that makes it where the enemy can target a game object, even if the game object is moving? I am trying to make a game object that targets a player.
Or in simpler words, make a homing bullettargetinggameobject.findchasehomingenemy-aiFri, 06 Jan 2017 05:29:23 GMTcaptmemory12Problem with chasing aihttp://answers.unity.com/questions/1286322/problem-with-chasing-ai.html
the code is working pretty well at first until the AI manage to catch the 1st mouse in the array it stop chasing and it give the error that said "the object have been destroy but you still try to access it" which is weird cuz if the other object in array get destroy it still work perfectly.
here is the code
public Transform[] mouses;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 currentPos = transform.position;
Transform tMin = null;
float minDist = Mathf.Infinity;
foreach (Transform mouse in mouses)
{
float dist = Vector3.Distance(mouse.position, currentPos);
if (dist < minDist)
{
tMin = mouse;
minDist = dist;
transform.LookAt(tMin);
transform.position += transform.forward * 3.5f * Time.deltaTime;
}
Debug.Log(tMin);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "mouse")
{
Destroy(other.gameObject);
}
}aichaseFri, 16 Dec 2016 11:58:38 GMTkurakuramakiHave Ghost go from Patrolling to Chasing - Pacmanhttp://answers.unity.com/questions/1272537/have-ghost-go-from-patrolling-to-chasing-pacman.html
I'm currently working on recreating Pacman in 2D (NOT 3D) and I am having trouble with one aspect. I understand how to get the ghosts to move along a deterministic path of waypoints. However, I'm wondering how to code it so that it follows this path while patrolling, but then if the Pacman object gets within a certain radius of a ghost while its patrolling, that ghost begins chasing the Pacman directly. How would you suggest doing this? Any help appreciated! Thanks!2dwaypointpatrolchasepacmanThu, 17 Nov 2016 07:18:25 GMTthatgirljaynaEnemy's NavMesh not workinghttp://answers.unity.com/questions/1257502/enemys-navmesh-not-working.html
Hey guys.
I'm new in Unity and I don't know why my code doesn't work. When range is under 15, enemy should chase player, but instead of this it stops. Also, it is a little lagged when arrives at each point. How can I resolve this?
public Transform[] patrolPoints;
public float moveSpeed;
private int currentPoint;
private GameObject Player1;
private GameObject currentPlayer;
private bool Patrolling = true;
private NavMeshAgent navComp;
// Use this for initialization
void Start () {
currentPoint = 0;
Player1 = GameObject.FindGameObjectWithTag ("Player");
currentPlayer = Player1;
navComp = this.GetComponent<NavMeshAgent> ();
// transform.position = patrolPoints [0].position;
}
// Update is called once per frame
void Update () {
float range = Vector3.Distance (transform.position, currentPlayer.transform.position);
transform.position = Vector3.MoveTowards (transform.position, patrolPoints [currentPoint].position, moveSpeed * Time.deltaTime);
if (Patrolling) {
if (transform.position == patrolPoints [currentPoint].position) {
currentPoint++;
}
if (currentPoint >= patrolPoints.Length) {
currentPoint = 0;
}
if (range <= 15) {
Patrolling = false;
}
//transform.LookAt (patrolPoints [currentPoint].transform.position);
}
else if (Patrolling == false) {
//transform.position = Vector3.MoveTowards (transform.position, currentPlayer.transform.position, moveSpeed * Time.deltaTime);
navComp.SetDestination(currentPlayer.transform.position);
if (range >= 20) {
Patrolling = true;
}
}
}
}playeraienemynavmeshagentchaseMon, 17 Oct 2016 05:01:46 GMTvithorescamesHow to make an enemy stay behind youhttp://answers.unity.com/questions/1243932/how-to-make-an-enemy-stay-behind-you.html
I wanted to make an endless runner game, but i have a little problem. I never tried to make a game like this one, and i am kinda new, so i wanted to do a game like this so i can "gain some experience" with lots of things, but i am stuck in the enemy.
Most endless runners give you a second chance when you almost hit something or dodge an obstacle immediately after being hit by it. I wanted to make a giant flaming ball that i have here to go after the player for 7 seconds, but ONLY in a specific place. Like, it rotates forward and follow the player, but only stay a few meters from it, without actually hitting the player. Could someone help me on this? It would help a lot, because i don't know much about scripting yet, and i am just a beginner in AI.
I made a script that make an object follow the player, but i don't know what to change in the script so it makes what i want.
#pragma strict
var Player : Transform;
var MoveSpeed = 4;
var MaxDist = 10;
var MinDist = 5;
function Start ()
{
}
function FixedUpdate ()
{
transform.LookAt(Player);
if(Vector3.Distance(transform.position,Player.position) >= MinDist){
transform.position += transform.forward*MoveSpeed*Time.deltaTime;
if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
{
//Here Call any function U want Like Shoot at here or something
}
}
}
It follows the player, and you can set the enemy's speed, minimum and max distance to detect and follow the player.scripting beginnerfollow playerchasestay in placeThu, 15 Sep 2016 03:12:11 GMTZitooxHow do I make a character run away from the player?http://answers.unity.com/questions/1241753/enemy-stares-at-the-player-but-wont-follow-them.html
This is a bit of a weird one but if I wanted to have a model that runs away from the player whenever they get close, then stop when the player contacts the model, how would I go about doing that?
So basically it would be like playing tag only when the player tags the model, they would actually pick up the model, if that makes sense.
Also(based on an issue I'm having with a chasing NPC) how do I stop the model from running through physical objects/meshes of buildings, props, etc? I've added a mesh collider to both this model and the other chasing model but they still go through objects P:c#chaseSat, 10 Sep 2016 08:18:27 GMTCraftyMaelyssHow do I make an enemy chase the player with a C script?http://answers.unity.com/questions/1240332/how-do-i-make-an-enemy-chase-the-player-with-a-c-s.html
Basically I've been searching this for ages and the techniques and scripts I've seen and tried haven't been able to work, so this is why I'm asking here.
How do I write a script so that when the player walks within a certain range, the enemy will start to chase them but when they're further away, they will just look in their direction?
Again I've been through the answers, I've googled this topic and read through a lot of forums and I still can't seem to get it to work. This is one of the scripts that I tried to use from a tutorial(that didn't work) so maybe someone can see where I've gone wrong?
using UnityEngine;
using System.Collections;
public class FogMan : MonoBehaviour {
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var range : float=10f;
var range2 : float=10f;
var stop : float=0;
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy acces/performance
}
function Start()
{
Target = GameObject.FindWithTag("Basehuman01b").transform; //target the player
}
function Update () {
//rotate to look at the player
var distance = Vector3.Distance(myTransform.position, target.position);
if (distance<=range2 && distance>=range){
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position -- myTransform.position), rotationSpeed*Time.deltaTime);
}
else if(distance<=range && distance>stop){
//move towards the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
else if (distance<=stop) {
myTransform.rotation = Quaternion/Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
}
}c#aichaseWed, 07 Sep 2016 14:33:06 GMTCraftyMaelyssMy Cubes wont Chase mehttp://answers.unity.com/questions/1225584/my-cubes-wont-chase-me.html
I was working on another Game. This time I wanted my Cubes to follow / chase me along a Raycast.
It seems like the PlayerPos part in my variablies does have some problems...
var Player : GameObject;
var Enemy : GameObject;
var speed : float = 5;
var raycastDist : float = 20;
var hit : RaycastHit;
var ray : Ray;
var playerPos : Vector3 = Player.transform.position;
function FixedUpdate() {
var EyeRay = new Ray(Player.transform.position, Enemy.transform.position - Player.transform.position);
if (Physics.Raycast(EyeRay, hit, raycastDist))
transform.Translate(speed * playerPos * Time.deltaTime);
}
Any ideas?raycastenemyvariableschaseSat, 06 Aug 2016 02:47:17 GMTCortex00How to fix my chasing/attacking code?http://answers.unity.com/questions/1210820/how-to-fix-my-chasingattacking-code.html
So how the code currently works is, the enemy will find the player and move towards him. When he finds him, he will stop and then start attacking. If the player moves away though, the enemy will stop attacking and just sit there until the player comes back into range. How can I fix it so that when the player moves out of range, the enemy starts chasing again and then attacks as normal?
float moveSpeed = 3f;
float rotationSpeed = 3f;
float attackThreshold = 3f; //distance within which to attack
float chaseThreshold = 10f; //distance within which to start chasing
float giveUpThreshold = 20f; //distance beyond which AI gives up
float attackRepeatTime = 1f; //time between attacks
bool attacking = false;
bool chasing = false;
float attackTime;
Transform target; //the enemy's target
Transform myTransform; //current transform data of the enemy
void Update()
{
//rotate to look at the player
float distance = (target.position - myTransform.position).magnitude;
if (chasing)
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
}
//move towards the player
if (chasing == true && attacking == false)
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
//give up if too far away
if (distance >= giveUpThreshold)
{
chasing = false;
// attacking = false;
}
//attack, if close enough, and if time is OK
if (distance <= attackThreshold && Time.time >= attackTime) //if attacking we want to stop moving
{
//attack here
bossAttack.Attack();
attackTime = Time.time + attackRepeatTime;
print("Attacking!");
attacking = true;
// anim.SetTrigger("AutoAttack");
chasing = false;
}
else
{
//not currently chasing.
//start chasing if target comes close enough
if (distance <= chaseThreshold) //if he gets to chase, and then you move out of range again, he won't chase again. he will only attack if comes into range again
{
chasing = true;
// attacking = false;
// print("Chasing!");
}
}
}
I think that's all the necessary relevant code.transformmovefollowchaseMon, 04 Jul 2016 12:58:07 GMTn-carlson1Why is my camera shaking when I use my chaser script on something?http://answers.unity.com/questions/1207409/why-is-my-camera-shaking-when-i-use-my-chaser-scri.html
Following is my chaser script.
using UnityEngine;
using System.Collections;
class Chaser_usingTransformClass : MonoBehaviour
{
public Transform target;
Vector3 R, trans;
bool flag = true;
void Start()
{
R = new Vector3(0, 0, 0);
}
void Update()
{
trans = target.position - R;
R = target.position;
gameObject.transform.LookAt(target, Vector3.up);
if (flag)
{
gameObject.transform.Translate(new Vector3(0, 0, 0), Space.World);
flag = false;
}
else
gameObject.transform.Translate(trans, Space.World);
}
}cameracamera-movementlookatcamera followchaseFri, 24 Jun 2016 04:03:39 GMTPrajwal SamalEnemy Car movement towards playerhttp://answers.unity.com/questions/1062949/enemy-car-movement-towards-player.html
using this code.
transform.position = Vector3.SmoothDamp(transform.position, playerTowardMove.transform.position, ref velocity, enemyMoveSpeed);
car object movement well towards player but rotation is not right. what to do?movementcarchaseMon, 07 Sep 2015 11:03:24 GMTMFKJGetting the player to retreat a certain distance from the playerhttp://answers.unity.com/questions/1024117/getting-the-player-to-retreat-a-certain-distance-f.html
Hi all,
This problem has been plaguing me for about 2 weeks now and I cant seem to crack it.
I have a simple state machine for the enemy. The enemy chases the player until the player reaches a light source. Once the player reaches a light source, the enemy retreats. This all works except i want the enemy to stop retreating a certain distance from the player.
At the moment, the enemy is retreating indefinitely until the player leaves the light in which the enemy once again, gives chase.
As you can see in the Retreat function below, I have tried a few methods but none seem to do exactly what I want.
Pastie here or code below: http://pastie.org/private/tjfb3r1xzemmm05dele0wa
Thanks for the help in advance, I really appreciate it.
using UnityEngine;
using System.Collections;
public class DarkChase : MonoBehaviour {
public float maxAdvanceSpeedY = 1.0f;
public float maxAdvanceSpeedX = 1.0f;
public float maxRetreatSpeedY = 1.0f;
public float maxRetreatSpeedX = 1.0f;
public float minDistance = 5.0f;
//public float maxRetreatDistance = 100.0f;
//public float maxDistance = -10.0f;
public GameObject Player;
public GameObject theDark;
public PlayerControl thePlayerScript;
//public Transform Target;
// Use this for initialization
void Start () {
Player = GameObject.FindGameObjectWithTag("Player");
thePlayerScript = thePlayerScript.GetComponent<PlayerControl>();
}
// Update is called once per frame
void Update () {
if (PlayerControl.inLight == false)
Advance();
else if (PlayerControl.inLight == true)
Retreat();
}
public void Advance () {
print ("Advance");
Vector3 playerPosition = Player.transform.position;
Vector3 darkPosition = transform.position;
Vector3 difference = darkPosition - playerPosition;
difference.Normalize();
transform.Translate (
(difference.x * -maxAdvanceSpeedX), (difference.y * -maxAdvanceSpeedY), (difference.z * -1));
}
public void Retreat () {
print ("Retreat");
Vector3 playerPosition = Player.transform.position;
Vector3 darkPosition = transform.position;
Vector3 difference = darkPosition + playerPosition;
difference.Normalize();
transform.Translate (
(difference.x * +maxRetreatSpeedX), (difference.y * +maxRetreatSpeedY), (difference.z * +1));
float dist = Vector3.Distance(playerPosition, darkPosition);
if (Vector3.Distance (playerPosition, darkPosition) <= minDistance)
Debug.DrawLine (playerPosition, darkPosition, Color.yellow);
print ("Distance to player: " + dist);
//darkPosition = Vector2.MoveTowards (transform.position, playerPosition, maxAdvanceSpeedX * Time.deltaTime);
//transform.Translate (
//(maxDistance), (0), (0));
//Vector3 maxDistance = Vector3.Distance (playerPosition, darkPosition);
//if (maxDistance >= maxRetreatDistance)
//.Translate (
//(difference.x - maxRetreatDistance), (difference.y - 0.01), (difference.z - 0.01));
}
}playerenemychaseSat, 08 Aug 2015 12:29:14 GMTjonmeldrumProblem using boids algorithm for chasing enemies.http://answers.unity.com/questions/1008293/problem-using-boids-algorithm-for-chasing-enemies.html
Hello,
I'm making a 2D game where I want the enemies to chase the player (think geometry wars). I don't want them to overlap and stack though. So they need to move away from eachother and chase the player in a smooth way.
While googling I came across flocking and boids. It's exactly what I need (I think). While I kind of understand what's supposed to happen I can only make it kind of work but not really. I'm self taught and may be overlooking some basic stuff. I've been following this explanation and trying to implement it in Unity. (http://www.kfish.org/boids/pseudocode.html).
I've also heard of and looked into UnitySteer (https://github.com/ricardojmendez/UnitySteer). Some of the examples are really cool but it's a bit above my level. I find it hard to understand and even harder to implement in my own project.
So here's the code. I'm using a list of enemies, each enemy has a velocity (that's set to Vector3.zero when they spawn) that contains the amount they need to move every update. (I think I may be doing/using this wrong).
The enemies do kind of move but they keep accelerating and spinning out of control like this. (https://www.youtube.com/watch?v=OYn4zVMD-9M&feature=youtu.be ).
This made me think that the velocity keeps stacking so I tried resetting the velocity to zero every update (and upping the movespeed) which results into this. (https://www.youtube.com/watch?v=mMuyqp1NZcs&feature=youtu.be ). I don't think that's how it's supposed to be since the velocity should get updated and compared to the last one in rule 3. Rule 2 is also not very smooth.
I'm not sure what's going wrong. I've tried singling out each rule but it's hard to find problems because I'm also not entirely sure what it's supposed to look like. Any help or suggestions would be appreciated.
----------
private void Update()
{
MoveEnemies();
}
private void MoveEnemies()
{
Vector3 v1,v2,v3,v4;
for(int i = 0; i < AliveEnemies.Count; i++)
{
EnemyScript e = AliveEnemies[i];
//e.veloc = Vector3.zero;
v1 = rule1(e); //fly towards (percieved) center
v2 = rule2(e); //distance other boids
v3 = rule3(e); //match (percieved) velocity with near boids
v4 = rule4(e); //move towards player
e.veloc = e.veloc + v1 + v2 + v3 +v4;
e.transform.position = e.transform.position + e.veloc*Time.deltaTime;
}
}
private Vector3 rule1(EnemyScript ej)
{
Vector3 percievedCenter = Vector3.zero;
for(int j = 0; j < AliveEnemies.Count; j++)
{
EnemyScript e = AliveEnemies[j];
if(e != ej)
{
percievedCenter = percievedCenter + e.transform.position;
}
}
percievedCenter = percievedCenter / (AliveEnemies.Count-1);
return(percievedCenter - ej.transform.position)/100f;
}
private Vector3 rule2(EnemyScript ej)
{
Vector3 center = Vector3.zero;
for(int j = 0; j < AliveEnemies.Count; j++)
{
EnemyScript e = AliveEnemies[j];
float enemyDistance = Vector3.Distance (ej.transform.position, e.transform.position);
if(e != ej && enemyDistance <= 1f)
{
center = center - (e.transform.position - ej.transform.position);
}
}
return center;
}
private Vector3 rule3(EnemyScript ej)
{
Vector3 percievedVeloc = Vector3.zero;
for(int j = 0; j < AliveEnemies.Count; j++)
{
EnemyScript e = AliveEnemies[j];
if(e != ej)
{
percievedVeloc = percievedVeloc + e.veloc;
}
}
percievedVeloc = percievedVeloc / (AliveEnemies.Count-1);
return (percievedVeloc - ej.veloc)/8f;
}
private Vector3 rule4(EnemyScript ej)
{
if(player != null)
{
Vector3 target = player.transform.position;
return((target - ej.transform.position)/20f);
}
else
{
return(Vector3.zero);
}
}aienemyscriptingbasicsalgorithmchaseThu, 16 Jul 2015 12:56:26 GMTJeffkeuh