- 最后登录
- 2016-8-29
- 注册时间
- 2012-8-25
- 阅读权限
- 90
- 积分
- 23585
- 纳金币
- 20645
- 精华
- 62
|
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;
}
|
|