Пример #1
0
    protected override Vector3 getTargetPosition()
    {
        float targetDistance = (character.transform.position - target.transform.position).magnitude;
        float currSpeed      = character.linearVelocity.magnitude;

        float currPredictionTime;

        if (currSpeed <= targetDistance / maxTimeToPredict)
        {
            currPredictionTime = maxTimeToPredict;
        }
        else
        {
            currPredictionTime = targetDistance / currSpeed;
        }

        Kinematic movingTarget = target.GetComponent <Kinematic>();

        if (movingTarget == null)
        {
            return(base.getTargetPosition());
        }

        return((movingTarget.linearVelocity * currPredictionTime) - target.transform.position);
    }
Пример #2
0
 public MoveKinematicToObject(Kinematic mover, GameObject target, TextMesh text)
 {
     movie    = mover;
     leTarget = target;
     leText   = text;
     anim     = movie.GetComponent <Animator>();
 }
    protected override Vector3 getTargetPosition()
    {
        Vector3 directionToTarget = target.transform.position - character.transform.position;
        float   distanceToTarget  = directionToTarget.magnitude;
        float   mySpeed           = character.linear.magnitude;
        float   predictionTime;

        if (mySpeed <= distanceToTarget / maxPredictionTime)
        {
            predictionTime = maxPredictionTime;
        }
        else
        {
            predictionTime = distanceToTarget / mySpeed;
        }

        Kinematic myMovingTarget = target.GetComponent(typeof(Kinematic)) as Kinematic;

        if (myMovingTarget == null)
        {
            return(base.getTargetPosition());
        }

        return(target.transform.position + myMovingTarget.linear * predictionTime);
    }
Пример #4
0
    /// <summary>
    /// Draws the path of the shoot from source object current position to
    /// target object current position.
    /// </summary>
    /// <param name="source">Source.</param>
    /// <param name="target">Target.</param>
    /// <param name="gravity">Gravity.</param>
    /// <param name="delta_h">The maximum height of the shoot starting from
    /// target y postion.</param>
    public static void DrawPath(Transform source, Transform target,
                                float gravity, float delta_h)
    {
        ShootData shootData = Kinematic.CalculateShoot(source,
                                                       target,
                                                       gravity,
                                                       delta_h);
        Vector3 previousDrawPoint = source.position;

        int resolution = 30;

        for (int i = 1; i <= resolution; i++)
        {
            float   simulationTime = (i / (float)resolution) * shootData.timeToTarget;
            Vector3 displacement   = shootData.initialVelocity * simulationTime
                                     + Vector3.up * gravity
                                     * simulationTime * simulationTime /
                                     2f;
            Vector3 drawPoint = source.position + displacement;

            // TODO Find a way to draw trajectory not only in debug mode (to be
            //      able to visualizing it in the actual scene, not only in Scene tab)
            Debug.DrawLine(previousDrawPoint, drawPoint, Color.green);
            previousDrawPoint = drawPoint;
        }
    }
Пример #5
0
    //Code based on AI for Games 3rd Edition, p. 83
    public override SteeringOutput getSteering(Kinematic selfKinematic, GameObject target = null, Kinematic targetKinematic = null)
    {
        if (targets.Length == 0)
        {
            return(null);
        }

        result.angular = 0;
        result.linear  = Vector3.zero;

        foreach (GameObject t in targets)
        {
            Vector3 direction = selfKinematic.position - t.transform.position;
            //project onto plane
            direction.y = 0;
            float distanceSquared = direction.sqrMagnitude;

            if (distanceSquared < thresholdSquared)
            {
                float strength = Mathf.Min(decayCoefficient / distanceSquared, selfKinematic.maxAcceleration);
                direction.Normalize();
                result.linear += strength * direction * weight;
            }
        }
        return(result);
    }
Пример #6
0
    //private float currentAcceleration = 0f;
    //private float maxAcceleration = 0f;

    public Seek(Kinematic thisCharacter, ref GameObject target, ref SteeringOutput currentDirection, ref float currentAccel, ref float maxAccel, int choice)
    {
        this.character   = thisCharacter;
        this.target      = target;
        currentAccel     = maxAccel;
        currentDirection = this.getSteering(choice);
    }
Пример #7
0
    public static Steering getSteering(float maxAcceleration, float maxSpeed, float targetRadius, float slowRadius,
        float predictionTime, Kinematic character, Kinematic target)
    {
        Steering steering = new Steering();

        Vector3 direction = target.position - character.position;
        float distance = direction.magnitude;

        if (distance < targetRadius)
        {
            steering.linear = Vector3.zero;
            steering.angular = 0.0f;
            return steering;
        }            

        float targetSpeed;
        if (distance > slowRadius)
            targetSpeed = maxSpeed;
        else
            targetSpeed = maxSpeed * distance / slowRadius;

        Vector3 targetVelocity = direction.normalized * targetSpeed;

        steering.linear = (targetVelocity - character.velocity) / predictionTime;

        if (steering.linear.magnitude > maxAcceleration)
            steering.linear = steering.linear.normalized * maxAcceleration;

        steering.angular = 0.0f;

        return steering;
    }
