Question by
rizkijsj · Oct 01, 2016 at 06:54 AM ·
ai2d-platformerfollow player
Help with 2D AI scripting
This script should work as the player enter the range of enemy then the enemy will charge/move towards the player ... but the enemy are sit still and not moving .. can anybody fix or point out my script ?
public float enemySpeed;
//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;
void Start (){
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);
}
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Player")
{
canFlip = true;
charging = false;
enemyRB.velocity = new Vector2(0f, 0f);
}
}
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