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

Posted 水榭阁主

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity3d angrybots学习之敌人围绕主角旋转和移动相关的知识,希望对你有一定的参考价值。

看过angrybots例子的人都知道,敌人有可能是飞行器,有可能是机器人,这里我们假定他是飞行器,ok,我们首先设定飞行器是rigidbody,然后固定的y的postion,和x,z的rotation,写下如下的代码

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) {
            rigidbody.AddForce(deltaVelocity, ForceMode.Force);
        }
        else //反之,两个对象该远离了
        {
            rigidbody.AddForce(-deltaVelocity * backtrackIntensity, ForceMode.Force);
            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);
    }
}

 

以上是关于unity3d angrybots学习之敌人围绕主角旋转和移动的主要内容,如果未能解决你的问题,请参考以下文章

uboot学习之二----主Makefile学习之四----两种编译方法:原地编译和单独输出文件夹编译

uboot学习之二----主Makefile学习之二----环境变量之:主机的操作系统和主机架构(HOSTOSHOSTARCH)(31-43行)

机器学习之PCA主成分分析

UnityEditor研究学习之自定义Editor

机器学习之主成分分析(手推公式版)

机器学习之主成分分析