Ejemplo n.º 1
0
 public static void RemoveAllSources(this ParentConstraint parentConstraint)
 {
     for (int i = 0; i < parentConstraint.sourceCount; i++)
     {
         parentConstraint.RemoveSource(0);
     }
 }
Ejemplo n.º 2
0
 private void Start()
 {
     // property blocks
     sphereBlock    = new MaterialPropertyBlock();
     fingerSphereOn = new MaterialPropertyBlock();
     fingerSphereOn.SetInt("_Enabled", 1);
     fingerSphereOff = new MaterialPropertyBlock();
     fingerSphereOff.SetInt("_Enabled", 0);
     // handle default values
     cam                = cameraObject.GetComponent <Camera>();
     zoom               = Remap(cam.focalLength, 5, 60, 0, 1);
     zoomSlider.value   = zoom;
     vrZoomSlider.value = zoom;
     focal              = 0.5f;
     lensAnimator.SetFloat("Focal", focal);
     focalSlider.value   = focal;
     vrFocalSlider.value = focal;
     // handle vr/desktop switch
     col        = gameObject.GetComponent <BoxCollider>();
     constraint = gameObject.GetComponent <ParentConstraint>();
     cR         = visuals.GetComponent <MeshRenderer>();
     sR         = viewSphere.GetComponent <MeshRenderer>();
     fingerSphere.gameObject.SetActive(false);
     pickup = (VRC_Pickup)GetComponent(typeof(VRC_Pickup));
     player = Networking.LocalPlayer;
     if (player == null)
     {
         return;
     }
 }
Ejemplo n.º 3
0
    private void ThrowDuckling()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Vector3 worldMousePosition =
                Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
            Vector2 relativePosition = worldMousePosition - transform.position;

            if (ammo > 0)
            {
                --ammo;
                throwing = true;
                AudioManager.instance.PlaySound("duckling");
                Duckling duckling = ducklings[ammo];
                StartCoroutine(WingSpin());
                ducklings.Remove(duckling);
                duckling.motherless = true;
                duckling.an.SetBool("Thrown", true);
                duckling.NotJumping();
                ParentConstraint dpc = duckling.gameObject.GetComponent <ParentConstraint>();
                Rigidbody2D      drc = duckling.gameObject.GetComponent <Rigidbody2D>();
                duckling.gameObject.transform.position = new Vector2(transform.position.x, transform.position.y + 2f);
                dpc.constraintActive = false;
                drc.AddForce(relativePosition.normalized * throwPower, ForceMode2D.Impulse);
                drc.simulated = true;
            }
        }
    }
Ejemplo n.º 4
0
 // ********************************************************************
 #region Extension Methods
 // ********************************************************************
 public static void ClearSources(this ParentConstraint _constraint)
 {
     for (int i = _constraint.sourceCount - 1; i >= 0; --i)
     {
         _constraint.RemoveSource(i);
     }
 }
Ejemplo n.º 5
0
        protected virtual void Awake()
        {
            this._camera           = this.gameObject.AddComponent <Camera>();
            this._cameraConstraint = this.gameObject.AddComponent <ParentConstraint>();
            this._cameraConstraint.constraintActive = true;

            RenderTextureFormat format = WebRTC.GetSupportedRenderTextureFormat(SystemInfo.graphicsDeviceType);

            this._streamingTexture = new RenderTexture(VideoStreamManager.Instance.streamingResolution.x, VideoStreamManager.Instance.streamingResolution.y, this.depth, format)
            {
                antiAliasing = this.antiAliasing
            };
            this._streamingTexture.Create();

            Camera currentMain = Camera.main;

            if (currentMain != null)
            {
                ConfigureForNewCamera(currentMain);
            }
            else
            {
                this._lookingForNewCamera = true;
            }
        }
Ejemplo n.º 6
0
    private void OnTriggerEnter(Collider other)
    {
        if (itemGrabbed)
        {
            return;
        }

        if (other.CompareTag("Item"))
        {
            other.GetComponent <Rigidbody>().isKinematic = true;
            ParentConstraint p = other.GetComponent <ParentConstraint>();
            if (p == null)
            {
                return;
            }
            constraintSource.sourceTransform = this.transform;
            constraintSource.weight          = 1.0f;
            p.AddSource(constraintSource);

            Vector3 tO = translationOffset;
            Vector3 rO = rotationOffset;
            if (Vector3.Dot(transform.forward, Vector3.up) < 0)
            {
                tO *= -1;
                rO *= -1;
            }
            p.SetTranslationOffset(0, tO);
            p.SetRotationOffset(0, rO);
            p.constraintActive = true;
            //other.transform.SetParent(this.transform);
            //other.transform.localPosition = Vector3.zero;
            //other.transform.localRotation = Quaternion.identity;
            itemGrabbed = true;
        }
    }
    void SetupParentConstraint()
    {
        ParentConstraint constraint = gameObject.AddComponent <ParentConstraint>();

        constraint.AddSource(MakeConstraintSourceFromMainCamera());
        constraint.SetTranslationOffset(0, new Vector3(0, 0, 10));
        constraint.constraintActive = true;
    }
    void SetupParentConstraint()
    {
        Vector3          translationOffset = transform.position - Camera.main.transform.position;
        ParentConstraint constraint        = gameObject.AddComponent <ParentConstraint>();

        constraint.AddSource(MakeConstraintSourceFromMainCamera());
        constraint.SetTranslationOffset(0, translationOffset);
        constraint.constraintActive = true;
    }
 private void Start()
 {
     _isActive       = false;
     _camParent      = Camera.main.transform;
     _originLocalPos = transform.localPosition;
     _myPC           = GetComponent <ParentConstraint>();
     _newParent      = Instantiate(new GameObject("BowParentObject"), _camParent.parent.parent).transform;
     SetParentInstance(_isActive, false);
 }
