This question was
closed Oct 28, 2015 at 10:58 AM by
lengzai96 for the following reason:
Other
Charging Enemy behaviour?
So basically I'm trying to make an enemy that chargers at you and it if detects a change in your x direction he's supposed to pause and recalculate the direction you're in and charge that way instead.
here's my code:
using UnityEngine;
using System.Collections;
public class ChargingEnemyAI : MonoBehaviour {
public GameObject Player;
public float Velocity = 0;
public Vector3 movement;
bool isCharging = false;
bool ischargeLeft = false;
bool ischargeRight = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Charge();
}
public void Charge()
{
if(isCharging == false)
{
if(Velocity >= 1)
{
Velocity -= 1;
}
else
{
Velocity = 0;
}
Invoke("CalculateDirection",2);
}
else
{
if (ischargeLeft)
{
if (Player.transform.position.x > this.transform.position.x || Player.transform.position.x == this.transform.position.x)
{
isCharging = false;
}
else
{
Velocity += 1;
movement.x = -0.5f * Velocity;
movement.y = this.transform.position.y;
movement.z = this.transform.position.z;
this.transform.position = movement;
}
}
else if (ischargeRight)
{
if (Player.transform.position.x < this.transform.position.x || Player.transform.position.x == this.transform.position.x)
{
isCharging = false;
}
else
{
Velocity += 1;
movement.x = 0.5f * Velocity;
movement.y = this.transform.position.y;
movement.z = this.transform.position.z;
this.transform.position = movement;
}
}
}
}
public void CalculateDirection()
{
if (Player.transform.position.x < this.transform.position.x)
{
ischargeLeft = true;
ischargeRight = false;
isCharging = true;
}
else if (Player.transform.position.x > this.transform.position.x)
{
ischargeRight = true;
ischargeLeft = false;
isCharging = true;
}
}
}
Using this, the enemy seems to go towards my player and then start flickering left and right. Can anyone tell me what's wrong with my code?
Comment
I see this post is really old, but do you still need a reply? Or if you already sorted it out, could you post your solution here?