Пример #8
0
    protected override Vector3 getTargetPosition()
    {
        // distance to target
        Vector3 direction = target.transform.position - character.transform.position;
        float   distance  = direction.magnitude;

        // get speed of character
        float speed = character.linearVelocity.magnitude;

        // check if speed gives reasonable prediction time
        float prediction;

        if (speed <= distance / maxPrediction)
        {
            prediction = maxPrediction;
        }
        else
        {
            prediction = distance / speed;
        }

        Kinematic movingTarget = target.GetComponent <Kinematic>();

        if (movingTarget == null)
        {
            return(base.getTargetPosition());
        }

        base.flee = true;
        return(target.transform.position + movingTarget.linearVelocity * prediction);
    }
    void Start()
    {
        slotAs   = formation.getSlotByNumber(slot);
        objetivo = new GameObject(); //Creo el objetivo
        objetivo.AddComponent <Kinematic>();

        kinetic = objetivo.GetComponent <Kinematic>();
    }
Пример #10
0
 void Start()
 {
     char_RigidBody  = GetComponent <Kinematic>();
     arrive          = GetComponent <DynoArrive>();
     align           = GetComponent <DynoAlign>();
     kinematicArrive = GetComponent <KinematicArrive>();
     isWandering     = true;
 }
Пример #11
0
    void Start()
    {
        objetivo = new GameObject(); //Creo el objetivo
        objetivo.AddComponent <Kinematic>();

        kinetic           = objetivo.GetComponent <Kinematic>();
        collisionDetector = new CollisionDetector();
    }
Пример #12
0
    void Start()
    {
        objetivo = new GameObject(); //Creo el objetivo
        objetivo.AddComponent <Kinematic>();

        kinetic    = objetivo.GetComponent <Kinematic>();
        wanderRate = wanderRate * Mathf.Deg2Rad;  //Máxima Orientacion
    }
Пример #13
0
 public void init()
 {
     myKinematic             = new Kinematic();
     myKinematic.Position    = this.transform.position;
     myKinematic.Velocity    = new Vector3(0f, 0f, 0f);
     myKinematic.Rotation    = 0f;
     myKinematic.Orientation = 0f;
 }
Пример #14
0
 public KinematicArrive(Kinematic character, Kinematic target, float maxSpeed, float satisfactionRadius, float timeToTarget)
 {
     this.character          = character;
     this.target             = target;
     this.maxSpeed           = maxSpeed;
     this.satisfactionRadius = satisfactionRadius;
     this.timeToTarget       = timeToTarget;
 }
Пример #15
0
    // Use this for initialization
    void Start()
    {
        char_kinematic = GetComponent <Kinematic>();
        seek           = GetComponent <KinematicSeek>();
        arrive         = GetComponent <KinematicArrive>();

        wander = GetComponent <Wander>();
    }
    public override SteeringOutput getSteering()
    {
        float shortestTime = float.PositiveInfinity;

        Kinematic firstTarget        = null;
        float     firstMinSeparation = 0f;;
        float     firstDistance      = 0f;
        Vector3   firstRelativePos   = new Vector3(0, 0, 0);
        Vector3   firstRelativeVel   = new Vector3(0, 0, 0);
        Vector3   relativePos;
        Vector3   relativeVel;

        foreach (Kinematic target in targets)
        {
            relativePos = target.transform.position - character.transform.position;
            relativeVel = target.linear - character.linear;
            float relativeSpeed   = relativeVel.magnitude;
            float timeToCollision = Vector3.Dot(relativePos, relativeVel) / (relativeSpeed * relativeSpeed);

            float distance      = relativePos.magnitude;
            float minSeparation = distance - relativeSpeed * timeToCollision;
            if (minSeparation > 2 * radius)
            {
                continue;
            }

            if (timeToCollision > 0 && timeToCollision < shortestTime)
            {
                shortestTime     = timeToCollision;
                firstTarget      = target;
                firstDistance    = distance;
                firstRelativePos = relativePos;
                firstRelativeVel = relativeVel;
            }
        }
        if (!firstTarget)
        {
            return(null);
        }

        SteeringOutput result = new SteeringOutput();


        float dotResult = Vector3.Dot(character.linear.normalized, firstTarget.linear.normalized);

        if (dotResult < -0.9 && dotResult > -1.1)
        {
            result.linear = -firstTarget.transform.right;
        }
        else
        {
            result.linear = -firstTarget.linear;
        }
        result.linear.Normalize();
        result.linear *= maxAcceleration;
        result.angular = 0;
        return(result);
    }