Ejemplo n.º 10
0
 // ********************************************************************
 public static void AddSourceTransform(this ParentConstraint _constraint, Transform _transform)
 {
     if (_transform != null)
     {
         ConstraintSource source = new ConstraintSource();
         source.sourceTransform = _transform;
         source.weight          = 100;
         _constraint.AddSource(source);
     }
 }
Ejemplo n.º 11
0
 void OnToggleParentConstraint()
 {
     foreach (var selected in Selection.SelectedObjects)
     {
         ParentConstraint constraint = selected.GetComponent <ParentConstraint>();
         if (null != constraint)
         {
             constraint.constraintActive = !constraint.constraintActive;
         }
     }
 }
Ejemplo n.º 12
0
    /* Constraints for the position, necessary to keep the stars within the bubbles */
    public void setConstraint(GameObject bubble)
    {
        parentsCons = GetComponent <ParentConstraint>();
        bubbSource.sourceTransform = bubble.transform;

        parentsCons.AddSource(bubbSource);
        parentsCons.SetTranslationOffset(0, new Vector3(0, 0, 0));
        parentsCons.weight           = 1;
        parentsCons.locked           = true;
        parentsCons.constraintActive = true;
    }
Ejemplo n.º 13
0
 public static void SetSource(this ParentConstraint constraint, Transform target, bool snapToTarget)
 {
     constraint.SetSource(target);
     if (!snapToTarget)
     {
         // Setup target offset.
         Vector3 posOffset = target.InverseTransformPoint(constraint.transform.position);
         Vector3 rotOffset = (Quaternion.Inverse(target.rotation) * constraint.transform.rotation).eulerAngles;
         constraint.SetTranslationOffset(0, posOffset);
         constraint.SetRotationOffset(0, rotOffset);
     }
 }
Ejemplo n.º 14
0
    protected void Awake()
    {
        _animationTweens = new List <Tweener>();

        rect_transform = this.transform as RectTransform;
        rigidBody      = this.GetComponent <Rigidbody2D>();
        fixedJoint     = this.GetComponent <FixedJoint2D>();

        _parentConstraint = this.GetComponent <ParentConstraint>();
        _trailRenderer    = this.GetComponent <TrailRenderer>();

        SetCollisionEnabled(false);
    }
Ejemplo n.º 15
0
    IEnumerator HoldItem()
    {
        isHolding = true;

        // Create layer mask for holdable objects
        int layermask = LayerMask.GetMask(holdableLayer);

        RaycastHit raycast;

        // If we hit a GameObject on specified layer
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out raycast, pickupDistance, layermask))
        {
            // Save object information for later use
            Transform hit          = raycast.transform;
            Rigidbody hitRigidbody = hit.GetComponent <Rigidbody>();

            // Set parent constraint for object to hold
            ParentConstraint hitConstraint = hit.GetComponent <ParentConstraint>();
            hitConstraint.SetTranslationOffset(0, transform.InverseTransformPoint(hit.position));
            hitConstraint.SetRotationOffset(0, (Quaternion.Inverse(transform.rotation) * hit.rotation).eulerAngles);
            hitConstraint.weight           = 1f;
            hitConstraint.constraintActive = true;

            do
            {
                yield return(null);
            } while (!Input.GetButtonDown(leftClickName));

            // Disable the parent constraint
            hitConstraint.constraintActive = false;

            // Calculate throwForce
            Vector3 throwForce = transform.TransformDirection(Vector3.forward) * throwDistance;

            // If the holdable object has a FreezeControl script set velocity accordingly
            FreezeControl freezeControl = hit.GetComponent <FreezeControl>();

            if (freezeControl != null)
            {
                freezeControl.SetLastVelocity(throwForce);
            }

            hitRigidbody.velocity = throwForce;
        }

        isHolding = false;
    }
