UnityEngine.Debug.DrawRay(UnityEngine.Vector3, UnityEngine.Vector3, UnityEngine.Color)

Here are the examples of the csharp api UnityEngine.Debug.DrawRay(UnityEngine.Vector3, UnityEngine.Vector3, UnityEngine.Color) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

12 Examples 7

19 View Source File : CameraWallStop.cs
License : MIT License
Project Creator : Interactml

private void LateUpdate()
        {
            float targetDist = m_OriginalDist;                                  // initially set the target distance

            m_Ray.origin = m_Pivot.position + m_Pivot.forward * sphereCastRadius;
            m_Ray.direction = -m_Pivot.forward;

            var cols = Physics.OverlapSphere(m_Ray.origin, sphereCastRadius);   // initial check to see if start of spherecast intersects anything

            bool initialIntersect = false;
            bool hitSomething = false;

            for (int i = 0; i < cols.Length; i++)                   // loop through all the collisions to check if something we care about
            {
                if ((!cols[i].isTrigger) && !(MalbersTools.CollidersLayer(cols[i],dontClip)))   //is on a layer we don't want to clip
                {
                    initialIntersect = true;
                    break;
                }
            }
           
            if (initialIntersect)                                                               // if there is a collision
            {
                m_Ray.origin += m_Pivot.forward * sphereCastRadius;
                hits = Physics.RaycastAll(m_Ray, m_OriginalDist - sphereCastRadius);            // do a raycast and gather all the intersections
            }
            else        // if there was no collision do a sphere cast to see if there were any other collisions
            {
                hits = Physics.SphereCastAll(m_Ray, sphereCastRadius, m_OriginalDist + sphereCastRadius);
            }

           
            Array.Sort(hits, m_RayHitComparer);                         // sort the collisions by distance

           
            float nearest = Mathf.Infinity;                             // set the variable used for storing the closest to be as far as possible

           
            for (int i = 0; i < hits.Length; i++)                       // loop through all the collisions
            {
                // only deal with the collision if it was closer than the previous one, not a trigger, not in the Layer Mask
                if (hits[i].distance < nearest && (!hits[i].collider.isTrigger) &&  !MalbersTools.CollidersLayer(hits[i].collider,dontClip))
                {
                    nearest = hits[i].distance;                                         // change the nearest collision to latest
                    targetDist = -m_Pivot.InverseTransformPoint(hits[i].point).z;
                    hitSomething = true;
                }
            }

                
            if (hitSomething)           // visualise the cam clip effect in the editor
            {
                Debug.DrawRay(m_Ray.origin, -m_Pivot.forward * (targetDist + sphereCastRadius), Color.red);
            }

            // hit something so move the camera to a better position
            protecting = hitSomething;
            m_CurrentDist = Mathf.SmoothDamp(m_CurrentDist, targetDist, ref m_MoveVelocity,
                                           m_CurrentDist > targetDist ? clipMoveTime : returnTime);
            m_CurrentDist = Mathf.Clamp(m_CurrentDist, closestDistance, m_OriginalDist);
            m_Cam.localPosition = -Vector3.forward * m_CurrentDist;
        }

19 View Source File : MProtectCameraFromWallClip.cs
License : MIT License
Project Creator : Interactml

private void LateUpdate()
        {
            // initially set the target distance
            float targetDist = m_OriginalDist;

            m_Ray.origin = m_Pivot.position + m_Pivot.forward * sphereCastRadius;
            m_Ray.direction = -m_Pivot.forward;

            // initial check to see if start of spherecast intersects anything
            var cols = Physics.OverlapSphere(m_Ray.origin, sphereCastRadius);

            bool initialIntersect = false;
            bool hitSomething = false;

            // loop through all the collisions to check if something we care about
            for (int i = 0; i < cols.Length; i++)
            {
                if ((!cols[i].isTrigger) &&
                    !(cols[i].attachedRigidbody != null && cols[i].attachedRigidbody.CompareTag(dontClipTag)))
                {
                    initialIntersect = true;
                    break;
                }
            }

            // if there is a collision
            if (initialIntersect)
            {
                m_Ray.origin += m_Pivot.forward * sphereCastRadius;

                // do a raycast and gather all the intersections
                m_Hits = Physics.RaycastAll(m_Ray, m_OriginalDist - sphereCastRadius);
            }
            else
            {
                // if there was no collision do a sphere cast to see if there were any other collisions
                m_Hits = Physics.SphereCastAll(m_Ray, sphereCastRadius, m_OriginalDist + sphereCastRadius);
            }

            // sort the collisions by distance
            Array.Sort(m_Hits, m_RayHitComparer);

            // set the variable used for storing the closest to be as far as possible
            float nearest = Mathf.Infinity;

            // loop through all the collisions
            for (int i = 0; i < m_Hits.Length; i++)
            {
                // only deal with the collision if it was closer than the previous one, not a trigger, and not attached to a rigidbody tagged with the dontClipTag
                if (m_Hits[i].distance < nearest && (!m_Hits[i].collider.isTrigger) &&
                    !(m_Hits[i].collider.attachedRigidbody != null &&
                      m_Hits[i].collider.attachedRigidbody.CompareTag(dontClipTag)))
                {
                    // change the nearest collision to latest
                    nearest = m_Hits[i].distance;
                    targetDist = -m_Pivot.InverseTransformPoint(m_Hits[i].point).z;
                    hitSomething = true;
                }
            }

            // visualise the cam clip effect in the editor
            if (hitSomething)
            {
                Debug.DrawRay(m_Ray.origin, -m_Pivot.forward * (targetDist + sphereCastRadius), Color.red);
            }

            // hit something so move the camera to a better position
            protecting = hitSomething;
            m_CurrentDist = Mathf.SmoothDamp(m_CurrentDist, targetDist, ref m_MoveVelocity,
                                           m_CurrentDist > targetDist ? clipMoveTime : returnTime);
            m_CurrentDist = Mathf.Clamp(m_CurrentDist, closestDistance, m_OriginalDist);
            m_Cam.localPosition = -Vector3.forward * m_CurrentDist;
        }