Пример #17
0
    private void Start()
    {
        kinematic = GetComponent <Kinematic>();

        switch (moveType)
        {
        case SteeringType.Pursue:
            pursueAI           = new Pursue();
            pursueAI.character = kinematic;
            pursueAI.target    = target;
            break;

        case SteeringType.Evade:
            evadeAI           = new Evade();
            evadeAI.character = kinematic;
            evadeAI.target    = target;
            break;

        case SteeringType.FollowPath:
            followAI           = new PathFollow();
            followAI.character = kinematic;
            followAI.path      = pathOfObjects;
            break;

        case SteeringType.Seek:
            seekAI           = new Seek();
            seekAI.character = kinematic;
            seekAI.target    = target;
            break;

        case SteeringType.Flee:
            fleeAI           = new Flee();
            fleeAI.character = kinematic;
            fleeAI.target    = target;
            break;

        case SteeringType.Seperation:
            seperationAI           = new Seperation();
            seperationAI.character = kinematic;
            seperationAI.targets   = seperateObstacles;
            break;

        case SteeringType.Arrive:
            arriveAI           = new Arrive();
            arriveAI.character = kinematic;
            arriveAI.target    = target;
            break;
        }

        switch (lookType)
        {
        case LookType.Align:
            alignAI           = new Align();
            alignAI.character = kinematic;
            alignAI.target    = target;
            break;
        }
    }
Пример #18
0
    // Define Output
    override public Steering Output(Kinematic target)
    {
        // Ignore Boid layer
        int layermask = ~(1 << 9);

        // Set up forward ray
        RaycastHit2D hit1 = Physics2D.Raycast(player.data.position, player.data.velocity, lookahead, layermask);

        Debug.DrawRay(player.data.position, player.data.velocity.normalized * (lookahead), Color.black);

        // Set up right ray
        Vector2      direction = player.data.velocity - Vector2.Perpendicular(player.data.velocity) * 0.7f;
        RaycastHit2D hit2      = Physics2D.Raycast(player.data.position, direction, lookahead, layermask);

        Debug.DrawRay(player.data.position, direction.normalized * (lookahead), Color.black);

        // Set up left ray
        direction = player.data.velocity + Vector2.Perpendicular(player.data.velocity) * 0.7f;
        RaycastHit2D hit3 = Physics2D.Raycast(player.data.position, direction, lookahead, layermask);

        Debug.DrawRay(player.data.position, direction.normalized * (lookahead), Color.black);

        if (active && hit1.collider == null && hit2.collider && hit3.collider)
        {
            if (manager.GetComponent <ScalableManager>())
            {
                manager.GetComponent <ScalableManager>().TunnelOn();
                GetComponent <MultiBehavior>().ai[1] = GetComponent <RayCastRemove>();
            }
            else if (manager.GetComponent <EmergentManager>())
            {
                manager.GetComponent <EmergentManager>().TunnelOn();
                GetComponent <NPCController>().ai = GetComponent <RayCastPath>();
            }
            else if (manager.GetComponent <TwoLevelManager>())
            {
                manager.GetComponent <TwoLevelManager>().TunnelOn();
                manager.GetComponent <TwoLevelManager>().spacing = 1;
                manager.GetComponent <TwoLevelManager>().SetFollowers();
                GetComponent <NPCController>().ai = GetComponent <PathFollow>();
            }
        }
        if (!inTunnel && hit1.collider == null && hit2.collider && hit3.collider)
        {
            inTunnel = true;
        }
        if (inTunnel && hit2.collider == null && hit3.collider == null)
        {
            GetComponent <MultiBehavior>().ai[0]      = GetComponent <Arrive>();
            GetComponent <MultiBehavior>().ai[1]      = GetComponent <Align>();
            GetComponent <NPCController>().maxSpeedL *= 2;
            if (GetComponent <MultiBehavior>().weights.Length == 4)
            {
                GetComponent <MultiBehavior>().weights[3] = 1;
            }
        }
        return(new Steering());
    }
Пример #19
0
    public DynamicEvade(Kinematic _character, Kinematic _target, float _maxAcceleration, float _maxPrediction)
    {
        character       = _character;
        target          = _target;
        maxAcceleration = _maxAcceleration;
        maxPrediction   = _maxPrediction;

        df = new DynamicFlee(_character, _target, _maxAcceleration);
    }
Пример #20
0
 // Use this for initialization
 void Start()
 {
     char_RigidBody = GetComponent <Kinematic>();
     //seek = GetComponent<DynoSeek>();
     arrive = GetComponent <DynoArrive>();
     wander = GetComponent <DynoWander>();
     align  = GetComponent <DynoAlign>();
     face   = GetComponent <DynoFace>();
 }
Пример #21
0
    public DynamicPursue(Kinematic _character, Kinematic _target, float _maxAcceleration, float _maxPrediction)
    {
        character       = _character;
        target          = _target;
        maxAcceleration = _maxAcceleration;
        maxPrediction   = _maxPrediction;

        ds = new DynamicSeek(_character, _target, _maxAcceleration);
    }
Пример #22
0
    // Use this for initialization
    void Start()
    {
        Kinematic = GetComponent <Kinematic>();

        if (!File.Exists(path))
        {
            sw = File.CreateText(path);
        }
    }
