纳金网

标题: 几种控制角色运动的方法--寻找,逃离,跟随一定距离 [打印本页]

作者: 王者再临    时间: 2014-10-18 03:29
标题: 几种控制角色运动的方法--寻找,逃离,跟随一定距离

1.控制朝向transform.LookAt(target.transform);

2.实现跟随,逐渐靠近
GameObject player;
float MAX_MOVE_DISTANCE=500.0f;

void FixedUpdate()
{
     float moveDistance=MAX_MOVE_DISTANCE*Time.deltaTime;
     Vector3 source=transform.position;
     Vector3 target=player.transform.position;
     Vector3 seekVelocity=Seek(source,target,moveDistance);
    seekVelocity=UsefulFunctions.ClampMagnitude(seekVelocity,moveDistance);
     rigidbody.AddForce(seekVelocity,ForceMode.VelocityChange)
}

Vector3 Seek(Vector3 source,Vector3 target,float moveDistance)
{
        Vector3 directionToTarget=Vector3.Normalize(target-source);
        Vector3  VelocityToTarget=moveDistance*directionToTarget;
        transform.LookAt(player.transform);
        return velocityToTarget-rigidbody.velocity;  //注意,这里是向量相减
}

3.对2进行优化,提供一个更简单的方法
Transform player;
float speed=5.0f;

void Update()
{
        transform.LookAt(player);
        float distance=speed*Time.deltaTime;
        Vector3 source=transform.position;
        Vector3 target=player.position;
        transform.position=Vector3.MoveTowards(source,target,distance);
}

4.实现接近目标时通过减速改善到达行为
将2中的Seek替换如下:
float DECELERATION_FACTOR=0.6f;

Vector3 Arrive(Vector3 source,Vector3 target)
{
       float distanceToTarget=Vector3.Distance(source,target);
       Vector3 directionToTarget=Vector3.Normalize(target-source);
        float speed=distanceToTarget/DECELERATION_FACTOR;
        Vector3 velocityToTarget=speed*directionToTarget;
        return velocityToTarget-rigidbody.velocity;
}


5.实现和目标之间保持一定的距离

float DECELERATION_FACTOR=0.6f;
float FLEE_RADIUS=14f;
float SEEK_RADIUS=6f;

Vector3 adjustVelocity=Vector3.zero;
float distanceToTarget=Vector3.Distance(target,source);
if(distanceToTarget<FLEE_RADIUS)
   adjustVelocity+=Flee(source,target);
if(distanceToTarget>SEEK_RADIUS)
   adjustVelocity+=Arrive(source,target);  //这个是用上面的函数


private Vector3 Flee(Vector3 source, Vector3 target)
{
        float distanceToTarget=Vector3.Distance(target,source);
        Vector3 directionAwayFromTarget=Vector3.Normalize(source-target);
        float speed=(FLEE_RADIUS-distanceToTarget)/DECELERATION_FACTOR;
        Vector3 velocityAwayFromTarget=speed*directionAwayFromTarget;
        return velocityAwayFromTarget;
}


作者: hyui    时间: 2014-10-18 03:54
Thakns for this one !
作者: kaifly8888    时间: 2014-10-19 08:46
不错的分享
作者: cgjch8    时间: 2014-10-19 12:18
谢谢楼主




欢迎光临 纳金网 (http://old.narkii.com/club/) Powered by Discuz! X2.5