19 View Source File : Fly_NoRoot_Behavior.cs
License : MIT License
Project Creator : Interactml

override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
        {
            if (!animal.Fly) return;

            float TransitionNormalizedTime = 1;

            if (animator.IsInTransition(layerIndex) && stateInfo.normalizedTime < 0.5f)     //If is in the First Transition
                TransitionNormalizedTime = animator.GetAnimatorTransitionInfo(layerIndex).normalizedTime;

            if (animator.IsInTransition(layerIndex) && stateInfo.normalizedTime > 0.5f)     //If is in the Last Transition
                TransitionNormalizedTime = 1 - animator.GetAnimatorTransitionInfo(layerIndex).normalizedTime;

            deltaTime = Time.deltaTime; //Store the Delta Time

            var CleanEuler = (transform.eulerAngles);
            CleanEuler.x = CleanEuler.z = 0;

            transform.eulerAngles = CleanEuler;                                             //Reset the Rotation before rotating... with just Yaw Rotation

            float isGoingForward = animal.MovementAxis.z >= 0 ? 1 : -1;                     //Check if the animal is going Forward or Backwards

            Direction = Mathf.Lerp(Direction, Mathf.Clamp(animal.Direction, -1, 1), deltaTime * BehaviourSpeed.lerpRotation);          //Calculate the direction

            var RotationYaw = new Vector3(0, Direction * BehaviourSpeed.rotation * isGoingForward, 0);

            Quaternion Yaw = Quaternion.Euler(transform.InverseTransformDirection(RotationYaw));            //Get the Rotation on the Y Axis transformed to Quaternion


            //***THE ANIMAL ALREADY TAKE CARE FO THE YAW ROTATIONs***/
            animal.DeltaRotation *= Yaw;                                                                      //Rotation ROLL USING DeltaRotation (GOOD FOR PERFORMACE)
            // transform.rotation *= Yaw;                                                                       //Rotation ROLL USING ROTATE (BAD FOR PERFORMACE)

            //DeltaRotation = Quaternion.FromToRotation(transform.up, Vector3.up) * rb.rotation;            //Restore the rotation to the Default after turning USING ROTATE ...             
            //DeltaRotation = Quaternion.FromToRotation(transform.up, Vector3.up) * rb.rotation * Yaw;        //Restore the rotation to the Default after turning USING DeltaRotation ...

            float UpDown = animal.MovementUp;

            vertical = Mathf.Lerp(vertical, Mathf.Clamp(animal.Speed, -1, 1), deltaTime * 6);

            Vector3 DirectionVector = Vector3.zero;
            Vector3 movement = animal.T_Forward;                    //Set the Movement as the Stored Animal Forward Direction



            if (animal.DirectionalMovement)                         //If the Animal is using Directional Movement use the Raw Direction Vector
            {
                DirectionVector = animal.RawDirection;
                if (animal.IgnoreYDir) DirectionVector.y = 0;
                DirectionVector.Normalize();

                DirectionVector += (transform.up * UpDown);
                if (DirectionVector.magnitude > 1) DirectionVector.Normalize();                          //Remove extra Speed
            }
            else                                                                                         //If not is using Directional Movement Calculate New Direction Vector
            {
                DirectionVector = (transform.forward * vertical) + (transform.up * UpDown);              //Calculate the Direction to Move
                if (DirectionVector.magnitude > 1) DirectionVector.Normalize();                          //Remove extra Speed
                if (animal.MovementAxis.z < 0) UpDown = 0;                                               //Remove UP DOWN MOVEMENT while going backwards
                movement = DirectionVector;
            }

            forwardAceleration = Mathf.Lerp(forwardAceleration, DirectionVector.magnitude, deltaTime * BehaviourSpeed.lerpPosition);

            var DeltaMovement =
                movement *                                      //Apply the movement to the Forward Direction of the Animal
                forwardAceleration *                            //This is to avoid going forward all the time even if no key is pressed
                BehaviourSpeed.position *                       //The Fly Velocity multiplier
                (animal.Speed < 0 ? 0.5f : 1) *                 //If the animal is going backwards go half speed;
                deltaTime;                                      //DeltaTime

            DeltaMovement = Vector3.Lerp(Vector3.zero, DeltaMovement, TransitionNormalizedTime);

            if (CanNotSwim)
            {
                RaycastHit WaterHitCenter;
                // Debug.DrawRay(animal.Main_Pivot_Point, -Vector3.up * animal.Pivot_Multiplier * animal.ScaleFactor * animal.FallRayMultiplier, Color.green);

                if (Physics.Raycast(animal.Main_Pivot_Point, -Vector2.up, out WaterHitCenter, animal.Pivot_Multiplier * animal.ScaleFactor * animal.FallRayMultiplier, 16)) //16 Water Layer
                {
                    foundWater = true;
                }
                else
                {
                    foundWater = false;
                }
            }

            if (foundWater && DeltaMovement.y < 0)
            {
                DeltaMovement.y = 0.001f;
                animal.DeltaPosition.y = 0f;
                animal.MovementUp = 0;
            }

            animal.DeltaPosition += DeltaMovement;

            if (animal.debug) Debug.DrawRay(transform.position, DirectionVector * 2, Color.yellow);


            if (DirectionVector.magnitude > 0.001)                                              //Rotation PITCH
            {
                float NewAngle = 90 - Vector3.Angle(Vector3.up, DirectionVector);

                float smooth = Mathf.Max(Mathf.Abs(animal.MovementAxis.y), Mathf.Abs(vertical));

                NewAngle = Mathf.Clamp(-NewAngle, -Ylimit, Ylimit);

                PitchAngle = Mathf.Lerp(PitchAngle, NewAngle, deltaTime * animal.upDownSmoothness * 2);

                //transform.Rotate(Mathf.Clamp(PitchAngle, -Ylimit, Ylimit) * smooth , 0, 0, Space.Self);           //Rotation PITCH USING ROTATE (BAD FOR PERFORMACE)
                animal.DeltaRotation *= Quaternion.Euler(PitchAngle * smooth * TransitionNormalizedTime, 0, 0);      //Rotation PITCH USING DeltaRotation (GOOD FOR PERFORMACE)
            }

            //transform.Rotate(0, 0, -Bank * Mathf.Clamp(Direction, -1, 1), Space.Self);                //Rotation Bank USING ROTATE (BAD FOR PERFORMACE)
            animal.DeltaRotation *= Quaternion.Euler(0, 0, -Bank * Direction);                           //Rotation Bank USING DeltaRotation (GOOD FOR PERFORMACE)


            if (foundWater) return;

            if (FallVector != Vector3.zero)                              //if last animation was falling 
            {
                animal.DeltaPosition += FallVector * deltaTime;          //Add Recovery from falling
                FallVector = Vector3.Lerp(FallVector, Vector3.zero, deltaTime * FallRecovery);
            }

            if (UseDownAcceleration) GravityAcceleration(DirectionVector);
        }

