Question by
pasharafeeq007 · Aug 08, 2018 at 08:16 AM ·
enemymovement script
Hi guys, I am trying to make my enemy to chess the player when he enter in to danger zone. But the enemy is not chasing the player when he enter in to dangerzone. Please help me ..Thank you....
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemyMovementController : MonoBehaviour {
public float enemySpeed;
Animator enemyAnimator;
//facing
public GameObject enemyGraphic;
bool canFlip = true;
bool facingRight = false;
float flipTime = 5f;
float nextFlipChance = 0f;
//attacking
public float chargeTime;
float startChargeTime;
bool charging;
Rigidbody2D enemyRB;
// Use this for initialization
void Start () {
enemyAnimator = GetComponentInChildren<Animator> ();
enemyRB = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
if (Time.time > nextFlipChance) {
if (Random.Range (0, 10) >= 5)
flipFacing ();
nextFlipChance = Time.time + flipTime;
}
}
void OnTriggerEnter2D(Collider2D other){
if (other.tag == "Player"){
if (facingRight && other.transform.position.x < transform.position.x) {
flipFacing ();
} else if (!facingRight && other.transform.position.x > transform.position.x) {
flipFacing ();
}
canFlip = false;
charging = true;
startChargeTime = Time.time + chargeTime;
}
}
void OntriggerStay2D(Collider2D other){
if (other.tag == "Player") {
if (startChargeTime < Time.time) {
if (!facingRight)
enemyRB.AddForce (new Vector2(-1, 0) * enemySpeed);
else
enemyRB.AddForce (new Vector2(1, 0) * enemySpeed);
enemyAnimator.SetBool ("isCharging", charging);
}
}
}
void OnTriggerExit2D (Collider2D other ) {
if (other.tag == "Player"){
canFlip = true;
charging = false;
enemyRB.velocity = new Vector2(0f, 0f);
enemyAnimator.SetBool ("isCharging", charging);
}
}
void flipFacing() {
if (!canFlip) return;
float facingX = enemyGraphic.transform.localScale.x;
facingX *= -1f;
enemyGraphic.transform.localScale = new Vector3( facingX, enemyGraphic.transform.localScale.y, enemyGraphic.transform.localScale.z);
facingRight =! facingRight;
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612172424im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Make circular moving object stay within a specific area 1 Answer
How to make enemy detect a character in his certain range? 1 Answer
Trying to make a cube move up a set amount 0 Answers
Object don't move towards. 0 Answers
How do I get my object to move towards the mouse without using raycasts or transform? 1 Answer