# unity3d angrybots学习之敌人围绕主角旋转和移动

using UnityEngine;
using System.Collections;

public class BuzzeMove : MonoBehaviour {

private Transform player;//目标，target
private Rigidbody rigidbody;
public float flyingSpeed = 5.0f;//飞行速度
public float zigZagSpeed = 2.5f; //设置一个左右的速度
private Vector3 smootheDirection = Vector3.zero;//使移动更平滑
private float backtrackIntensity = 0.5f;
public float oriantationMultiplier = 2.5f;//旋转系数
// Use this for initialization
void Awake () {
player = GameObject.FindGameObjectWithTag("Player").transform;
rigidbody = GetComponent<Rigidbody>();
}

// Update is called once per frame
void FixedUpdate () {
Vector3 direction = player.position - transform.position;
direction.Normalize();//方向归一化
smootheDirection = Vector3.Lerp(smootheDirection,direction,Time.deltaTime*3.0f);//差值使得运动平滑
Vector3 zigzag = transform.right*(Mathf.PingPong(Time.time*zigZagSpeed, 2.0f) - 1.0f) * zigZagSpeed;//给左右加点偏移
float orientationSpeed = 1.0f;
Vector3 deltaVelocity = (smootheDirection*flyingSpeed + zigzag) - rigidbody.velocity;
//如果Vector3.Dot两个值大于0，那么两个对象是面对面的
if (Vector3.Dot(direction, transform.forward) > 0.8f) {
}
else //反之，两个对象该远离了
{
orientationSpeed = oriantationMultiplier;//反方向的时候旋转得快一些
}

float rotationAngle = AngleAroundAxis(transform.forward,direction,Vector3.up);
rigidbody.angularVelocity = Vector3.up * rotationAngle* oriantationMultiplier;//刚体的旋转
//transform.LookAt(player, Vector3.up);
}

// The angle between dirA and dirB around axis
static float AngleAroundAxis(Vector3 dirA,  Vector3 dirB,  Vector3 axis)
{
// Project A and B onto the plane orthogonal target axis
dirA = dirA - Vector3.Project(dirA, axis);
dirB = dirB - Vector3.Project(dirB, axis);

// Find (positive) angle between A and B
float angle = Vector3.Angle(dirA, dirB);

// Return angle multiplied with 1 or -1
return angle * (Vector3.Dot(axis, Vector3.Cross(dirA, dirB)) < 0 ? -1 : 1);
}
}

posted on 2016-06-11 14:36  水榭阁主  阅读(585)  评论(0编辑  收藏  举报