19 View Source File : UnderWaterBehaviour.cs
License : MIT License
Project Creator : Interactml

override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
        {
            if (!animal.CanGoUnderWater || !animal.Underwater) return;              //Stop Moving if the animal is not going underwater anymore

            float TransitionNormalizedTime = 1;
            if (animator.IsInTransition(layerIndex) && stateInfo.normalizedTime < 0.5f)     //If is in the First Transition
                TransitionNormalizedTime = animator.GetAnimatorTransitionInfo(layerIndex).normalizedTime;

            if (animator.IsInTransition(layerIndex) && stateInfo.normalizedTime > 0.5f)     //If is in the Second Transition
                TransitionNormalizedTime = 1 - animator.GetAnimatorTransitionInfo(layerIndex).normalizedTime;

            deltaTime = Time.deltaTime;                                                     //Store the Delta Time

            if (useShift)
                Shift = Mathf.Lerp(Shift, animal.Shift ? ShiftMultiplier : 1, Speed.lerpPosition * deltaTime);   //Calculate the Shift

            if (animal.Up) animal.Down = false;       //Cannot press at the same time Down and UP(Jump)

            var CleanEuler = (transform.eulerAngles);
            CleanEuler.x = CleanEuler.z = 0;
            transform.eulerAngles = CleanEuler;                                             //Reset the Rotation before rotating... with just Yaw Rotation

            //animal.YAxisMovement(animal.upDownSmoothness, deltaTime);


            float isGoingForward = animal.MovementAxis.z >= 0 ? 1 : -1;                                           //Check if the animal is going Forward or Backwards
            Direction = Mathf.Lerp(Direction, Mathf.Clamp(animal.Direction, -1, 1), deltaTime * Speed.lerpRotation);          //Calculate the direction

            var RotationYaw = new Vector3(0, Direction * Speed.rotation * isGoingForward, 0);
            Quaternion Yaw = Quaternion.Euler(transform.InverseTransformDirection(RotationYaw));            //Get the Rotation on the Y Axis transformed to Quaternion

            // transform.rotation *= Yaw;                                                                   //Rotation ROLL USING ROTATE (BAD FOR PERFORMACE)
            animal.DeltaRotation *= Yaw;                                                                    //Rotation ROLL USING DeltaRotation (GOOD FOR PERFORMACE)

            float Up = animal.MovementUp;

            float forwardSpeed = Mathf.Clamp(animal.Speed, -1, 1);

            Vector3 DirectionVector = Vector3.zero;
            Vector3 movement = animal.T_Forward;                    //Set the Movement as the Stored Animal Forward Direction

            if (animal.DirectionalMovement)                         //If the Animal is using Directional Movement use the Raw Direction Vector
            {
                DirectionVector = animal.RawDirection;
                DirectionVector += (transform.up * Up);
            }
            else                                                                                         //If not is using Directional Movement Calculate New Direction Vector
            {
                DirectionVector = (transform.forward * forwardSpeed) + (transform.up * Up);              //Calculate the Direction to Move
                if (DirectionVector.magnitude > 1) DirectionVector.Normalize();                          //Remove extra Speed
                if (animal.MovementAxis.z < 0) Up = 0;                                                   //Remove UP DOWN MOVEMENT while going backwards
                movement = DirectionVector;
            }

            forwardAceleration = Mathf.Lerp(forwardAceleration, DirectionVector.magnitude, deltaTime * Speed.lerpPosition);

            var DeltaMovement =
                movement *                                      //Apply the movement to the Forward Direction of the Animal
                forwardAceleration *                            //This is to avoid going forward all the time even if no key is pressed
                Speed.position *                             //The Fly Velocity multiplier
                Shift *                                         //The Sprint mulitplier
                (animal.Speed < 0 ? 0.5f : 1) *                 //If the animal is going backwards go half speed;
                deltaTime;                                      //DeltaTime

            DeltaMovement = Vector3.Lerp(Vector3.zero, DeltaMovement, TransitionNormalizedTime);


            animal.DeltaPosition += DeltaMovement;


            if (DirectionVector.magnitude > 0.001)                                              //Rotation PITCH
            {
                float NewAngle = 90 - Vector3.Angle(Vector3.up, DirectionVector);

                float smooth = Mathf.Max(Mathf.Abs(animal.MovementAxis.y), Mathf.Abs(forwardSpeed));

                NewAngle = Mathf.Clamp(-NewAngle, -Ylimit, Ylimit);

                PitchAngle = Mathf.Lerp(PitchAngle, NewAngle, deltaTime * animal.upDownSmoothness*2);

                transform.Rotate(Mathf.Clamp(PitchAngle, -Ylimit, Ylimit) * smooth , 0, 0, Space.Self);         //Rotation PITCH USING ROTATE (BAD FOR PERFORMACE)
                //animal.DeltaRotation *= Quaternion.Euler(PitchAngle * smooth, 0, 0);                          //Rotation PITCH USING DeltaRotation (GOOD FOR PERFORMACE)
            }

            if (animal.debug) Debug.DrawRay(transform.position, DirectionVector * 2, Color.yellow);

            transform.Rotate(0, 0, -Bank * Mathf.Clamp(Direction, -1, 1), Space.Self);                //Rotation Bank USING ROTATE (BAD FOR PERFORMACE)
            //animal.DeltaRotation *= Quaternion.Euler(0, 0, -Bank * Mathf.Clamp(Direction, -1, 1));      //Rotation Bank USING DeltaRotation (GOOD FOR PERFORMACE)

            CheckExitUnderWater();
        }