Ejemplo n.º 16
0
        bool HasParentOrConstraintSelected(Transform t, ref string parentLayerName)
        {
            Transform parent = t.parent;

            while (null != parent && parent.name != "RightHanded")
            {
                if (Selection.IsSelected(parent.gameObject))
                {
                    parentLayerName = LayerMask.LayerToName(parent.gameObject.layer);
                    return(true);
                }
                parent = parent.parent;
            }

            ParentConstraint constraint = t.gameObject.GetComponent <ParentConstraint>();

            if (null != constraint)
            {
                if (constraint.sourceCount > 0)
                {
                    GameObject sourceObject = constraint.GetSource(0).sourceTransform.gameObject;
                    if (Selection.IsSelected(sourceObject))
                    {
                        parentLayerName = LayerMask.LayerToName(sourceObject.layer);
                        return(true);
                    }
                }
            }

            LookAtConstraint lookAtConstraint = t.gameObject.GetComponent <LookAtConstraint>();

            if (null != lookAtConstraint)
            {
                if (lookAtConstraint.sourceCount > 0)
                {
                    ConstraintSource constraintSource = lookAtConstraint.GetSource(0);
                    GameObject       sourceObject     = constraintSource.sourceTransform.gameObject;
                    if (Selection.IsSelected(lookAtConstraint.GetSource(0).sourceTransform.gameObject))
                    {
                        parentLayerName = LayerMask.LayerToName(sourceObject.layer);
                        return(true);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 17
0
        public override void Initialise(VRTK_InteractableObject currentGrabbdObject, VRTK_InteractGrab currentPrimaryGrabbingObject, VRTK_InteractGrab currentSecondaryGrabbingObject, Transform primaryGrabPoint, Transform secondaryGrabPoint)
        {
            base.Initialise(currentGrabbdObject, currentPrimaryGrabbingObject, currentSecondaryGrabbingObject, primaryGrabPoint, secondaryGrabPoint);

            ParentConstraint parentConstraint = secondaryInteractableToRemove.GetComponent <ParentConstraint>();

            // Make sure that the assigned Interactable Object is still a child of this object
            bool isStillChild = secondaryInteractableToRemove.transform.IsChildOf(transform) || (parentConstraint != null && parentConstraint.sourceCount > 0 && parentConstraint.GetSource(0).sourceTransform == transform);

            if (isStillChild)
            {
                // First, remove from the parent from the secondary object so that it is not affected by it's movement
                if (parentConstraint != null)
                {
                    // Note: We assume that the objects will only have 1 parent here
                    parentConstraint.RemoveSource(0);

                    parentConstraint.constraintActive = false;
                }
                else
                {
                    secondaryInteractableToRemove.transform.parent = null;
                }

                // Set the Grabbable field to true so it can be grabbed
                secondaryInteractableToRemove.isGrabbable = true;
                secondaryInteractableToRemove.GetComponentInChildren <Collider>().enabled = true;
                secondaryInteractableToRemove.GetComponent <Rigidbody>().useGravity       = true;

                // Force grab the object with the secondary grabbing object (the controller/hand) so that it can move with that object's motion
                currentGrabbdObject.ForceStopSecondaryGrabInteraction();
                currentSecondaryGrabbingObject.interactTouch.ForceStopTouching();
                currentSecondaryGrabbingObject.ForceRelease();
                currentSecondaryGrabbingObject.interactTouch.ForceTouch(secondaryInteractableToRemove.gameObject);
                currentSecondaryGrabbingObject.AttemptGrab();

                OnObjectRemovedFromParent(new EventArgs());

                // Enable the GameObject holding the IA that will allow the object to be returned to the parent
                if (returnToParentInteractionAreaObject != null)
                {
                    returnToParentInteractionAreaObject.SetActive(true);
                }
            }
        }
Ejemplo n.º 18
0
        private void Start()
        {
            // property blocks
            sphereBlock    = new MaterialPropertyBlock();
            fingerSphereOn = new MaterialPropertyBlock();
            fingerSphereOn.SetInt("_Enabled", 1);
            fingerSphereOff = new MaterialPropertyBlock();
            fingerSphereOff.SetInt("_Enabled", 0);
            // handle default values
            cam                = cameraObject.GetComponent <Camera>();
            zoom               = Remap(cam.focalLength, 5, 60, 0, 1);
            zoomSlider.value   = zoom;
            vrZoomSlider.value = zoom;
            focal              = 0.5f;
            lensAnimator.SetFloat("Focal", focal);
            focalSlider.value   = focal;
            vrFocalSlider.value = focal;
            // handle vr/desktop switch
            col        = gameObject.GetComponent <BoxCollider>();
            constraint = gameObject.GetComponent <ParentConstraint>();
            cR         = visuals.GetComponent <MeshRenderer>();
            sR         = viewSphere.GetComponent <MeshRenderer>();
            fingerSphere.gameObject.SetActive(false);
            pickup = (VRC_Pickup)GetComponent(typeof(VRC_Pickup));
            var player = Networking.LocalPlayer;

            if (player == null)
            {
                return;
            }
            if (player.IsUserInVR())
            {
                cameraAnimator.SetBool("IsVR", true);
                vrUI.SetActive(true);
                isDesktop = false;
                constraint.constraintActive = false;
                pickup.pickupable           = true;
                return;
            }

            desktopUI.SetActive(true);
            sphereBlock.SetInt("_Watermark", 1);
            sphereBlock.SetFloat("_SceneStartTime", Time.time - 1);
            sR.SetPropertyBlock(sphereBlock);
        }
Ejemplo n.º 19
0
    public void PositionSelf()
    {
        lookAtTarget = GameObject.FindGameObjectWithTag("LookAtTarget").transform;
        constraint   = GetComponent <ParentConstraint>();

        if (owner != null)
        {
            ConstraintSource cs = new ConstraintSource();
            cs.sourceTransform = owner.gameObject.GetComponent <ItemController>().useWeaponBone;
            cs.weight          = 1;
            ConstraintSource cs1 = new ConstraintSource();
            cs1.sourceTransform = owner.gameObject.GetComponent <ItemController>().restWeaponBone;

            cs1.weight = 0;
            constraint.AddSource(cs);
            constraint.AddSource(cs1);
            constraint.constraintActive = true;
        }
    }
Ejemplo n.º 20
0
        private void Start()
        {
            rb               = GetComponent <Rigidbody2D>();
            fallChecker      = GetComponent <FallChecker>();
            itemCollectable  = GetComponent <ItemCollectable>();
            parentConstraint = GetComponent <ParentConstraint>();

            var groundCheckers = GetComponentsInChildren <GroundChecker>();

            side1Check = groundCheckers[0];
            side2Check = groundCheckers[1];

            rb.gravityScale = 0;
            spawnLocation   = transform.position;

            itemCollectable.Collected  += () => Collected();
            itemCollectable.Dropped    += () => Dropped();
            itemCollectable.StateReset += () => Reset();
        }
Ejemplo n.º 21
0
        public override void StartReaction(object o, EventArgs e)
        {
            InteractionAreaEventArgs interactionAreaEventArgs = e as InteractionAreaEventArgs;

            if (interactionAreaEventArgs != null)
            {
                // Look at the GrabAction to find if the piece that activated the reaction is the one that was originally removed
                RemovePieceGrabAction removeAction = gameObject.GetComponentInParent <RemovePieceGrabAction>();

                if (removeAction.secondaryInteractableToRemove.gameObject == interactionAreaEventArgs.interactionObject)
                {
                    // See if there is a Parent Constraint, if so, uses that to set the parent
                    ParentConstraint parentConstraint = interactionAreaEventArgs.interactionObject.GetComponent <ParentConstraint>();

                    if (parentConstraint != null)
                    {
                        ConstraintSource parentConstraintSource = new ConstraintSource();
                        parentConstraintSource.sourceTransform = removeAction.transform;
                        parentConstraintSource.weight          = 1.0f;

                        parentConstraint.AddSource(parentConstraintSource);
                        parentConstraint.SetTranslationOffset(0, localPosition);
                        parentConstraint.constraintActive = true;
                    }
                    // Otherwise, default to transform parent
                    else
                    {
                        interactionAreaEventArgs.interactionObject.transform.parent = removeAction.transform;
                    }

                    // Deactive the collider and rigidbody on the secondary IO so that the main object can be grabbed again
                    interactionAreaEventArgs.interactionObject.GetComponentInChildren <Collider>().enabled     = false;
                    interactionAreaEventArgs.interactionObject.GetComponentInChildren <Rigidbody>().useGravity = false;
                    interactionAreaEventArgs.interactionObject.GetComponentInChildren <VRTK_InteractableObject>().isGrabbable = false;

                    // After this has been returned, deactive the IA so that it cannot be triggered again
                    gameObject.SetActive(false);
                }
            }
        }
Ejemplo n.º 22
0
        private void DidConnectToRoom(Realtime realtime)
        {
            // Instantiate the Player for this client once we've successfully connected to the room
            GameObject playerGameObject = Realtime.Instantiate(prefabName: "Hoverbird Player",               // Prefab name
                                                               ownedByClient: true,                          // Make sure the RealtimeView on this prefab is owned by this client
                                                               preventOwnershipTakeover: true,               // Prevent other clients from calling RequestOwnership() on the root RealtimeView.
                                                               useInstance: realtime);                       // Use the instance of Realtime that fired the didConnectToRoom event.

            // Get a reference to the player
            HoverbirdPlayer player = playerGameObject.GetComponent <HoverbirdPlayer>();

            // Get the constraint used to position the camera behind the player
            ParentConstraint cameraConstraint = _camera.GetComponent <ParentConstraint>();

            // Add the camera target so the camera follows it
            ConstraintSource constraintSource = new ConstraintSource {
                sourceTransform = player.cameraTarget, weight = 1.0f
            };
            int constraintIndex = cameraConstraint.AddSource(constraintSource);

            // Set the camera offset so it acts like a third-person camera.
            cameraConstraint.SetTranslationOffset(constraintIndex, new Vector3(0.0f, 1.0f, -4.0f));
            cameraConstraint.SetRotationOffset(constraintIndex, new Vector3(15.0f, 0.0f, 0.0f));
        }
Ejemplo n.º 23
0
 private void PlaceDuckling(Duckling duckling)
 {
     if (!duckling.isAmmo)
     {
         if (ammo < maxAmmo)
         {
             Debug.Log($"Gained Ammo {duckling.gameObject.name}");
             duckling.isAmmo = true;
             //ducklings[ammo] = duckling;
             ducklings.Add(duckling);
             ParentConstraint dpc = duckling.gameObject.GetComponent <ParentConstraint>();
             Rigidbody2D      drc = duckling.gameObject.GetComponent <Rigidbody2D>();
             duckling.GetComponent <SpriteRenderer>().sortingOrder = 3 - ammo;
             dpc.constraintActive = true;
             drc.simulated        = false;
             dpc.SetTranslationOffset(0, new Vector2(-0.75f, 0.50f + ammo));
             ammo++;
         }
     }
     else
     {
         return;
     }
 }
Ejemplo n.º 24
0
 // Start is called before the first frame update
 void Start()
 {
     pc = GetComponent <ParentConstraint>();
 }
Ejemplo n.º 25
0
 public static Tween TweenWeight(this ParentConstraint constraint, float to, float duration) =>
 Tweening.To(getter: () => constraint.weight,
             setter: weight => constraint.weight = weight,
             to, duration).SetTarget(constraint);
Ejemplo n.º 26
0
 // Use this for initialization
 void Start()
 {
     _startScale       = transform.localScale;
     _parentConstraint = GetComponent <ParentConstraint>();
 }
Ejemplo n.º 27
0
        public void Generate()
        {
            // Unique directory setup, named after avatar
            Directory.CreateDirectory("Assets/VRLabs/GeneratedAssets/Marker/");
            AssetDatabase.Refresh();
            // Folder name cannot contain these chars
            string cleanedName = string.Join("", descriptor.name.Split('/', '?', '<', '>', '\\', ':', '*', '|', '\"'));
            string guid        = AssetDatabase.CreateFolder("Assets/VRLabs/GeneratedAssets/Marker", cleanedName);
            string directory   = AssetDatabase.GUIDToAssetPath(guid) + "/";

            // Install layers, parameters, and menu before prefab setup
            // FX layer
            if (useIndexFinger)
            {
                AssetDatabase.CopyAsset("Assets/VRLabs/Marker/Resources/M_FX (Finger).controller", directory + "FXtemp.controller");
            }
            else
            {
                AssetDatabase.CopyAsset("Assets/VRLabs/Marker/Resources/M_FX.controller", directory + "FXtemp.controller");
            }
            AnimatorController FX = AssetDatabase.LoadAssetAtPath(directory + "FXtemp.controller", typeof(AnimatorController)) as AnimatorController;

            // remove controller layers before merging to avatar, corresponding to setup
            if (leftHanded)
            {
                RemoveLayer(FX, "M_Marker R");
            }
            else
            {
                RemoveLayer(FX, "M_Marker L");
            }

            if (!brushSize)
            {
                RemoveLayer(FX, "M_Size");
                RemoveParameter(FX, "M_Size");
            }

            if (!eraserSize)
            {
                RemoveLayer(FX, "M_EraserSize");
                RemoveParameter(FX, "M_EraserSize");
            }

            if (!localSpace)
            {
                RemoveLayer(FX, "M_Space");
                RemoveParameter(FX, "M_Space");
                RemoveLayer(FX, "M_Cull");
            }
            else
            {
                RemoveLayer(FX, "M_SpaceSimple");
                RemoveParameter(FX, "M_SpaceSimple");
                RemoveLayer(FX, "M_CullSimple");
            }

            if (writeDefaults)
            {
                AV3ManagerFunctions.SetWriteDefaults(FX);
            }
            if (gestureToDraw != 3)             // uses fingerpoint by default
            {
                ChangeGestureCondition(FX, 0, gestureToDraw);
            }

            // Set parameter driver on 'Clear' state to reset local space
            AnimatorState            state  = FX.layers[0].stateMachine.states.FirstOrDefault(s => s.state.name.Equals("Clear")).state;
            VRCAvatarParameterDriver driver = (VRCAvatarParameterDriver)state.behaviours[0];
            string driverParamName          = localSpace ? "M_Space" : "M_SpaceSimple";

            VRC.SDKBase.VRC_AvatarParameterDriver.Parameter param = new VRC.SDKBase.VRC_AvatarParameterDriver.Parameter()
            {
                name  = driverParamName,
                type  = VRC.SDKBase.VRC_AvatarParameterDriver.ChangeType.Set,
                value = 0f
            };
            driver.parameters.Add(param);

            EditorUtility.SetDirty(FX);
            AV3ManagerFunctions.MergeToLayer(descriptor, FX, AV3ManagerFunctions.PlayableLayer.FX, directory);
            AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(FX));             // delete temporary FX layer

            // Gesture layer
            AssetDatabase.CopyAsset("Assets/VRLabs/Marker/Resources/M_Gesture.controller", directory + "gestureTemp.controller");             // to modify
            AnimatorController gesture = AssetDatabase.LoadAssetAtPath(directory + "gestureTemp.controller", typeof(AnimatorController)) as AnimatorController;

            if (descriptor.baseAnimationLayers[2].isDefault == true || descriptor.baseAnimationLayers[2].animatorController == null)
            {
                AssetDatabase.CopyAsset(path_defaultGesture, directory + "Gesture.controller");
                AnimatorController gestureOriginal = AssetDatabase.LoadAssetAtPath(directory + "Gesture.controller", typeof(AnimatorController)) as AnimatorController;

                descriptor.customExpressions = true;
                descriptor.baseAnimationLayers[2].isDefault          = false;
                descriptor.baseAnimationLayers[2].animatorController = gestureOriginal;

                if (writeDefaults)
                {
                    AV3ManagerFunctions.SetWriteDefaults(gestureOriginal);
                    EditorUtility.SetDirty(gestureOriginal);
                }
            }

            gesture.RemoveLayer((leftHanded) ? 1 : 0);
            if (useIndexFinger)
            {               // use different hand animations
                for (int i = 0; i < 3; i++)
                {
                    if (gesture.layers[0].stateMachine.states[i].state.motion.name == "M_Gesture")
                    {
                        gesture.layers[0].stateMachine.states[i].state.motion = AssetDatabase.LoadAssetAtPath("Assets/VRLabs/Marker/Resources/Animations/Gesture/M_Gesture (Finger).anim", typeof(AnimationClip)) as AnimationClip;
                    }
                    else if (gesture.layers[0].stateMachine.states[i].state.motion.name == "M_Gesture Draw")
                    {
                        gesture.layers[0].stateMachine.states[i].state.motion = AssetDatabase.LoadAssetAtPath("Assets/VRLabs/Marker/Resources/Animations/Gesture/M_Gesture Draw (Finger).anim", typeof(AnimationClip)) as AnimationClip;
                    }
                }
            }
            if (gestureToDraw != 3)
            {
                ChangeGestureCondition(gesture, 0, gestureToDraw);
            }
            if (writeDefaults)
            {
                AV3ManagerFunctions.SetWriteDefaults(gesture, true);
            }

            EditorUtility.SetDirty(gesture);
            AV3ManagerFunctions.MergeToLayer(descriptor, gesture, AV3ManagerFunctions.PlayableLayer.Gesture, directory);
            AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(gesture));             // delete temporary gesture layer

            // layer weight control from merged layer may need index set correctly
            AnimatorController avatarGesture = (AnimatorController)descriptor.baseAnimationLayers[2].animatorController;

            for (int i = 0; i < avatarGesture.layers.Length; i++)
            {               // the controls' layer is normally 3 (AllParts, LeftHand, RightHand, >>>M_Gesture<<<)
                if (avatarGesture.layers[i].name.Contains("M_Gesture") && (i != 3))
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (avatarGesture.layers[i].stateMachine.states[j].state.behaviours.Length != 0)
                        {
                            VRCAnimatorLayerControl ctrl = (VRCAnimatorLayerControl)avatarGesture.layers[i].stateMachine.states[j].state.behaviours[0];
                            ctrl.layer = i;
                        }
                    }
                }
            }

            EditorUtility.SetDirty(avatarGesture);

            // Parameters
            VRCExpressionParameters.Parameter
                p_marker = new VRCExpressionParameters.Parameter
            {
                name = "M_Marker", valueType = VRCExpressionParameters.ValueType.Bool, saved = false
            },
                p_eraser = new VRCExpressionParameters.Parameter
            {
                name = "M_Eraser", valueType = VRCExpressionParameters.ValueType.Bool, saved = false
            },
                p_clear = new VRCExpressionParameters.Parameter
            {
                name = "M_Clear", valueType = VRCExpressionParameters.ValueType.Bool, saved = false
            },
                p_color = new VRCExpressionParameters.Parameter
            {
                name = "M_Color", valueType = VRCExpressionParameters.ValueType.Float, saved = true
            };
            AV3ManagerFunctions.AddParameter(descriptor, p_marker, directory);
            AV3ManagerFunctions.AddParameter(descriptor, p_eraser, directory);
            AV3ManagerFunctions.AddParameter(descriptor, p_clear, directory);
            AV3ManagerFunctions.AddParameter(descriptor, p_color, directory);

            if (localSpace)
            {
                VRCExpressionParameters.Parameter p_space = new VRCExpressionParameters.Parameter
                {
                    name = "M_Space", valueType = VRCExpressionParameters.ValueType.Int, saved = false
                };
                AV3ManagerFunctions.AddParameter(descriptor, p_space, directory);
            }
            else
            {
                VRCExpressionParameters.Parameter p_spaceSimple = new VRCExpressionParameters.Parameter
                {
                    name = "M_SpaceSimple", valueType = VRCExpressionParameters.ValueType.Bool, saved = false
                };
                AV3ManagerFunctions.AddParameter(descriptor, p_spaceSimple, directory);
            }

            if (brushSize)
            {
                VRCExpressionParameters.Parameter p_size = new VRCExpressionParameters.Parameter
                {
                    name = "M_Size", valueType = VRCExpressionParameters.ValueType.Float, saved = false
                };
                AV3ManagerFunctions.AddParameter(descriptor, p_size, directory);
            }
            if (eraserSize)
            {
                VRCExpressionParameters.Parameter p_eraserSize = new VRCExpressionParameters.Parameter
                {
                    name = "M_EraserSize", valueType = VRCExpressionParameters.ValueType.Float, saved = false
                };
                AV3ManagerFunctions.AddParameter(descriptor, p_eraserSize, directory);
            }

            VRCExpressionParameters.Parameter p_menu = new VRCExpressionParameters.Parameter
            {
                name = "M_Menu", valueType = VRCExpressionParameters.ValueType.Bool, saved = false
            };
            AV3ManagerFunctions.AddParameter(descriptor, p_menu, directory);

            // handle menu instancing
            AssetDatabase.CopyAsset("Assets/VRLabs/Marker/Resources/M_Menu.asset", directory + "Marker Menu.asset");
            VRCExpressionsMenu markerMenu = AssetDatabase.LoadAssetAtPath(directory + "Marker Menu.asset", typeof(VRCExpressionsMenu)) as VRCExpressionsMenu;

            if (!localSpace)             // change from submenu to 1 toggle
            {
                VRCExpressionsMenu.Control.Parameter pm_spaceSimple = new VRCExpressionsMenu.Control.Parameter
                {
                    name = "M_SpaceSimple"
                };
                markerMenu.controls[6].type      = VRCExpressionsMenu.Control.ControlType.Toggle;
                markerMenu.controls[6].parameter = pm_spaceSimple;
                markerMenu.controls[6].subMenu   = null;               // or else the submenu is still there internally, SDK complains
            }
            else
            {
                AssetDatabase.CopyAsset("Assets/VRLabs/Marker/Resources/M_Menu Space.asset", directory + "Marker Space Submenu.asset");
                VRCExpressionsMenu subMenu = AssetDatabase.LoadAssetAtPath(directory + "Marker Space Submenu.asset", typeof(VRCExpressionsMenu)) as VRCExpressionsMenu;

                if (localSpaceFullBody == 0)                 // remove left and right foot controls
                {
                    subMenu.controls.RemoveAt(7);
                    subMenu.controls.RemoveAt(6);
                }
                markerMenu.controls[6].subMenu = subMenu;
                EditorUtility.SetDirty(subMenu);
            }

            if (!brushSize)
            {
                RemoveMenuControl(markerMenu, "Brush Size");
            }

            if (!eraserSize)
            {
                RemoveMenuControl(markerMenu, "Eraser Size");
            }

            EditorUtility.SetDirty(markerMenu);

            VRCExpressionsMenu.Control.Parameter pm_menu = new VRCExpressionsMenu.Control.Parameter
            {
                name = "M_Menu"
            };
            Texture2D markerIcon = AssetDatabase.LoadAssetAtPath("Assets/VRLabs/Marker/Resources/Icons/M_Icon_Menu.png", typeof(Texture2D)) as Texture2D;

            AV3ManagerFunctions.AddSubMenu(descriptor, markerMenu, "Marker", directory, pm_menu, markerIcon);

            // setup in scene
            GameObject marker = PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath("Assets/VRLabs/Marker/Resources/Marker.prefab", typeof(GameObject))) as GameObject;

            if (PrefabUtility.IsPartOfPrefabInstance(marker))
            {
                PrefabUtility.UnpackPrefabInstance(marker, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
            }
            marker.transform.SetParent(avatar.transform, false);

            Transform system       = marker.transform.Find("System");
            Transform targets      = marker.transform.Find("Targets");
            Transform markerTarget = targets.Find("MarkerTarget");
            Transform markerModel  = targets.Find("Model");
            Transform eraser       = system.Find("Eraser");
            Transform local        = marker.transform.Find("World").Find("Local");

            // constrain cull object to avatar
            Transform cull = marker.transform.Find("Cull");

            cull.GetComponent <ParentConstraint>().SetSource(0, new ConstraintSource {
                sourceTransform = descriptor.transform, weight = 1f
            });

            if (useIndexFinger)
            {
                DestroyImmediate(markerTarget.GetChild(0).gameObject);                 // destroy Flip
                Transform indexDistal = leftHanded ? avatar.GetBoneTransform(HumanBodyBones.LeftIndexDistal) : avatar.GetBoneTransform(HumanBodyBones.RightIndexDistal);

                // prefer the end bone of the index finger if it exists
                if (indexDistal.Find(indexDistal.gameObject.name + "_end") != null)
                {
                    markerTarget.SetParent(indexDistal.Find(indexDistal.gameObject.name + "_end"), true);
                }
                else
                {
                    markerTarget.SetParent(indexDistal, false);
                }
            }
            else                                         // using model: scale Model to target freely, and until script is destroyed, scale System to target uniformly with X-axis
            {
                markerModel.SetParent(marker.transform); // move it out of Targets hierarchy
                if (leftHanded)
                {
                    markerTarget.SetParent(avatar.GetBoneTransform(HumanBodyBones.LeftHand), true);
                }
                else
                {
                    markerTarget.SetParent(avatar.GetBoneTransform(HumanBodyBones.RightHand), true);
                }
                ((Marker)target).markerModel = markerModel;                 // to turn its mesh renderer off when script is finished
            }
            markerTarget.localPosition = Vector3.zero;
            markerTarget.localRotation = Quaternion.Euler(0f, 0f, 0f);

            HumanBodyBones[] bones = { HumanBodyBones.Hips,     HumanBodyBones.Chest, HumanBodyBones.Head, HumanBodyBones.LeftHand, HumanBodyBones.RightHand,
                                       HumanBodyBones.LeftFoot, HumanBodyBones.RightFoot };
            ParentConstraint localConstraint = local.GetComponent <ParentConstraint>();

            localConstraint.SetSource(0, new ConstraintSource {
                sourceTransform = avatar.transform, weight = 1f
            });
            if (localSpace)
            {
                for (int i = 0; i < 5; i++)
                {
                    localConstraint.SetSource(i + 1, new ConstraintSource {
                        sourceTransform = avatar.GetBoneTransform(bones[i]), weight = 0f
                    });
                }
                if (localSpaceFullBody == 1)
                {
                    for (int i = 5; i < 7; i++)
                    {
                        localConstraint.SetSource(i + 1, new ConstraintSource {
                            sourceTransform = avatar.GetBoneTransform(bones[i]), weight = 0f
                        });
                    }
                }
            }

            DestroyImmediate(targets.gameObject);             // remove the "Targets" container object when finished

            // set anything not adjustable to a medium-ish amount
            if (!eraserSize)
            {
                eraser.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);
            }
            if (!brushSize)
            {
                ParticleSystem.MinMaxCurve size = new ParticleSystem.MinMaxCurve(0.024f);
                Transform draw    = system.transform.Find("Draw");
                Transform preview = draw.GetChild(0);
                ParticleSystem.MainModule main = draw.GetComponent <ParticleSystem>().main;
                main.startSize = size;
                main           = preview.GetComponent <ParticleSystem>().main;
                main.startSize = size;
            }

            // scale MarkerTarget, which controls prefab size, according to a (normalized) worldspace distance between avatar hips and head
            Transform hips = avatar.GetBoneTransform(HumanBodyBones.Hips);
            Transform head = avatar.GetBoneTransform(HumanBodyBones.Head);
            Vector3   dist = (head.position - hips.position);

            float normalizedDist = (Math.Max(Math.Max(dist.x, dist.y), dist.z) / KSIVL_UNIT);
            float newScale       = markerTarget.localScale.x * normalizedDist;

            markerTarget.localScale = new Vector3(newScale, newScale, newScale);

            ((Marker)target).system       = system;
            ((Marker)target).markerTarget = markerTarget;
            ((Marker)target).finished     = true;
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            Debug.Log("Successfully generated Marker!");
        }