Пример #23
0
    public SteeringOutput getSteering()
    {
        SteeringOutput steering     = new SteeringOutput();
        float          shortestTime = Mathf.Infinity;

        Kinematic firstTarget        = new Kinematic();
        bool      setFirstTarget     = false;
        float     firstMinSeparation = 0;
        float     firstDistance      = 0;
        Vector3   firstRelativePos   = Vector3.zero;
        Vector3   firstRelativeVel   = Vector3.zero;
        float     distance           = 0;

        Vector3 relativePos = Vector3.zero;

        foreach (NPCController target in targets)
        {
            relativePos = target.position - character.position;
            Vector3 relativeVel     = target.k.velocity - character.velocity;
            float   relativeSpeed   = relativeVel.magnitude;
            float   timeToCollision = (Vector3.Dot(relativePos, relativeVel)) / (relativeSpeed * relativeSpeed);
            distance = relativePos.magnitude;
            float minSeperation = distance - (relativeSpeed * shortestTime);
            if (minSeperation > radius)
            {
                continue;
            }
            if (timeToCollision > 0 && timeToCollision < shortestTime)
            {
                shortestTime       = timeToCollision;
                firstTarget        = target.k;
                setFirstTarget     = true;
                firstMinSeparation = minSeperation;
                firstDistance      = distance;
                firstRelativePos   = relativePos;
                firstRelativeVel   = relativeVel;
            }
        }

        if (!setFirstTarget)
        {
            return(new SteeringOutput());
        }
        if (firstMinSeparation <= 0 || distance < 2 * radius)
        {
            relativePos = firstTarget.position - character.position;
        }
        else
        {
            relativePos = firstRelativePos + firstRelativeVel * shortestTime;
        }

        relativePos.Normalize();
        steering.linear = relativePos * maxAcceleration;
        return(steering);
    }
Пример #24
0
    // Start is called before the first frame update
    void Start()
    {
        self      = GetComponent <Kinematic>();
        tank      = GetComponent <Tank>();
        mEffector = GetComponent <MovementEffector>();
        dTree     = new CheckShieldOnDecision();

        ((Decision)dTree).testData = mEffector.ShieldStatus;
        ((CheckShieldOnDecision)dTree).trueNode = new ShotApproachingDecision();                                                                                                                                      // Shield is on. Is a shot approaching? (Should we leave it on?)

        ((ShotApproachingDecision)((CheckShieldOnDecision)dTree).trueNode).trueNode = new IsGunReadyDecision();                                                                                                       // A shot is coming, leave the shield alone. Can we return fire?
        ((IsGunReadyDecision)(((ShotApproachingDecision)((CheckShieldOnDecision)dTree).trueNode).trueNode)).trueNode = new FacingEnemyDecision();                                                                     // Are we facing the enemy?
        ((FacingEnemyDecision)(((IsGunReadyDecision)(((ShotApproachingDecision)((CheckShieldOnDecision)dTree).trueNode).trueNode)).trueNode)).trueNode  = new ShootGunAction();                                       // Shoot!
        ((FacingEnemyDecision)(((IsGunReadyDecision)(((ShotApproachingDecision)((CheckShieldOnDecision)dTree).trueNode).trueNode)).trueNode)).falseNode = new Action();                                               // Not facing the enemy. Do nothing new.
        ((IsGunReadyDecision)(((ShotApproachingDecision)((CheckShieldOnDecision)dTree).trueNode).trueNode)).falseNode = new Action();                                                                                 // We can't return fire. Do nothing new.

        ((ShotApproachingDecision)((CheckShieldOnDecision)dTree).trueNode).falseNode = new ShieldOffAction();                                                                                                         // Turn the shield off to conserve power. We don't need it right now.

        ((CheckShieldOnDecision)dTree).falseNode = new CanEnableShieldDecision();                                                                                                                                     // Shield is off. Can we have the shield on?

        ((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).trueNode = new ShotApproachingDecision();                                                                                                 // Is there a shot approaching the tank? SHOULD we turn it on?
        ((ShotApproachingDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).trueNode)).trueNode  = new ShieldOnAction();                                                                   // Turn the shield on
        ((ShotApproachingDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).trueNode)).falseNode = new IsGunReadyDecision();                                                               // Don't turn the shield on, but is the gun ready?
        (((IsGunReadyDecision)((ShotApproachingDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).trueNode)).falseNode)).trueNode = new FacingEnemyDecision();                             // Are we facing the enemy?
        ((FacingEnemyDecision)(((IsGunReadyDecision)((ShotApproachingDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).trueNode)).falseNode)).trueNode).trueNode  = new ShootGunAction(); // Shoot!
        ((FacingEnemyDecision)(((IsGunReadyDecision)((ShotApproachingDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).trueNode)).falseNode)).trueNode).falseNode = new Action();         // Do nothing new
        (((IsGunReadyDecision)((ShotApproachingDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).trueNode)).falseNode)).falseNode = new Action();                                         // Do nothing new


        ((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).falseNode = new IsGunReadyDecision();                                                                   // Can't turn shield on. But, can we shoot?
        ((IsGunReadyDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).falseNode)).trueNode = new FacingEnemyDecision();                                 // Are we facing the enemy?
        (((FacingEnemyDecision)(((IsGunReadyDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).falseNode)).trueNode))).trueNode  = new ShootGunAction(); // Are we facing the enemy?
        (((FacingEnemyDecision)(((IsGunReadyDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).falseNode)).trueNode))).falseNode = new Action();         // Don't do anything new

        ((IsGunReadyDecision)(((CanEnableShieldDecision)((CheckShieldOnDecision)dTree).falseNode).falseNode)).falseNode = new Action();                                             // Do nothing new.



        List <State> states = new List <State>();

        State fightState = new FightState();

        fightState.GetTransitions().Add(new Transition());
        states.Add(fightState);

        State fleeState = new FleeState();

        fleeState.GetTransitions().Add(new Transition());
        states.Add(fleeState);

        states[0].GetTransitions()[0].targetState = states[1];
        states[1].GetTransitions()[0].targetState = states[0];

        //states[0].GetTransitions()[0].bTriggered = true;
        sm = new StateMachine(this, states);
    }