19 View Source File : FallBehavior.cs
License : MIT License
Project Creator : Interactml

void AirControl()
        {
            RaycastHit hit_AirControl = animal.FallRayCast;
            float Angle = Vector3.Angle(Vector3.up, hit_AirControl.normal);
            if (Angle > animal.maxAngleSlope) return;


            float deltaTime = Time.deltaTime;
            var VerticalSpeed = rb.velocity.y;
            var PlanarRawDirection = animal.RawDirection;
            PlanarRawDirection.y = 0;

            animal.AirControlDir = Vector3.Lerp(animal.AirControlDir, PlanarRawDirection, deltaTime * animal.airSmoothness);

            Debug.DrawRay(transform.position, transform.TransformDirection(animal.AirControlDir), Color.yellow);

            Vector3 RB_Velocity = animal.AirControlDir * animal.AirForwardMultiplier;

            if (!animal.DirectionalMovement)
            {
                RB_Velocity = transform.TransformDirection(RB_Velocity);
            }

            RB_Velocity.y = VerticalSpeed;

            rb.velocity = RB_Velocity;
        }

19 View Source File : LookAt.cs
License : MIT License
Project Creator : Interactml

void LookAtBoneSet()
        {
            if (!Target && !cam) return; //If there's no camera and no Target ignore completely

            hasTarget = false;
            if (UseCamera || Target) hasTarget = true;


            angle = Vector3.Angle(transform.forward, Direction);                                                    //Find the angle for the current bone


            currentSmoothness = Mathf.Lerp(currentSmoothness, IsAiming ? 1 : 0, Time.deltaTime * Smoothness);

            if (currentSmoothness > 0.9999f) currentSmoothness = 1;
            if (currentSmoothness < 0.0001f) currentSmoothness = 0;

            for (int i = 0; i < Bones.Length; i++)
            {
                var bone = Bones[i];

                if (!bone.bone) continue;   //if There's no bone skip

                Vector3 dir = transform.forward;


                if (UseCamera && cam)
                {
                    var ScreenCenter = new Vector2(CameraCenter.x * Screen.width, CameraCenter.y * Screen.height);
                    dir = cam.forward;
                    dir = Utilities.MalbersTools.DirectionFromCamera(bone.bone, ScreenCenter, out aimHit, ~Ignore);

                    //aimHit = MalbersTools.RayCastHitToCenter(bone.bone, CameraCenter, ~Ignore);        //Calculate the Direction from the Bone

                    if (aimHit.collider)                                                //if something was hit 
                    {
                        dir = MalbersTools.DirectionTarget(bone.bone.position, aimHit.point);
                    }
                }

                if (Target) dir = MalbersTools.DirectionTarget(bone.bone, Target);

                Direction = Vector3.Lerp(Direction, dir, Time.deltaTime * Smoothness);

                if (currentSmoothness == 0) return;                                         //Skip all next stuffs


                if (debug && i == Bones.Length - 1)
                {
                    Debug.DrawRay(bone.bone.position, Direction * 15, Color.green);
                }


                var final = Quaternion.LookRotation(Direction, UpVector) * Quaternion.Euler(bone.offset);
                var next = Quaternion.Lerp(bone.bone.rotation, final, bone.weight * currentSmoothness);
                bone.bone.rotation = next;
            }
        }