Ejemplo n.º 28
0
 private void Start()
 {
     constrain = GetComponent <ParentConstraint>();
 }
Ejemplo n.º 29
0
        void UpdateUIOnSelectionChanged(HashSet <GameObject> _, HashSet <GameObject> __)
        {
            if (null == selectedObjectNameLabel)
            {
                return;
            }
            // Clear
            selectedObjectNameLabel.Text = "";

            enableParentButton.Checked = false;
            parentTargetLabel.Text     = "";

            enableLookAtButton.Checked = false;
            lookAtTargetLabel.Text     = "";

            posLockButton.Checked   = false;
            rotLockButton.Checked   = false;
            scaleLockButton.Checked = false;

            GameObject selected = null;

            foreach (GameObject gobject in Selection.SelectedObjects)
            {
                selected = gobject;
                break;
            }

            if (null == selected)
            {
                return;
            }

            // Selected label
            if (Selection.SelectedObjects.Count > 1)
            {
                selectedObjectNameLabel.Text = $"{Selection.SelectedObjects.Count} objects selected";
            }
            else
            {
                selectedObjectNameLabel.Text = selected.name;
            }
            selectedObjectNameLabel.Text = "<color=#0079FF>" + selectedObjectNameLabel.Text + "</color>";

            // Transform
            UpdateTransformUI(selected);

            // Constraints
            ParentConstraint parentConstraint = selected.GetComponent <ParentConstraint>();

            if (null != parentConstraint && parentConstraint.sourceCount > 0)
            {
                enableParentButton.Checked = parentConstraint.constraintActive;
                parentTargetLabel.Text     = parentConstraint.GetSource(0).sourceTransform.name;
            }

            LookAtConstraint lookAtConstraint = selected.GetComponent <LookAtConstraint>();

            if (null != lookAtConstraint && lookAtConstraint.sourceCount > 0)
            {
                enableLookAtButton.Checked = lookAtConstraint.constraintActive;
                lookAtTargetLabel.Text     = lookAtConstraint.GetSource(0).sourceTransform.name;
            }
        }
Ejemplo n.º 30
0
 private void Start()
 {
     pc  = GetComponent <ParentConstraint>();
     col = GetComponent <Collider2D>();
 }