Пример #25
0
    public SteeringOutput getSteering()
    {
        Vector3 rayVector = s.getCharacter().velocity;

        rayVector.Normalize();
        rayVector *= lookahead;
        //Debug.Log(lookahead);
        // Does the ray intersect any objects excluding the player layer
        collisionDetector = new RaycastHit();
        float angleInc = 10f;

        //Debug.DrawRay(s.getCharacter().position, s.getCharacter().velocity, Color.green);
        for (int i = 0; i < 6; i++)
        {
            Vector3 rotRayVec;
            if (i % 2 == 0)
            {
                rotRayVec = Quaternion.AngleAxis(angleInc * -(i / 2), Vector3.up) * rayVector;
            }
            else
            {
                rotRayVec = Quaternion.AngleAxis(angleInc * Mathf.Ceil(i / 2), Vector3.up) * rayVector;
            }


            rotRayVec.Scale(new Vector3(1f, 0f, 1f));
            Debug.DrawRay(s.getCharacter().position, rotRayVec, Color.cyan);
            s.getCharacter().owner.GetComponent <NPCController>().DrawLine(s.getCharacter().owner.transform.position, rotRayVec * lookahead);
            if (Physics.Raycast(s.getCharacter().position, rotRayVec, out collisionDetector, lookahead))
            {
                if (collisionDetector.collider.gameObject.Equals(s.getCharacter().owner))
                {
                    continue;
                }

                Debug.DrawRay(collisionDetector.point, collisionDetector.normal * avoidDistance, Color.red);
                s.setTargetPosition(collisionDetector.point + (collisionDetector.normal * avoidDistance));
                Kinematic avoid = new Kinematic()
                {
                    position = collisionDetector.point + (collisionDetector.normal * avoidDistance)
                };
                //targetPos = s.getTarget().position;

                DynamicSeek seekAvoidPoint = new DynamicSeek(s.getCharacter(), avoid, maxAcceleration);
                return(seekAvoidPoint.getSteering());
            }
        }

        try
        {
            targetPos = s.getTarget().position;
        }
        catch (Exception e) {
        }
        return(s.getSteering());
    }
Пример #26
0
 public KinematicSteeringOutput getSteering(Kinematic self)
 {
     if (this.target == null)
     {
         //if there is no target, set it to yourself
         this.target = self;
     }
     KSO = AICore.getSteering(self, this.target);
     return(this.KSO);
 }
    public override SteeringOutPut GetSteering(Kinematic character)
    {
        slotAs = formation.getSlotByNumber(slot);

        kinetic.posicion    = slotAs.Location.Posicion;
        kinetic.orientacion = slotAs.Location.Orientacion;
        arrive.target       = kinetic;
        align.target        = kinetic;
        return(base.GetSteering(character));
    }
Пример #28
0
    // Define Output
    override public Steering Output(Kinematic target)
    {
        // Create the structure to hold our output and bound acceleration
        Steering steering = new Steering(target.position - player.data.position, 0);

        steering.linear = steering.linear.normalized * player.maxAccelerationL;

        // Return acceleration
        return(steering);
    }
Пример #29
0
 public DynamicArrive(Kinematic _character, Kinematic _target, float _maxAcceleration, float _maxSpeed,
                      float _targetRadius, float _slowRadius)
 {
     character       = _character;
     target          = _target;
     maxAcceleration = _maxAcceleration;
     maxSpeed        = _maxSpeed;
     targetRadius    = _targetRadius;
     slowRadius      = _slowRadius;
 }
Пример #30
0
    //Code based on AI for Games 3rd Edition, p. 73
    public override SteeringOutput getSteering(Kinematic selfKinematic, GameObject target = null, Kinematic targetKinematic = null)
    {
        if (selfKinematic.velocity.sqrMagnitude == 0)
        {
            return(null);
        }

        alignTarget.orientation = Mathf.Atan2(selfKinematic.velocity.x, selfKinematic.velocity.z) * Mathf.Rad2Deg;
        return(base.getSteering(selfKinematic, target, alignTarget));
    }