19 View Source File : JumpBehaviour.cs
License : MIT License
Project Creator : Interactml

void AirControl()
        {
            RaycastHit hit_AirControl = animal.FallRayCast;
            float Angle = Vector3.Angle(Vector3.up, hit_AirControl.normal);
            if (Angle > animal.maxAngleSlope) return;


            float deltaTime = Time.deltaTime;
            var VerticalSpeed = rb.velocity.y;
            var PlanarRawDirection = animal.RawDirection;
            PlanarRawDirection.y = 0;

            animal.AirControlDir = Vector3.Lerp(animal.AirControlDir, PlanarRawDirection * ForwardMultiplier, deltaTime * animal.airSmoothness);

            Debug.DrawRay(transform.position, transform.TransformDirection(animal.AirControlDir), Color.yellow);

            Vector3 RB_Velocity = animal.AirControlDir * animal.AirForwardMultiplier;

            if (!animal.DirectionalMovement)
            {
                RB_Velocity = transform.TransformDirection(RB_Velocity);
            }

            RB_Velocity.y = VerticalSpeed;

            rb.velocity = RB_Velocity;
        }

19 View Source File : ProtectCameraFromWallClip.cs
License : MIT License
Project Creator : Lallassu

private void LateUpdate()
        {
            // initially set the target distance
            float targetDist = m_OriginalDist;

            m_Ray.origin = m_Pivot.position + m_Pivot.forward*sphereCastRadius;
            m_Ray.direction = -m_Pivot.forward;

            // initial check to see if start of spherecast intersects anything
            var cols = Physics.OverlapSphere(m_Ray.origin, sphereCastRadius);

            bool initialIntersect = false;
            bool hitSomething = false;

            // loop through all the collisions to check if something we care about
            for (int i = 0; i < cols.Length; i++)
            {
                if ((!cols[i].isTrigger) &&
                    !(cols[i].attachedRigidbody != null && cols[i].attachedRigidbody.CompareTag(dontClipTag)))
                {
                    initialIntersect = true;
                    break;
                }
            }

            // if there is a collision
            if (initialIntersect)
            {
                m_Ray.origin += m_Pivot.forward*sphereCastRadius;

                // do a raycast and gather all the intersections
                m_Hits = Physics.RaycastAll(m_Ray, m_OriginalDist - sphereCastRadius);
            }
            else
            {
                // if there was no collision do a sphere cast to see if there were any other collisions
                m_Hits = Physics.SphereCastAll(m_Ray, sphereCastRadius, m_OriginalDist + sphereCastRadius);
            }

            // sort the collisions by distance
            Array.Sort(m_Hits, m_RayHitComparer);

            // set the variable used for storing the closest to be as far as possible
            float nearest = Mathf.Infinity;

            // loop through all the collisions
            for (int i = 0; i < m_Hits.Length; i++)
            {
                // only deal with the collision if it was closer than the previous one, not a trigger, and not attached to a rigidbody tagged with the dontClipTag
                if (m_Hits[i].distance < nearest && (!m_Hits[i].collider.isTrigger) &&
                    !(m_Hits[i].collider.attachedRigidbody != null &&
                      m_Hits[i].collider.attachedRigidbody.CompareTag(dontClipTag)))
                {
                    // change the nearest collision to latest
                    nearest = m_Hits[i].distance;
                    targetDist = -m_Pivot.InverseTransformPoint(m_Hits[i].point).z;
                    hitSomething = true;
                }
            }

            // visualise the cam clip effect in the editor
            if (hitSomething)
            {
                Debug.DrawRay(m_Ray.origin, -m_Pivot.forward*(targetDist + sphereCastRadius), Color.red);
            }

            // hit something so move the camera to a better position
            protecting = hitSomething;
            m_CurrentDist = Mathf.SmoothDamp(m_CurrentDist, targetDist, ref m_MoveVelocity,
                                           m_CurrentDist > targetDist ? clipMoveTime : returnTime);
            m_CurrentDist = Mathf.Clamp(m_CurrentDist, closestDistance, m_OriginalDist);
            m_Cam.localPosition = -Vector3.forward*m_CurrentDist;
        }

