ok, so im working on a basic 2d AI script. The enemies are to simple home in on the player. however they dont go straight there, but have a steering limit... basically they have to actually turn around instead of doing an instant 180. however i keep getting really weird behavior and would appreciate any help.
void Update () {
//find direction to player
direction = Vector3.Normalize(player.transform.position - this.transform.position);
float rot_z = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
target.transform.Rotate(0, 0, rot_z - 90f);
//determine left or right
if (Mathf.Abs(target.transform.rotation.eulerAngles.z - transform.rotation.eulerAngles.z) < 179) {
left = true;
}
else { left = false; }
/*if (Mathf.Abs(target.transform.rotation.eulerAngles.z - transform.rotation.eulerAngles.z) < turnSpeed) {
turnSpeed = 0;
}*/
if (!left) {
turnSpeed += turnAccel;
}
else if (left) {
turnSpeed -= turnAccel;
}
if (turnSpeed > turnAccelMax) { turnSpeed = turnAccelMax; }
if (turnSpeed < -turnAccelMax) { turnSpeed = -turnAccelMax; }
speed += speedAccel;
speed -= Mathf.Abs(turnSpeed);
if (speed <= 0) { speed = 0; }
if (speed > speedMax) { speed = speedMax; }
//target.transform.position = transform.position;
//target.transform.rotation = transform.rotation;
//target.transform.Rotate(0, 0, -turnSpeed);
target.transform.RotateAround(transform.position, Vector3.forward, turnSpeed);
target.transform.Translate(new Vector3(direction.x * speed * drag, direction.y * speed * drag, 0), Space.Self);
// currently target does not rotate correctly
rigidbody.MovePosition(new Vector3(target.transform.position.x, target.transform.position.y, 0));
transform.Rotate(0,0,-turnSpeed);
}
↧