Пример #31
0
        /// <summary>
        /// Calculates the node of this character
        /// </summary>
        /// <param name="character">Kinematic of the character</param>
        /// <returns>The node of the character</returns>
        protected Node GetNearestNode(Kinematic character)
        {
            Vector2 pos = GetPolygon(character).center;

            foreach (Node node in GameMode.smells.nodes)
                if (pos == node.point)
                    return node;

            return new Node(Vector2.Zero, -1);
        }
Пример #32
0
 public DynamicAlign(Kinematic _character, Kinematic _target, float _maxAngularAcceleration, float _maxRotation,
                     float _targetRadius, float _slowRadius)
 {
     character = _character;
     target    = _target;
     maxAngularAcceleration = _maxAngularAcceleration;
     maxRotation            = _maxRotation;
     targetRadius           = _targetRadius;
     slowRadius             = _slowRadius;
 }
Пример #33
0
        public Character(float startPositionX, float startPositionY)
        {
            kinematic = new Kinematic();
            life = 100;
            sourceRect = new Rectangle(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
            spriteColor = Color.White;

            kinematic.position = new Vector3(startPositionX, startPositionY, 0);
            bound = new BoundingSphere(kinematic.position, 30);
            CollisionDetector.players.Add(bound);
        }
Пример #34
0
    public static Steering getSteering(float maxAcceleration, float maxSpeed, Kinematic character, Kinematic target)
    {
        Steering steering = new Steering();

        steering.linear = character.position - target.position;

        steering.linear = steering.linear.normalized * maxAcceleration;
        steering.angular = 0;

        return steering;
    }
Пример #35
0
    public static Steering getSteering(float maxAcceleration, float maxSpeed, Kinematic character,
        IPath path, int pathOffset)
    {
        currentParam = path.getParam(character.position, currentParam);

        int targetParam = currentParam + pathOffset;

        Kinematic target = new Kinematic(path.getPosition(targetParam));

        return Seek_S.getSteering(maxAcceleration, maxSpeed, character, target);
    }
Пример #36
0
        public override SteeringOutput GetSteering(Kinematic character, Kinematic target)
        {
            // If the target was reached, stop your movement
            if ((character.position - target.position).Length() <= endingRadius)
            {
                character.velocity = Vector3.Zero;
                character.rotation = 0;
                return new SteeringOutput();
            }

            return base.GetSteering(character, target);
        }
Пример #37
0
	void Start () {
        character = new Kinematic(transform.position, transform.rotation.eulerAngles.z);
        lastTargetPosition = target.transform.position;

        List<Vector3> pathPoints = new List<Vector3>();
        pathPoints.Add(transform.position);
        for (int i = 1; i < 20; i++)
        {
            Vector3 randomOffset = new Vector3(Random.Range(0, 10f), 0, Random.Range(0, 20f));
            pathPoints.Add(pathPoints[pathPoints.Count - 1] + randomOffset);
            Debug.DrawLine(pathPoints[pathPoints.Count - 2], pathPoints[pathPoints.Count - 1], Color.red, 60);
        }
        pathPoints.Add(transform.position);
        randomPath = new SegmentPath(pathPoints, 2);
	}
Пример #38
0
    public static Steering getSteering(float maxAcceleration, float maxSpeed, float targetRadius, float slowRadius,
        float predictionTime, Kinematic character, Kinematic target)
    {
        Steering steering = new Steering();

        steering.linear = target.velocity - character.velocity;
        steering.linear /= predictionTime;

        if (steering.linear.magnitude > maxAcceleration)
            steering.linear = steering.linear.normalized * maxAcceleration;

        steering.angular = 0;

        return steering;
    }
Пример #39
0
        public Paintball(ContentManager content, Kinematic k, Color c)
        {
            // Load the texture
            texture = content.Load<Texture2D>(ASSET);
            color = c;

            // Initialize the kinematics
            kinematic = k;

            kinematic.velocity += kinematic.velocity * 2;
            kinematic.velocity.Z += 1.5f;
            kinematic.rotation = 0;

            // Initialize the bounding box
            bound = new BoundingSphere(kinematic.position, Math.Max(texture.Height, texture.Width));
        }
Пример #40
0
    public static Steering getSteering(float maxAngularAcceleration, float maxRotation, float targetRadius, float slowRadius,
        float predictionTime, float wanderOffset, float wanderRadius, float wanderRate, float maxAcceleration, Kinematic character)
    {
        wanderOrientation += randomBinomial() * wanderRate;

        float targetOrientation = wanderOrientation + character.orientation;

        Kinematic target = new Kinematic(character.position + wanderOffset * character.OrientationVector());
        target.position += wanderRadius * new Vector3(0, 0, targetOrientation);

        Steering steering = Face_S.getSteering(maxAcceleration, maxRotation, targetRadius, slowRadius, predictionTime,
            character, target);

        steering.linear = maxAcceleration * character.OrientationVector();

        return steering;
    }
Пример #41
0
    public static Steering getSteering(float maxAcceleration, float maxSpeed, float maxPredictionTime, Kinematic character, Kinematic target)
    {
        Vector3 direction = target.position - character.position;
        float distance = direction.magnitude;

        float speed = character.velocity.magnitude;

        float prediction;
        if (speed <= distance / maxPredictionTime)
            prediction = maxPredictionTime;
        else
            prediction = distance / speed;

        Kinematic newTarget = new Kinematic(target.position + target.velocity * prediction);

        return Seek_S.getSteering(maxAcceleration, maxSpeed, character, newTarget);
    }
Пример #42
0
    public static Steering getSteering(float maxAngularAcceleration, float maxRotation, float targetRadius, float slowRadius,
        float predictionTime, Kinematic character, Kinematic target)
    {
        Vector3 direction = target.position - character.position;

        if (direction.magnitude == 0)
        {
            Steering steering = new Steering();
            steering.linear = Vector3.zero;
            steering.angular = 0.0f;
            return steering;
        }

        Kinematic newTarget = new Kinematic(target.position, - Mathf.Atan2(-direction.x, direction.z) * 180 / Mathf.PI);

        return Align_S.getSteering(maxAngularAcceleration, maxRotation, targetRadius, slowRadius,
            predictionTime, character, newTarget);
    }
Пример #43
0
    public static Steering getSteering(Kinematic character, Kinematic[] targets, float treshold, float maxAcceleration)
    {
        Steering steering = new Steering();

        for (int i = 0; i < targets.Length; i++)
        {
            Vector3 direction = targets[i].position - character.position;
            float distance = direction.magnitude;

            if (distance < treshold)
            {
                float strength = maxAcceleration * (treshold - distance) / treshold;
                steering.linear += strength * direction.normalized;
            }
        }

        return steering;
    }
Пример #44
0
        public void Update(GameTime time, Kinematic target)
        {
            CollisionDetector.players.Remove(bound);

            // Dont try to reach the target in the z-axis. You can't jump!
            target.position.Z = target.velocity.Z = 0;

            // Update kinematics
            UpdateKinematics(time, target);

            // Increase life a little bit
            if (life < 25)
                life += 0.005f;

            base.Update();

            CollisionDetector.players.Add(bound);
        }
Пример #45
0
        /// <summary>
        /// Calculates the character's polygon
        /// </summary>
        /// <param name="character">Kinematic of the character</param>
        /// <returns>The polygon of the character</returns>
        protected Polygon GetPolygon(Kinematic character)
        {
            float min = float.PositiveInfinity;
            Polygon polygon = new Polygon(new List<Vector2>());
            Vector2 vect = new Vector2(character.position.X, character.position.Y);

            foreach (Polygon poly in GameMode.polygons)
            {
                float diff = Vector2.Distance(poly.center, vect);

                if (poly.Contains(vect) && diff < min)
                {
                    min = diff;
                    polygon = poly;
                }
            }

            return polygon;
        }
Пример #46
0
        /// <summary>
        /// Calculates the character's polygon
        /// </summary>
        /// <param name="character">Kinematic of the character</param>
        /// <returns>The polygon of the character</returns>
        protected Polygon GetPolygon(Kinematic character)
        {
            Vector2 vect = new Vector2(character.position.X, character.position.Y);
            float min = float.PositiveInfinity;
            Polygon closest = new Polygon(new List<Vector2>());

            foreach (Polygon poly in GameMode.polygons)
                if (poly.Contains(vect))
                {
                    return poly;
                }
                else if ((poly.center - vect).Length() < min)
                {
                    min = (poly.center - vect).Length();
                    closest = poly;
                }

            return closest;
        }
Пример #47
0
        public override SteeringOutput GetSteering(Kinematic character, Kinematic target)
        {
            // If the characters are in the same polygon, do nothing
            Polygon targetPolygon = GetPolygon(target);
            if (lastPolygon.center != targetPolygon.center)
            {
                // Generate a new path
                AStar star = new AStar(GameMode.movement);

                Node c = GetNearestNode(character);
                Node t = GetNearestNode(target);

                if (heuristic == 's')
                    path = star.Pathfind(c, t, new SafestHeuristic(t));
                else
                    path = star.Pathfind(c, t, new ClosestHeuristic(t));

                lastPolygon = targetPolygon;
            }

            return base.GetSteering(character, target);
        }
Пример #48
0
    public static Steering getSteering(float maxAngularAcceleration, float maxRotation, float targetRadius, float slowRadius,
        float predictionTime, Kinematic character, Kinematic target)
    {
        Steering steering = new Steering();

        float rotation = target.orientation - character.orientation;

        rotation = mapToRange(rotation);
        float rotationSize = Mathf.Abs(rotation);

        if (rotationSize < targetRadius)
        {
            steering.linear = Vector3.zero;
            steering.angular = 0.0f;
            return steering;
        }

        float targetRotation;
        if (rotationSize > slowRadius)
            targetRotation = maxRotation;
        else
            targetRotation = maxRotation * rotationSize / slowRadius;

        targetRotation *= rotation / rotationSize;

        steering.linear = Vector3.zero;
        steering.angular = (targetRotation - character.rotation) / predictionTime;

        float angularAcceleration = Mathf.Abs(steering.angular);
        if (angularAcceleration > maxAngularAcceleration)
        {
            steering.angular /= angularAcceleration;
            steering.angular *= maxAngularAcceleration;
        }

        return steering;
    }
Пример #49
0
 public RefugeeSteering(Kinematic character, IHasPosition target, float maxAcceleration)
     : base(character, target, maxAcceleration)
 {
 }
Пример #50
0
	void Start () {
        character = new Kinematic(transform.position);
        target = new Kinematic(targetTransform.position);
        lastFrameTargetPosition = targetTransform.position;
	}
Пример #51
0
	void Update () {
        Steering curSteering;
        Kinematic targetK;
        switch (behaviour)
        {
            case Behaviours.Seek:
                targetK = new Kinematic(target.position);
                curSteering = Seek_S.getSteering(maxAcceleration, maxSpeed, character, targetK);
                break;

            case Behaviours.Flee:
                targetK = new Kinematic(target.position);
                curSteering = Flee_S.getSteering(maxAcceleration, maxSpeed, character, targetK);
                break;

            case Behaviours.Arrive:
                targetK = new Kinematic(target.position);
                curSteering = Arrive_S.getSteering(maxAcceleration, maxSpeed, targetRadius, slowRadius, predictionTime,
                    character, targetK);
                break;

            case Behaviours.Align:
                targetK = new Kinematic(target.position, target.rotation.eulerAngles.z);
                curSteering = Align_S.getSteering(maxAngularAcceleration, maxRotation, targetRadius, slowRadius, predictionTime,
                    character, targetK);
                break;

            case Behaviours.VelocityMatch:
                targetK = new Kinematic(target.position, (target.transform.position - lastTargetPosition) / Time.deltaTime);
                curSteering = VelocityMatch_S.getSteering(maxAcceleration, maxSpeed, targetRadius, slowRadius,
                    predictionTime, character, targetK);
                break;

            case Behaviours.Face:
                targetK = new Kinematic(target.position, target.rotation.eulerAngles.z);
                curSteering = Face_S.getSteering(maxAngularAcceleration, maxRotation, targetRadius, slowRadius, predictionTime,
                    character, targetK);
                break;

            case Behaviours.Pursue:
                targetK = new Kinematic(target.position, (target.transform.position - lastTargetPosition) / Time.deltaTime);
                curSteering = Pursue_S.getSteering(maxAcceleration, maxSpeed, maxPredictionTime, character, targetK);
                break;

            case Behaviours.Evade:
                targetK = new Kinematic(target.position, (target.transform.position - lastTargetPosition) / Time.deltaTime);
                curSteering = Evade_S.getSteering(maxAcceleration, maxSpeed, maxPredictionTime, character, targetK);
                break;

            case Behaviours.Wander:
                curSteering = Wander_S.getSteering(maxAngularAcceleration, maxRotation, targetRadius, slowRadius, predictionTime,
                    wanderOffset, wanderRadius, wanderRate, maxAcceleration, character);
                break;

            case Behaviours.RandomPatrol:
                curSteering = FollowPath_S.getSteering(maxAcceleration, maxSpeed, character, randomPath, 1);
                break;

            default:
                curSteering = new Steering(Vector3.zero, 0.0f);
                break;
        }
        character.Update(curSteering, maxSpeed, Time.deltaTime);
        transform.position = character.position;
        Quaternion rot = Quaternion.Euler(transform.rotation.eulerAngles.x, character.orientation, transform.rotation.eulerAngles.z);
        transform.rotation = rot;

        lastTargetPosition = target.transform.position;
	}
Пример #52
0
 protected SteeringBase(Kinematic character, IHasPosition target, float maxAcceleration)
 {
     Character = character;
     Target = target;
     MaxAcceleration = maxAcceleration;
 }
Пример #53
0
        protected Polygon GetPolygon(Kinematic character)
        {
            Vector2 vect = new Vector2(character.position.X, character.position.Y);

            foreach (Polygon poly in GameMode.polygons)
                if (poly.Contains(vect))
                    return poly;

            return new Polygon(new List<Vector2>());
        }
Пример #54
0
 public ArrivingSteering(Kinematic character, IHasPosition target, float maxAcceleration, float slowRadius, float satisfactionRadius)
     : base(character, target, maxAcceleration)
 {
     mSatisfactionRadius = satisfactionRadius;
     mSlowRadius = slowRadius;
 }
Пример #55
0
        protected virtual void UpdateKinematics(GameTime time, Kinematic target)
        {
            //  SteeringOutput steering = behaviors[0].GetSteering(kinematic, target);

            // Update the movement
            SteeringOutput steering = machine.Update(kinematic, target);

            kinematic.Update(steering, MAX_SPEED, time);

            // Update the sensors
            foreach (Sensor sensor in sensors)
                sensor.Detect();

            // If the character is close enough, throw a paintball
            UpdatePaintballs(time);

            // If the character is moving, animate it
            if (kinematic.velocity.Length() > 0)
                AnimateWalk(time);

            foreach (Sensor sensor in sensors)
                Gearset.GS.Show("Sensor", sensor.Test());
        }
Пример #56
0
	void Start () {
        character = new Kinematic(transform.position);
        target = new Kinematic(targetTransform.position);
	}