19 View Source File : DrawLine.cs
License : MIT License
Project Creator : XINCGer

void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            draw = true;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            draw = false;
        }

        if (draw)
        {
            //  line.enabled = true;
            Vector3 dir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - Vector3.back * 10;
       //     if( dir.y - 2 < transform.position.y ) { HidePoints(); return; }
            Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
            if( !MainScript.StopControl )
            {//dir.y < 15.5 && dir.y > - 2 && 

                dir.z = 0;
                if (lastMousePos == dir)
                {
                    startAnim = true;
                }
                else startAnim = false;
                lastMousePos = dir;
                line.SetPosition(0, transform.position);

                waypoints[0] = transform.position;
                //int layerMask = ~(1 << LayerMask.NameToLayer("Mesh"));


                RaycastHit2D[] hit = Physics2D.LinecastAll( waypoints[0], waypoints[0] + ( (Vector2)dir - waypoints[0] ).normalized * 10 );
                foreach (RaycastHit2D item in hit)
                {
                    Vector2 point = item.point;
                //    if (point.y - waypoints[0].y < 1.5f) point += Vector2.up * 5;
                    line.SetPosition(1, point);
                    addAngle = 180;

                       if (waypoints[1].x < 0) addAngle = 0;
                       if( item.collider.gameObject.layer == LayerMask.NameToLayer( "Border" ) && item.collider.gameObject.name != "GameOverBorder" && item.collider.gameObject.name != "borderForRoundedLevels" )
                        {
                           Debug.DrawLine( waypoints[0], waypoints[1], Color.red );  //waypoints[0] + ( (Vector2)dir - waypoints[0] ).normalized * 10
                           Debug.DrawLine( waypoints[0], dir, Color.blue );
                           Debug.DrawRay( waypoints[0], waypoints[1] - waypoints[0], Color.green );
                           waypoints[1] = point;
                           waypoints[2] = point;
                           line.SetPosition( 1, dir );
                            waypoints[1] = point;
                            float angle = 0;
                            angle = Vector2.Angle(waypoints[0] - waypoints[1], (point - Vector2.up * 100) - (Vector2)point);
                            if (waypoints[1].x > 0) angle = Vector2.Angle(waypoints[0] - waypoints[1], (Vector2)point - (point - Vector2.up * 100));
                            waypoints[2] = Quaternion.AngleAxis(angle + addAngle, Vector3.back) * ((Vector2)point - (point - Vector2.up * 100));
                            Vector2 AB = waypoints[2] - waypoints[1];
                            AB = AB.normalized;
                            line.SetPosition(2, waypoints[2]);
                            break;
                        }
                        else if (item.collider.gameObject.layer == LayerMask.NameToLayer("Ball"))
                        {
                            Debug.DrawLine( waypoints[0], waypoints[1], Color.red );  //waypoints[0] + ( (Vector2)dir - waypoints[0] ).normalized * 10
                            Debug.DrawLine( waypoints[0], dir, Color.blue );
                            Debug.DrawRay( waypoints[0], waypoints[1] - waypoints[0], Color.green );
                            line.SetPosition( 1, point );
                            waypoints[1] = point;
                            waypoints[2] = point;
                            Vector2 AB = waypoints[2] - waypoints[1];
                            AB = AB.normalized;
                            line.SetPosition(2, waypoints[1] + (0.1f * AB));
                            break;
                        }
                        else
                        {

                            waypoints[1] = waypoints[0] + ( (Vector2)dir - waypoints[0] ).normalized * 10;
                            waypoints[2] = waypoints[0] + ( (Vector2)dir - waypoints[0] ).normalized * 10;
                        }

                    
 
                }
                if (!startAnim )
                    GeneratePositionsPoints();

            }

        }
        else if (!draw)
        {
            HidePoints();
        }

    }

