官术网_书友最值得收藏!

Wandering around

This technique works like a charm for random crowd simulations, animals, and almost any kind of NPC that requires random movement when idle.

Getting ready

We need to add another function to our AgentBehaviour class called OriToVec that converts an orientation value to a vector.

public Vector3 GetOriAsVec (float orientation) {
    Vector3 vector  = Vector3.zero;
    vector.x = Mathf.Sin(orientation * Mathf.Deg2Rad) * 1.0f;
    vector.z = Mathf.Cos(orientation * Mathf.Deg2Rad) * 1.0f;
    return vector.normalized;
}

How to do it...

We could see it as a big three-step process in which we manipulate the internal target position in a parameterized random way, face that position, and move accordingly:

  1. Create the Wander class deriving from Face:
    using UnityEngine;
    using System.Collections;
    
    public class Wander : Face
    {
        public float offset;
        public float radius;
        public float rate;
    }
  2. Define the Awake function in order to set up the internal target:
    public override void Awake()
    {
        target = new GameObject();
        target.transform.position = transform.position;
        base.Awake();
    }
  3. Define the GetSteering function:
    public override Steering GetSteering()
    {
        Steering steering = new Steering();
        float wanderOrientation = Random.Range(-1.0f, 1.0f) * rate;
        float targetOrientation = wanderOrientation + agent.orientation;
        Vector3 orientationVec = OriToVec(agent.orientation);
        Vector3 targetPosition = (offset * orientationVec) + transform.position;
        targetPosition = targetPosition + (OriToVec(targetOrientation) * radius);
        targetAux.transform.position = targetPosition;
        steering = base.GetSteering();
        steering.linear = targetAux.transform.position - transform.position;
        steering.linear.Normalize();
        steering.linear *= agent.maxAccel;
        return steering;
    }

How it works...

The behavior takes into consideration two radii in order to get a random position to go to next, looks towards that random point, and converts the computed orientation into a direction vector in order to advance.

How it works...

A visual description of the parameters for creating the Wander behavior

主站蜘蛛池模板: 泗洪县| 田东县| 大邑县| 包头市| 昂仁县| 穆棱市| 阿坝县| 筠连县| 金山区| 安仁县| 壤塘县| 赤城县| 格尔木市| 昌江| 海阳市| 洛宁县| 饶平县| 双江| 象州县| 彩票| 方正县| 静宁县| 玛曲县| 札达县| 平度市| 拜城县| 平阴县| 依兰县| 侯马市| 静海县| 麻阳| 土默特右旗| 郎溪县| 米泉市| 右玉县| 德清县| 繁峙县| 出国| 莱芜市| 温州市| 辽源市|