2016-06-11 14:36:00 weixin_30251587 阅读数 10
  • Unity 值得看的500+ 技术内容列表

    Unity3D是由Unity Technologies开发的一个让玩家轻松创建诸如三维视频游戏、建筑可视化、实时三维动画等类型互动内容的多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

看过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);
    }
}

 

转载于:https://www.cnblogs.com/heartgame/p/5575303.html

没有更多推荐了,返回首页