19 View Source File : NodeLink3.cs
License : MIT License
Project Creator : XINCGer

public void Apply (bool forceNewCheck) {
			//TODO
			//This function replacedumes that connections from the n1,n2 nodes never need to be removed in the future (e.g because the nodes move or something)
			NNConstraint nn = NNConstraint.None;

			nn.distanceXZ = true;
			int graph = (int)startNode.GraphIndex;

			//Search all graphs but the one which start and end nodes are on
			nn.graphMask = ~(1 << graph);

			bool same = true;

			{
				var info = AstarPath.active.GetNearest(StartTransform.position, nn);
				same &= info.node == connectedNode1 && info.node != null;
				connectedNode1 = info.node as MeshNode;
				clamped1 = info.position;
				if (connectedNode1 != null) Debug.DrawRay((Vector3)connectedNode1.position, Vector3.up*5, Color.red);
			}

			{
				var info = AstarPath.active.GetNearest(EndTransform.position, nn);
				same &= info.node == connectedNode2 && info.node != null;
				connectedNode2 = info.node as MeshNode;
				clamped2 = info.position;
				if (connectedNode2 != null) Debug.DrawRay((Vector3)connectedNode2.position, Vector3.up*5, Color.cyan);
			}

			if (connectedNode2 == null || connectedNode1 == null) return;

			startNode.SetPosition((Int3)StartTransform.position);
			endNode.SetPosition((Int3)EndTransform.position);

			if (same && !forceNewCheck) return;

			RemoveConnections(startNode);
			RemoveConnections(endNode);

			uint cost = (uint)Mathf.RoundToInt(((Int3)(StartTransform.position-EndTransform.position)).costMagnitude*costFactor);
			startNode.AddConnection(endNode, cost);
			endNode.AddConnection(startNode, cost);

			Int3 dir = connectedNode2.position - connectedNode1.position;

			for (int a = 0; a < connectedNode1.GetVertexCount(); a++) {
				Int3 va1 = connectedNode1.GetVertex(a);
				Int3 va2 = connectedNode1.GetVertex((a+1) % connectedNode1.GetVertexCount());

				if (Int3.DotLong((va2-va1).Normal2D(), dir) > 0) continue;

				for (int b = 0; b < connectedNode2.GetVertexCount(); b++) {
					Int3 vb1 = connectedNode2.GetVertex(b);
					Int3 vb2 = connectedNode2.GetVertex((b+1) % connectedNode2.GetVertexCount());

					if (Int3.DotLong((vb2-vb1).Normal2D(), dir) < 0) continue;

					if (Int3.Angle((vb2-vb1), (va2-va1)) > (170.0/360.0f)*Mathf.PI*2) {
						float t1 = 0;
						float t2 = 1;

						t2 = System.Math.Min(t2, VectorMath.ClosestPointOnLineFactor(va1, va2, vb1));
						t1 = System.Math.Max(t1, VectorMath.ClosestPointOnLineFactor(va1, va2, vb2));

						if (t2 < t1) {
							Debug.LogError("Something went wrong! " + t1 + " " + t2 + " " + va1 + " " + va2 + " " + vb1 + " " + vb2+"\nTODO, how can this happen?");
						} else {
							Vector3 pa = (Vector3)(va2-va1)*t1 + (Vector3)va1;
							Vector3 pb = (Vector3)(va2-va1)*t2 + (Vector3)va1;

							startNode.portalA = pa;
							startNode.portalB = pb;

							endNode.portalA = pb;
							endNode.portalB = pa;

							//Add connections between nodes, or replace old connections if existing
							connectedNode1.AddConnection(startNode, (uint)Mathf.RoundToInt(((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
							connectedNode2.AddConnection(endNode, (uint)Mathf.RoundToInt(((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));

							startNode.AddConnection(connectedNode1, (uint)Mathf.RoundToInt(((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
							endNode.AddConnection(connectedNode2, (uint)Mathf.RoundToInt(((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));

							return;
						}
					}
				}
			}
		}

19 View Source File : RVOAgent.cs
License : MIT License
Project Creator : XINCGer

static void DrawVO (Vector2 circleCenter, float radius, Vector2 origin) {
			float alpha = Mathf.Atan2((origin - circleCenter).y, (origin - circleCenter).x);
			float gamma = radius/(origin-circleCenter).magnitude;
			float delta = gamma <= 1.0f ? Mathf.Abs(Mathf.Acos(gamma)) : 0;

			Draw.Debug.CircleXZ(FromXZ(circleCenter), radius, Color.black, alpha-delta, alpha+delta);
			Vector2 p1 = new Vector2(Mathf.Cos(alpha-delta), Mathf.Sin(alpha-delta)) * radius;
			Vector2 p2 = new Vector2(Mathf.Cos(alpha+delta), Mathf.Sin(alpha+delta)) * radius;

			Vector2 p1t = -new Vector2(-p1.y, p1.x);
			Vector2 p2t = new Vector2(-p2.y, p2.x);
			p1 += circleCenter;
			p2 += circleCenter;

			Debug.DrawRay(FromXZ(p1), FromXZ(p1t).normalized*100, Color.black);
			Debug.DrawRay(FromXZ(p2), FromXZ(p2t).normalized*100, Color.black);
		}

19 View Source File : PathTypesDemo.cs
License : MIT License
Project Creator : XINCGer

public IEnumerator DemoConstantPath () {
			ConstantPath constPath = ConstantPath.Construct(end.position, searchLength, null);

			AstarPath.StartPath(constPath);
			lastPath = constPath;
			// Wait for the path to be calculated
			yield return StartCoroutine(constPath.WaitForPath());

			ClearPrevious();

			// The following code will build a mesh with a square for each node visited
			List<GraphNode> nodes = constPath.allNodes;

			Mesh mesh = new Mesh();

			List<Vector3> verts = new List<Vector3>();


			#if FALSE
			// Just some debugging code which selects random points on the nodes
			List<Vector3> pts = Pathfinding.PathUtilities.GetPointsOnNodes(nodes, 20, 0);
			Vector3 avg = Vector3.zero;
			for (int i = 0; i < pts.Count; i++) {
				Debug.DrawRay(pts[i], Vector3.up*5, Color.red, 3);
				avg += pts[i];
			}

			if (pts.Count > 0) avg /= pts.Count;

			for (int i = 0; i < pts.Count; i++) {
				pts[i] -= avg;
			}

			Pathfinding.PathUtilities.GetPointsAroundPoint(start.position, AstarPath.active.data.graphs[0] as IRaycastableGraph, pts, 0, 1);

			for (int i = 0; i < pts.Count; i++) {
				Debug.DrawRay(pts[i], Vector3.up*5, Color.blue, 3);
			}
			#endif

			bool drawRaysInstead = false;
			// This will loop through the nodes from furthest away to nearest, not really necessary... but why not :D
			for (int i = nodes.Count-1; i >= 0; i--) {
				Vector3 pos = (Vector3)nodes[i].position+pathOffset;
				if (verts.Count == 65000 && !drawRaysInstead) {
					Debug.LogError("Too many nodes, rendering a mesh would throw 65K vertex error. Using Debug.DrawRay instead for the rest of the nodes");
					drawRaysInstead = true;
				}

				if (drawRaysInstead) {
					Debug.DrawRay(pos, Vector3.up, Color.blue);
					continue;
				}

				// Add vertices in a square

				GridGraph gg = AstarData.GetGraph(nodes[i]) as GridGraph;
				float scale = 1F;

				if (gg != null) scale = gg.nodeSize;

				verts.Add(pos+new Vector3(-0.5F, 0, -0.5F)*scale);
				verts.Add(pos+new Vector3(0.5F, 0, -0.5F)*scale);
				verts.Add(pos+new Vector3(-0.5F, 0, 0.5F)*scale);
				verts.Add(pos+new Vector3(0.5F, 0, 0.5F)*scale);
			}

			// Build triangles for the squares
			Vector3[] vs = verts.ToArray();
			int[] tris = new int[(3*vs.Length)/2];
			for (int i = 0, j = 0; i < vs.Length; j += 6, i += 4) {
				tris[j+0] = i;
				tris[j+1] = i+1;
				tris[j+2] = i+2;

				tris[j+3] = i+1;
				tris[j+4] = i+3;
				tris[j+5] = i+2;
			}

			Vector2[] uv = new Vector2[vs.Length];
			// Set up some basic UV
			for (int i = 0; i < uv.Length; i += 4) {
				uv[i] = new Vector2(0, 0);
				uv[i+1] = new Vector2(1, 0);
				uv[i+2] = new Vector2(0, 1);
				uv[i+3] = new Vector2(1, 1);
			}

			mesh.vertices = vs;
			mesh.triangles = tris;
			mesh.uv = uv;
			mesh.RecalculateNormals();

			GameObject go = new GameObject("Mesh", typeof(MeshRenderer), typeof(MeshFilter));
			MeshFilter fi = go.GetComponent<MeshFilter>();
			fi.mesh = mesh;
			MeshRenderer re = go.GetComponent<MeshRenderer>();
			re.material = squareMat;

			lastRender.Add(go);
		}