For some reason I do not understand, my enemy objects stop moving around whenever the transform reference object moves/rotates. Here is the code on my enemy object:
void FixedUpdate() {
Vector3 playerPosition = player.transform.position;
if (playerPosition.x == 0) {
playerPosition.x += UnityEngine.Random.Range(-1, 1);
}
if (playerPosition.y == 0) {
playerPosition.y += UnityEngine.Random.Range(-1, 1);
}
Vector3 direction = playerPosition - transform.position;
direction = player.transform.InverseTransformDirection(direction);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Vector2 velocity = new Vector2();
velocity.x = Mathf.Cos(angle);
velocity.y = Mathf.Sin(angle);
gameObject.GetComponent<Rigidbody2D>().AddForce(velocity * moveSpeed);
}
Any help is appreciated.
While it did not solve my problem exactly, I figure out a solution using the following:
void FixedUpdate() {
Vector3 playerPosition = player.transform.position;
if (playerPosition.x == 0) {
playerPosition.x += UnityEngine.Random.Range(-1, 1);
}
if (playerPosition.y == 0) {
playerPosition.y += UnityEngine.Random.Range(-1, 1);
}
Vector3 direction = playerPosition - transform.position;
float angleRad = Mathf.Atan2(direction.y, direction.x);
Vector2 jiggleAmount = new Vector2(UnityEngine.Random.Range(-1000.0F, 1000.0F), UnityEngine.Random.Range(-1000.0F, 1000.0F));
float jiggleDistance = UnityEngine.Random.Range(0.5F, 2.0F);
float speedRandomOffset = UnityEngine.Random.Range(0.5F, 2.0F);
float newMoveSpeed = moveSpeed * speedRandomOffset;
float angleRadJiggle = Mathf.Atan2(jiggleAmount.x, jiggleAmount.y);
Vector2 velocity = new Vector2();
velocity.x = Mathf.Cos(angleRad) + (Mathf.Cos(angleRadJiggle) * jiggleDistance);
velocity.y = Mathf.Sin(angleRad) + (Mathf.Sin(angleRadJiggle) * jiggleDistance);
gameObject.GetComponent<Rigidbody2D>().AddForce(velocity * newMoveSpeed);
}