public override void OnStart(StartState state)
        {
            base.OnStart(state);

            // Find the winch module.
            foreach (var m in part.Modules)
            {
                if (m is KASModuleWinch winch)
                {
                    WinchModule = winch;
                }
            }
            if (WinchModule == null)
            {
                return;
            }

            // If the length slider has not been used (is at the default value of 0, e.g. right after placing the winch), set the starting value to be the default winch length.
            // If the value is not the default starting value, set the winch length to what the value is.
            if (Math.Abs(MaxLength - default(float)) < 0.01f)
            {
                MaxLength = WinchModule.maxLenght;
            }
            else
            {
                WinchModule.maxLenght = MaxLength;
            }
            _lastMaxLength = MaxLength;
        }
Ejemplo n.º 2
0
        public void Update()
        {
            if (Input.GetKey(KeyCode.LeftControl) && Input.GetKeyDown(KeyCode.K))
            {
                if (GuiConfigToogle)
                {
                    Debug.Log("KASAddonDebugMenu - Closing KAS debug tools");
                    GuiConfigToogle = false;
                }
                else
                {
                    Debug.Log("KASAddonDebugMenu - Opening KAS debug tools");
                    GuiConfigToogle = true;
                }
            }

            if (GuiConfigToogle)
            {
                if (Input.GetKey(KeyCode.LeftControl) && Input.GetKeyDown(KeyCode.Mouse0))
                {
                    Debug.Log("KASAddonDebugMenu - On click");
                    clickedPart = KAS_Shared.GetPartUnderCursor();
                    if (clickedPart)
                    {
                        moduleWinch      = null;
                        moduleGrab       = null;
                        moduleMagnet     = null;
                        moduleSuctionCup = null;
                        moduleGrapple    = null;
                        moduleTimedBomb  = null;
                        modulePort       = null;
                        moduleAnchor     = null;
                        moduleStrut      = null;
                        moduleRotor      = null;

                        moduleWinch      = clickedPart.GetComponent <KASModuleWinch>();
                        moduleGrab       = clickedPart.GetComponent <KASModuleGrab>();
                        moduleMagnet     = clickedPart.GetComponent <KASModuleMagnet>();
                        moduleSuctionCup = clickedPart.GetComponent <KASModuleSuctionCup>();
                        moduleGrapple    = clickedPart.GetComponent <KASModuleGrapplingHook>();
                        moduleTimedBomb  = clickedPart.GetComponent <KASModuleTimedBomb>();
                        modulePort       = clickedPart.GetComponent <KASModulePort>();
                        moduleAnchor     = clickedPart.GetComponent <KASModuleAnchor>();
                        moduleStrut      = clickedPart.GetComponent <KASModuleStrut>();
                        moduleRotor      = clickedPart.GetComponent <KASModuleRotor>();
                    }
                }
            }

            if (FlightGlobals.ActiveVessel.heightFromTerrain == -1f)
            {
                if (FlightGlobals.ActiveVessel.Landed)
                {
                    KAS_Shared.DebugWarning("Warning ! ActiveVessel is landed and heightFromTerrain are negative (" + FlightGlobals.ActiveVessel.heightFromTerrain + ")");
                }
            }
        }
Ejemplo n.º 3
0
        private void UpdateWinchKeyGrab()
        {
            if (Input.GetKeyDown(grabHeadKey.ToLower()))
            {
                if (FlightGlobals.ActiveVessel.isEVA)
                {
                    KASModuleWinch tmpGrabbbedHead = KAS_Shared.GetWinchModuleGrabbed(FlightGlobals.ActiveVessel);
                    if (tmpGrabbbedHead)
                    {
                        tmpGrabbbedHead.DropHead();
                        return;
                    }
                    var nearestColliders = new List <Collider>(
                        Physics.OverlapSphere(FlightGlobals.ActiveVessel.transform.position, radius, 557059));
                    float          shorterDist        = Mathf.Infinity;
                    KASModuleWinch nearestModuleWinch = null;
                    foreach (Collider col in nearestColliders)
                    {
                        KAS_LinkedPart linkedPart = col.transform.gameObject.GetComponent <KAS_LinkedPart>();
                        if (!linkedPart)
                        {
                            continue;
                        }
                        KASModuleWinch winchModule = linkedPart.part.GetComponent <KASModuleWinch>();
                        if (!winchModule)
                        {
                            continue;
                        }

                        // Check if the head is plugged
                        if (winchModule.headState != KASModuleWinch.PlugState.Deployed)
                        {
                            continue;
                        }
                        // Check if it's a head grabbed by another kerbal eva
                        if (winchModule.evaHolderPart)
                        {
                            continue;
                        }
                        // Select the nearest grabbable part
                        float distToGrab = Vector3.Distance(FlightGlobals.ActiveVessel.transform.position,
                                                            winchModule.part.transform.position);
                        if (distToGrab <= shorterDist)
                        {
                            shorterDist        = distToGrab;
                            nearestModuleWinch = winchModule;
                        }
                    }
                    //Grab nearest head if exist
                    if (nearestModuleWinch)
                    {
                        nearestModuleWinch.GrabHead(FlightGlobals.ActiveVessel);
                        return;
                    }
                }
            }
        }
Ejemplo n.º 4
0
        public void OnKISAction(BaseEventData baseEventData)
        {
            string     action  = baseEventData.GetString("action");
            Part       tgtPart = (Part)baseEventData.Get("targetPart");
            AttachNode tgtNode = (AttachNode)baseEventData.Get("targetNode");

            if (action == "Store")
            {
                if (winchConnected)
                {
                    winchConnected.UnplugHead(false);
                }
            }
            if (action == "DropEnd")
            {
                if (winchConnected)
                {
                    winchConnected.cableJointLength = winchConnected.cableRealLenght;
                    winchConnected.PlugHead(this, KASModuleWinch.PlugState.PlugDocked, false, false, true);
                }
            }
            if (action == "AttachStart")
            {
                if (tgtNode != null)
                {
                    KASModuleWinch moduleWinch = tgtNode.owner.GetComponent <KASModuleWinch>();
                    if (moduleWinch && winchConnected &&
                        moduleWinch.headState == KASModuleWinch.PlugState.Deployed &&
                        tgtNode.id == moduleWinch.connectedPortNodeName)
                    {
                        winchConnected.UnplugHead(false);
                        return;
                    }
                }
            }
            if (action == "AttachEnd")
            {
                if (winchConnected)
                {
                    winchConnected.cableJointLength = winchConnected.cableRealLenght;
                }
                if (tgtNode != null)
                {
                    KASModuleWinch moduleWinch = tgtNode.owner.GetComponent <KASModuleWinch>();
                    if (moduleWinch && moduleWinch.headState == KASModuleWinch.PlugState.Deployed &&
                        tgtNode.id == moduleWinch.connectedPortNodeName)
                    {
                        moduleWinch.PlugHead(this, KASModuleWinch.PlugState.PlugDocked, alreadyDocked: true);
                        StartCoroutine(WaitAndRemoveJoint());
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public void OnKISAction(Dictionary <string, object> eventData)
        {
            var action  = eventData["action"].ToString();
            var tgtPart = eventData["targetPart"] as Part;
            var tgtNode = eventData["targetNode"] as AttachNode;

            if (action == "Store")
            {
                if (winchConnected)
                {
                    winchConnected.UnplugHead(false);
                }
            }
            if (action == "DropEnd")
            {
                if (winchConnected)
                {
                    winchConnected.cableJointLength = winchConnected.cableRealLenght;
                    winchConnected.PlugHead(this, KASModuleWinch.PlugState.PlugDocked, false, false, true);
                }
            }
            if (action == "AttachStart")
            {
                if (tgtNode != null)
                {
                    KASModuleWinch moduleWinch = tgtNode.owner.GetComponent <KASModuleWinch>();
                    if (moduleWinch && winchConnected &&
                        moduleWinch.headState == KASModuleWinch.PlugState.Deployed &&
                        tgtNode.id == moduleWinch.connectedPortNodeName)
                    {
                        winchConnected.UnplugHead(false);
                        return;
                    }
                }
            }
            if (action == "AttachEnd")
            {
                if (winchConnected)
                {
                    winchConnected.cableJointLength = winchConnected.cableRealLenght;
                }
                if (tgtNode != null)
                {
                    KASModuleWinch moduleWinch = tgtNode.owner.GetComponent <KASModuleWinch>();
                    if (moduleWinch && moduleWinch.headState == KASModuleWinch.PlugState.Deployed &&
                        tgtNode.id == moduleWinch.connectedPortNodeName)
                    {
                        moduleWinch.PlugHead(this, KASModuleWinch.PlugState.PlugDocked, alreadyDocked: true);
                        StartCoroutine(WaitAndRemoveJoint());
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public void ContextMenuPlugDocked()
        {
            KASModuleWinch winchModule = KAS_Shared.GetWinchModuleGrabbed(FlightGlobals.ActiveVessel);

            if (winchModule)
            {
                winchModule.PlugHead(this, KASModuleWinch.PlugState.PlugDocked);
            }
            else
            {
                ScreenMessages.PostScreenMessage("You didn't have anything to plug !", 5, ScreenMessageStyle.UPPER_CENTER);
            }
        }
Ejemplo n.º 7
0
        void OnGUI()
        {
            if (!clickedWinch)
            {
                return;
            }

            GUI.skin = HighLogic.Skin;
            GUI.skin.label.alignment  = TextAnchor.MiddleCenter;
            GUI.skin.button.alignment = TextAnchor.MiddleCenter;

            guiButtonStyle = new GUIStyle(GUI.skin.button);
            guiButtonStyle.normal.textColor    = Color.white;
            guiButtonStyle.focused.textColor   = Color.white;
            guiButtonStyle.hover.textColor     = Color.yellow;
            guiButtonStyle.active.textColor    = Color.yellow;
            guiButtonStyle.onNormal.textColor  = Color.green;
            guiButtonStyle.onFocused.textColor = Color.green;
            guiButtonStyle.onHover.textColor   = Color.green;
            guiButtonStyle.onActive.textColor  = Color.green;

            guiButtonStyle.padding   = new RectOffset(4, 4, 4, 4);
            guiButtonStyle.alignment = TextAnchor.MiddleCenter;

            Vector3 headScreenPoint = Camera.main.WorldToScreenPoint(clickedWinch.headTransform.position);

            GUILayout.BeginArea(new Rect(headScreenPoint.x, Screen.height - headScreenPoint.y, 200, 200));
            GUILayout.BeginVertical();

            if (clickedWinch.evaHolderPart)
            {
                if (GUILayout.Button("Drop (Key " + grabHeadKey + ")",
                                     guiButtonStyle, GUILayout.Width(100f)))
                {
                    clickedWinch.DropHead();
                    clickedWinch = null;
                }
            }
            else
            {
                if (GUILayout.Button("Grab (Key " + grabHeadKey + ")",
                                     guiButtonStyle, GUILayout.Width(100f)))
                {
                    clickedWinch.GrabHead(FlightGlobals.ActiveVessel);
                    clickedWinch = null;
                }
            }
            GUILayout.EndHorizontal();
            GUILayout.EndArea();
        }
Ejemplo n.º 8
0
        private void UpdateWinchMouseGrab()
        {
            if (Input.GetKeyDown(KeyCode.Mouse1))
            {
                if (clickedWinch)
                {
                    clickedWinch = null;
                    return;
                }
                if (FlightGlobals.ActiveVessel.isEVA)
                {
                    KerbalEVA kerbalEva = KAS_Shared.GetKerbalEvaUnderCursor();
                    if (kerbalEva)
                    {
                        KASModuleWinch winchModule = KAS_Shared.GetWinchModuleGrabbed(kerbalEva.vessel);
                        if (winchModule)
                        {
                            clickedWinch = winchModule;
                            return;
                        }
                    }

                    Transform headTransform = KAS_Shared.GetTransformUnderCursor();
                    if (headTransform)
                    {
                        KAS_LinkedPart linkedPart = headTransform.gameObject.GetComponent <KAS_LinkedPart>();
                        if (linkedPart)
                        {
                            float dist = Vector3.Distance(FlightGlobals.ActiveVessel.transform.position,
                                                          headTransform.position);
                            if (dist <= radius)
                            {
                                clickedWinch = linkedPart.part.GetComponent <KASModuleWinch>();
                                return;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public void Drop()
        {
            if (grabbed)
            {
                KAS_Shared.DebugLog("Drop - Dropping part :" + this.part.partInfo.name);
                base.SendMessage("OnPartDrop", SendMessageOptions.DontRequireReceiver);

                if (this.part.vessel.isEVA)
                {
                    this.part.decouple();
                }

                //Remove created joints between eva and part if exist
                KAS_Shared.RemoveFixedJointBetween(this.part, evaHolderPart);
                KAS_Shared.RemoveHingeJointBetween(this.part, evaHolderPart);

                List <Collider> allColliders = new List <Collider>(this.part.GetComponentsInChildren <Collider>() as Collider[]);
                foreach (Collider col in allColliders)
                {
                    col.isTrigger = false;
                }

                if (customGroundPos && evaHolderPart.checkLanded())
                {
                    KAS_Shared.MoveRelatedTo(this.part.transform, evaCollider.transform, dropPartPos, dropPartRot);
                }
                else
                {
                    KAS_Shared.MoveAlign(this.part.transform, partNode.nodeTransform, evaNodeTransform);
                }

                if (evaNodeTransform)
                {
                    Destroy(evaNodeTransform.gameObject);
                }
                if (evaJoint)
                {
                    Destroy(evaJoint);
                }

                this.part.transform.parent          = null;
                this.part.rigidbody.isKinematic     = false;
                this.part.physicalSignificance      = Part.PhysicalSignificance.FULL;
                this.part.rigidbody.velocity        = evaHolderPart.rigidbody.velocity;
                this.part.rigidbody.angularVelocity = evaHolderPart.rigidbody.angularVelocity;

                if (addPartMass & !physicJoint)
                {
                    evaHolderPart.mass = orgKerbalMass;
                }

                KASModuleWinch grabbedWinchHead = KAS_Shared.GetWinchModuleGrabbed(evaHolderPart.vessel);
                if (grabbedWinchHead)
                {
                    if (grabbedWinchHead.grabbedPortModule)
                    {
                        KAS_Shared.DebugLog("Drop - Grabbed part have a port connected");
                        grabbedWinchHead.PlugHead(grabbedWinchHead.grabbedPortModule, KASModuleWinch.PlugState.PlugDocked, fireSound: false);
                    }
                }

                evaJoint            = null;
                evaNodeTransform    = null;
                evaHolderVesselName = null;
                evaHolderPart       = null;
                grabbed             = false;

                RefreshContextMenu();

                //Send drop message to all child objects
                base.SendMessage("OnPartDropped", SendMessageOptions.DontRequireReceiver);
            }
            else
            {
                KAS_Shared.DebugWarning("Drop - Part not grabbed, ignoring drop...");
            }
        }
Ejemplo n.º 10
0
 private void UpdateWinchCableControl()
 {
     //Extend key pressed
     if (winchExtendKey != "")
     {
         if (Input.GetKeyDown(winchExtendKey.ToLower()))
         {
             KAS_Shared.SendMsgToWinch("EventWinchExtend", true, vess: FlightGlobals.ActiveVessel);
         }
         if (Input.GetKeyUp(winchExtendKey.ToLower()))
         {
             KAS_Shared.SendMsgToWinch("EventWinchExtend", false, vess: FlightGlobals.ActiveVessel);
         }
     }
     //Retract key pressed
     if (winchRetractKey != "")
     {
         if (Input.GetKeyDown(winchRetractKey.ToLower()))
         {
             KAS_Shared.SendMsgToWinch("EventWinchRetract", true, vess: FlightGlobals.ActiveVessel);
         }
         if (Input.GetKeyUp(winchRetractKey.ToLower()))
         {
             KAS_Shared.SendMsgToWinch("EventWinchRetract", false, vess: FlightGlobals.ActiveVessel);
         }
     }
     //Head left key pressed
     if (winchHeadLeftKey != "")
     {
         if (Input.GetKey(winchHeadLeftKey.ToLower()))
         {
             KAS_Shared.SendMsgToWinch("EventWinchHeadLeft", vess: FlightGlobals.ActiveVessel);
         }
     }
     //Head right key pressed
     if (winchHeadRightKey != "")
     {
         if (Input.GetKey(winchHeadRightKey.ToLower()))
         {
             KAS_Shared.SendMsgToWinch("EventWinchHeadRight", vess: FlightGlobals.ActiveVessel);
         }
     }
     //Eject key pressed
     if (winchEjectKey != "")
     {
         if (Input.GetKeyDown(winchEjectKey.ToLower()))
         {
             KAS_Shared.SendMsgToWinch("EventWinchEject", vess: FlightGlobals.ActiveVessel);
         }
     }
     //Hook key pressed
     if (winchHookKey != "")
     {
         if (Input.GetKeyDown(winchHookKey.ToLower()))
         {
             KAS_Shared.SendMsgToWinch("EventWinchHook", vess: FlightGlobals.ActiveVessel);
         }
     }
     //Eva Extend key pressed
     if (winchEvaExtendKey != "")
     {
         if (Input.GetKeyDown(winchEvaExtendKey.ToLower()))
         {
             KASModuleWinch grabbedWinchModule = KAS_Shared.GetWinchModuleGrabbed(FlightGlobals.ActiveVessel);
             if (grabbedWinchModule)
             {
                 grabbedWinchModule.EventWinchExtend(true);
             }
         }
         if (Input.GetKeyUp(winchEvaExtendKey.ToLower()))
         {
             KASModuleWinch grabbedWinchModule = KAS_Shared.GetWinchModuleGrabbed(FlightGlobals.ActiveVessel);
             if (grabbedWinchModule)
             {
                 grabbedWinchModule.EventWinchExtend(false);
             }
         }
     }
     //Eva Retract key pressed
     if (winchEvaRetractKey != "")
     {
         if (Input.GetKeyDown(winchEvaRetractKey.ToLower()))
         {
             KASModuleWinch grabbedWinchModule = KAS_Shared.GetWinchModuleGrabbed(FlightGlobals.ActiveVessel);
             if (grabbedWinchModule)
             {
                 grabbedWinchModule.EventWinchRetract(true);
             }
         }
         if (Input.GetKeyUp(winchEvaRetractKey.ToLower()))
         {
             KASModuleWinch grabbedWinchModule = KAS_Shared.GetWinchModuleGrabbed(FlightGlobals.ActiveVessel);
             if (grabbedWinchModule)
             {
                 grabbedWinchModule.EventWinchRetract(false);
             }
         }
     }
 }
Ejemplo n.º 11
0
        private void AttachOnCollision(Collision collision)
        {
            // Revert precision mode back to the performance. Non-discrete modes are very expensive.
            KAS_Shared.DebugLog(string.Format(
                                    "AttachOnCollision - Set collision mode back to Discrete on: {0}", part));
            part.Rigidbody.collisionDetectionMode = CollisionDetectionMode.Discrete;

            //Don't attach if inpact force is too low
            if (collision.relativeVelocity.magnitude < forceNeeded)
            {
                return;
            }

            float      shorterDist     = Mathf.Infinity;
            bool       nearestHitFound = false;
            Part       nearestHitPart  = null;
            RaycastHit nearestHit      = new RaycastHit();
            Vector3    rayDirection    = this.part.transform.TransformDirection(rayDir);
            //Get all raycast hits in front of the grapple
            var nearestHits = new List <RaycastHit>(
                Physics.RaycastAll(this.part.transform.position, rayDirection, rayLenght, 557059));

            foreach (RaycastHit hit in nearestHits)
            {
                //Exclude grapple collider
                if (hit.collider == this.part.collider)
                {
                    continue;
                }
                //Exclude parts if needed
                if (!attachToPart && hit.rigidbody && hit.rigidbody.GetComponent <Part>())
                {
                    continue;
                }

                // Get closest hit
                float tmpShorterDist = Vector3.Distance(this.part.transform.position, hit.point);
                if (tmpShorterDist <= shorterDist)
                {
                    shorterDist = tmpShorterDist;
                    nearestHit  = hit;
                    if (nearestHit.rigidbody)
                    {
                        nearestHitPart = nearestHit.rigidbody.GetComponent <Part>();
                    }
                    nearestHitFound = true;
                }
            }

            if (!nearestHitFound)
            {
                KAS_Shared.DebugLog("AttachOnCollision - Nothing to attach in front of grapple");
                return;
            }

            KASModuleWinch connectedWinch = KAS_Shared.GetConnectedWinch(this.part);

            if (connectedWinch)
            {
                MoveAbove(nearestHit.point, nearestHit.normal, aboveDist);
                connectedWinch.cableJointLength = connectedWinch.cableRealLenght;
            }

            if (nearestHitPart)
            {
                KAS_Shared.DebugLog("AttachOnCollision - grappleAttachOnPart=true");
                KAS_Shared.DebugLog("AttachOnCollision - Attaching to part : " + nearestHitPart.partInfo.title);
                AttachPartGrapple(nearestHitPart);
            }
            else
            {
                KAS_Shared.DebugLog("AttachOnCollision - Attaching to static : " + nearestHit.collider.name);
                AttachStaticGrapple();
            }
        }
Ejemplo n.º 12
0
        void OnGUI()
        {
            if (!clickedWinch)
            {
                return;
            }

            GUI.skin = HighLogic.Skin;
            GUI.skin.label.alignment  = TextAnchor.MiddleCenter;
            GUI.skin.button.alignment = TextAnchor.MiddleCenter;

            guiButtonStyle = new GUIStyle(GUI.skin.button);
            guiButtonStyle.normal.textColor   = guiButtonStyle.focused.textColor = Color.white;
            guiButtonStyle.hover.textColor    = guiButtonStyle.active.textColor = Color.yellow;
            guiButtonStyle.onNormal.textColor = guiButtonStyle.onFocused.textColor = guiButtonStyle.onHover.textColor = guiButtonStyle.onActive.textColor = Color.green;
            guiButtonStyle.padding            = new RectOffset(4, 4, 4, 4);
            guiButtonStyle.alignment          = TextAnchor.MiddleCenter;

            Vector3 headScreenPoint = Camera.main.WorldToScreenPoint(clickedWinch.headTransform.position);

            GUILayout.BeginArea(new Rect(headScreenPoint.x, Screen.height - headScreenPoint.y, 200, 200));
            GUILayout.BeginVertical();

            if (clickedWinch.evaHolderPart)
            {
                if (GUILayout.Button("Drop (Key " + grabHeadKey + ")", guiButtonStyle, GUILayout.Width(100f)))
                {
                    clickedWinch.DropHead();;
                    clickedWinch = null;
                }
            }
            else
            {
                if (GUILayout.Button("Grab (Key " + grabHeadKey + ")", guiButtonStyle, GUILayout.Width(100f)))
                {
                    clickedWinch.GrabHead(FlightGlobals.ActiveVessel);
                    clickedWinch = null;
                }
                if (clickedWinch)
                {
                    if (clickedWinch.headState == KASModuleWinch.PlugState.Deployed)
                    {
                        KASModuleGrab grabbedModule = KAS_Shared.GetGrabbedPartModule(FlightGlobals.ActiveVessel);
                        if (grabbedModule)
                        {
                            KASModulePort grabbedPort = grabbedModule.GetComponent <KASModulePort>();
                            if (grabbedPort)
                            {
                                if (GUILayout.Button("Plug grabbed", guiButtonStyle, GUILayout.Width(100f)))
                                {
                                    grabbedModule.Drop();
                                    grabbedPort.transform.rotation = Quaternion.FromToRotation(grabbedPort.portNode.forward, -clickedWinch.headPortNode.forward) * grabbedPort.transform.rotation;
                                    grabbedPort.transform.position = grabbedPort.transform.position - (grabbedPort.portNode.position - clickedWinch.headPortNode.position);
                                    clickedWinch.PlugHead(grabbedPort, KASModuleWinch.PlugState.PlugDocked);
                                    clickedWinch = null;
                                }
                            }
                        }
                    }
                }
            }
            GUILayout.EndHorizontal();
            GUILayout.EndArea();
        }
Ejemplo n.º 13
0
        private void AttachOnCollision(Collision collision)
        {
            //Don't attach if inpact force is too low
            if (collision.relativeVelocity.magnitude < forceNeeded)
            {
                return;
            }

            float      shorterDist     = Mathf.Infinity;
            bool       nearestHitFound = false;
            Part       nearestHitPart  = null;
            RaycastHit nearestHit      = new RaycastHit();
            Vector3    rayDirection    = this.part.transform.TransformDirection(rayDir);
            //Get all raycast hits in front of the grapple
            List <RaycastHit> nearestHits = new List <RaycastHit>(Physics.RaycastAll(this.part.transform.position, rayDirection, rayLenght, 557059));

            foreach (RaycastHit hit in nearestHits)
            {
                //Exclude grapple collider
                if (hit.collider == this.part.collider)
                {
                    continue;
                }
                //Exclude parts if needed
                if (!attachToPart)
                {
                    if (hit.rigidbody)
                    {
                        if (hit.rigidbody.GetComponent <Part>())
                        {
                            continue;
                        }
                    }
                }

                /*
                 * // Check forward dot
                 * float fwdDot = Mathf.Abs(Vector3.Dot(hit.normal, this.transform.up));
                 * if (fwdDot <= minFwdDot)
                 * {
                 *  continue;
                 * }
                 *
                 * // Check roll dot
                 * float rollDot = Vector3.Dot(hit.normal, this.transform.up);
                 * if (rollDot <= minRollDot)
                 * {
                 *  continue;
                 * }*/

                // Get closest hit
                float tmpShorterDist = Vector3.Distance(this.part.transform.position, hit.point);
                if (tmpShorterDist <= shorterDist)
                {
                    shorterDist = tmpShorterDist;
                    nearestHit  = hit;
                    if (nearestHit.rigidbody)
                    {
                        nearestHitPart = nearestHit.rigidbody.GetComponent <Part>();
                    }
                    nearestHitFound = true;
                }
            }

            if (!nearestHitFound)
            {
                KAS_Shared.DebugLog("AttachOnCollision - Nothing to attach in front of grapple");
                return;
            }

            KASModuleWinch connectedWinch = KAS_Shared.GetConnectedWinch(this.part);

            if (connectedWinch)
            {
                MoveAbove(nearestHit.point, nearestHit.normal, aboveDist);
                connectedWinch.cableJointLength = connectedWinch.cableRealLenght;
            }

            if (nearestHitPart)
            {
                KAS_Shared.DebugLog("AttachOnCollision - grappleAttachOnPart=true");
                KAS_Shared.DebugLog("AttachOnCollision - Attaching to part : " + nearestHitPart.partInfo.title);
                AttachPartGrapple(nearestHitPart, partBreakForce);
            }
            else
            {
                KAS_Shared.DebugLog("AttachOnCollision - Attaching to static : " + nearestHit.collider.name);
                AttachStaticGrapple(staticBreakForce);
            }
        }
Ejemplo n.º 14
0
        public void Drop(bool forAttach = false)
        {
            if (grabbed)
            {
                KAS_Shared.DebugLog("Drop - Dropping part :" + this.part.partInfo.name);

                base.SendMessage("OnPartDrop", SendMessageOptions.DontRequireReceiver);

                if (this.part.vessel.isEVA || grab_pending)
                {
                    this.part.decouple();
                }

                if (grab_pending)
                {
                    Destroy(evaNodeTransform.gameObject);
                    evaNodeTransform    = null;
                    evaHolderVesselName = null;
                    evaHolderPart       = null;
                    grabbed             = grab_pending = false;
                    RefreshContextMenu();
                    return;
                }

                //Remove created joints between eva and part if exist
                KAS_Shared.RemoveFixedJointBetween(this.part, evaHolderPart);
                KAS_Shared.RemoveHingeJointBetween(this.part, evaHolderPart);

                List <Collider> allColliders = new List <Collider>(this.part.GetComponentsInChildren <Collider>() as Collider[]);
                foreach (Collider col in allColliders)
                {
                    col.isTrigger = (keepTriggers != null && keepTriggers.Contains(col));
                }

                if (customGroundPos && evaHolderPart.checkLanded())
                {
                    KAS_Shared.MoveRelatedTo(this.part.transform, evaCollider.transform, dropPartPos, dropPartRot);
                }
                else
                {
                    KAS_Shared.MoveAlign(this.part.transform, partNode.nodeTransform, evaNodeTransform);
                }

                if (evaNodeTransform)
                {
                    Destroy(evaNodeTransform.gameObject);
                }
                if (evaJoint)
                {
                    Destroy(evaJoint);
                }

                this.part.rigidbody.velocity        = evaHolderPart.rigidbody.velocity;
                this.part.rigidbody.angularVelocity = evaHolderPart.rigidbody.angularVelocity;

                KAS_Shared.ResetCollisionEnhancer(this.part);

                if (addPartMass & !physicJoint)
                {
                    evaHolderPart.mass = orgKerbalMass;
                }

                KASModuleWinch grabbedWinchHead = KAS_Shared.GetWinchModuleGrabbed(evaHolderPart.vessel);
                if (grabbedWinchHead)
                {
                    if (grabbedWinchHead.grabbedPortModule && grabbedWinchHead.grabbedPortModule.part == part)
                    {
                        KAS_Shared.DebugLog("Drop - Grabbed part have a port connected");

                        if (forAttach)
                        {
                            // Docked causes big problems when the part is later coupled
                            grabbedWinchHead.PlugHead(grabbedWinchHead.grabbedPortModule, KASModuleWinch.PlugState.PlugUndocked, fireSound: false);
                        }
                        else
                        {
                            grabbedWinchHead.PlugHead(grabbedWinchHead.grabbedPortModule, KASModuleWinch.PlugState.PlugDocked, fireSound: false);
                        }
                    }
                }

                GameEvents.onCrewBoardVessel.Remove(new EventData <GameEvents.FromToAction <Part, Part> > .OnEvent(this.OnCrewBoardVessel));

                syncGrab            = false;
                keepTriggers        = null;
                evaJoint            = null;
                evaNodeTransform    = null;
                evaHolderVesselName = null;
                evaHolderPart       = null;
                grabbed             = grab_pending = false;

                RefreshContextMenu();

                //Send drop message to all child objects
                base.SendMessage("OnPartDropped", SendMessageOptions.DontRequireReceiver);
            }
            else
            {
                KAS_Shared.DebugWarning("Drop - Part not grabbed, ignoring drop...");
            }
        }
Ejemplo n.º 15
0
        private void GuiMainWindow(int windowID)
        {
            GuiStyles();
            GUILayout.Space(15);

            //Get all winches
            if (allWinchModule == null)
            {
                allWinchModule = GameObject.FindObjectsOfType(typeof(KASModuleWinch)) as KASModuleWinch[];
            }

            //Default selection / Force selection of the first system if no system are selected
            if (selectedWinchModule == null || selectedWinchModule.vessel != FlightGlobals.ActiveVessel)
            {
                foreach (KASModuleWinch winchModule in allWinchModule)
                {
                    if (winchModule.vessel == FlightGlobals.ActiveVessel)
                    {
                        selectedWinchModule = winchModule;
                        break;
                    }
                }
            }

            #region System loop
            //scrollPos = GUILayout.BeginScrollView(scrollPos, guiDataboxStyle, GUILayout.Width(800f), GUILayout.Height(scrollHeight));
            GUILayout.BeginVertical(guiDataboxStyle);
            int i = 0;
            foreach (KASModuleWinch winchModule in allWinchModule)
            {
                if (winchModule.vessel != FlightGlobals.ActiveVessel || !winchModule.isActive)
                {
                    continue;
                }

                GUILayout.BeginHorizontal();

                string sysname;
                if (winchModule.winchName != "" && winchModule.winchName != null)
                {
                    sysname = winchModule.winchName;
                }
                else
                {
                    sysname = "Winch(" + i + ")";
                    i++;
                }

                #region System title & selection
                GUILayout.BeginVertical();
                if (winchModule == selectedWinchModule)
                {
                    GUILayout.Label(new GUIContent("> " + sysname, "Selected KAS System"), guiBoldCenterStyle, GUILayout.Width(150f));
                }
                else
                {
                    GUILayout.Label(new GUIContent("  " + sysname, "KAS System"), guiCenterStyle, GUILayout.Width(150f));
                }

                if ((Event.current.type == EventType.repaint) && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
                {
                    if (Input.GetMouseButtonDown(0))
                    {
                        selectedWinchModule = winchModule;
                    }
                    if (!winchModule.highLightStarted)
                    {
                        winchModule.part.SetHighlight(true);
                        winchModule.highLightStarted = true;
                    }
                }
                else
                {
                    if (winchModule.highLightStarted)
                    {
                        winchModule.part.SetHighlight(false);
                        winchModule.highLightStarted = false;
                    }
                }

                GUILayout.EndVertical();
                #endregion

                #region Cable control


                //release
                winchModule.release.active = GUILayout.Toggle(winchModule.release.active, new GUIContent("Release", "Release connector/hook"), guiButtonStyle, GUILayout.Width(60f));

                //Eject
                if (!winchModule.ejectEnabled || winchModule.headState != KASModuleWinch.PlugState.Locked)
                {
                    GUI.enabled = false;
                }
                if (GUILayout.Button(new GUIContent("Eject", "Eject connector/hook"), guiButtonStyle, GUILayout.Width(40f)))
                {
                    winchModule.Eject();
                }
                GUI.enabled = true;

                //Retract
                if (winchModule.extend.active)
                {
                    GUI.enabled = false;
                }

                winchModule.retract.active = GUILayout.Toggle(winchModule.retract.active, new GUIContent("<<", "Toggle retract"), guiButtonStyle);

                if (GUILayout.RepeatButton(new GUIContent("<", "Retract"), guiButtonStyle))
                {
                    winchModule.guiRepeatRetract = true;
                    winchModule.retract.active   = true;
                }
                else if (winchModule.guiRepeatRetract)
                {
                    winchModule.guiRepeatRetract = false;
                    winchModule.retract.active   = false;
                }

                GUI.enabled = true;

                //Cable length
                GUI.skin.label.alignment = TextAnchor.MiddleCenter;
                if (winchModule.cableJoint)
                {
                    GUILayout.Label(new GUIContent(winchModule.cableJoint.maxDistance.ToString("0.00"), "Current cable length"), guiYellowStyle, GUILayout.Width(40f));
                    float strainDistance    = winchModule.cableJoint.maxDistance - winchModule.cableRealLenght;
                    float warningPercentage = 10;
                    float warningDistance   = (winchModule.cableJoint.maxDistance / 100) * warningPercentage;

                    GUILayout.Label("|", guiCenterStyle);

                    if (strainDistance < 0)
                    {
                        GUILayout.Label(new GUIContent(strainDistance.ToString("0.00"), "Cable is under strain"), guiMagentaStyle, GUILayout.Width(40f));
                    }
                    else if (strainDistance < warningDistance)
                    {
                        GUILayout.Label(new GUIContent(strainDistance.ToString("0.00"), "Distance before strain"), guiYellowStyle, GUILayout.Width(40f));
                    }
                    else if (strainDistance > warningDistance)
                    {
                        GUILayout.Label(new GUIContent(strainDistance.ToString("0.00"), "Distance before strain"), guigreenStyle, GUILayout.Width(40f));
                    }
                }
                else
                {
                    GUILayout.Label(new GUIContent("Retracted", "Cable is retracted and locked"), guigreenStyle, GUILayout.Width(93f));
                }

                //Extend
                if (winchModule.retract.active)
                {
                    GUI.enabled = false;
                }

                if (GUILayout.RepeatButton(new GUIContent(">", "Extend"), guiButtonStyle))
                {
                    winchModule.extend.active   = true;
                    winchModule.guiRepeatExtend = true;
                }
                else if (winchModule.guiRepeatExtend)
                {
                    winchModule.guiRepeatExtend = false;
                    winchModule.extend.active   = false;
                }

                winchModule.extend.active = GUILayout.Toggle(winchModule.extend.active, new GUIContent(">>", "Toggle extend"), guiButtonStyle);
                GUI.enabled = true;



                //
                winchModule.motorSpeedSetting = GUILayout.HorizontalSlider(winchModule.motorSpeedSetting, 0, winchModule.motorMaxSpeed, GUILayout.Width(100f));
                GUI.Box(GUILayoutUtility.GetLastRect(), new GUIContent("", "Motor speed setting"));
                GUILayout.Label(new GUIContent(winchModule.motorSpeed.ToString("0.00") + " / " + winchModule.motorSpeedSetting.ToString("0.00"), "Current motor speed / Motor speed setting"), guiCenterStyle, GUILayout.Width(90f));

                if (GUILayout.RepeatButton(new GUIContent("<", "Turn connected port to left"), guiButtonStyle))
                {
                    winchModule.EventWinchHeadLeft();
                    winchModule.guiRepeatTurnLeft = true;
                }
                else if (winchModule.guiRepeatTurnLeft)
                {
                    winchModule.guiRepeatTurnLeft = false;
                }

                if (GUILayout.RepeatButton(new GUIContent(">", "Turn connected port to right"), guiButtonStyle))
                {
                    winchModule.EventWinchHeadRight();
                    winchModule.guiRepeatTurnRight = true;
                }
                else if (winchModule.guiRepeatTurnRight)
                {
                    winchModule.guiRepeatTurnRight = false;
                }

                #endregion

                #region Winch & Connector & Hook controls

                if (winchModule.headState == KASModuleWinch.PlugState.Deployed || winchModule.headState == KASModuleWinch.PlugState.Locked)
                {
                    GUI.enabled = false;
                }
                winchModule.PlugDocked = GUILayout.Toggle(winchModule.PlugDocked, new GUIContent("Docked", "Plug mode"), guiButtonStyle, GUILayout.Width(60f));
                if (GUILayout.Button(new GUIContent("Unplug", "Unplug"), guiButtonStyle, GUILayout.Width(60f)))
                {
                    winchModule.UnplugHead();
                }
                GUI.enabled = true;

                KASModuleMagnet        moduleHookMagnet  = winchModule.GetHookMagnet();
                KASModuleSuctionCup    moduleHookSuction = winchModule.GetHookSuction();
                KASModuleGrapplingHook moduleHookGrapple = winchModule.GetHookGrapple();

                if (moduleHookMagnet)
                {
                    moduleHookMagnet.MagnetActive = GUILayout.Toggle(moduleHookMagnet.MagnetActive, new GUIContent("Magnet", "Magnet On/Off"), guiButtonStyle, GUILayout.Width(60f));
                }

                if (moduleHookSuction)
                {
                    if (!moduleHookSuction.attachMode.FixedJoint)
                    {
                        GUI.enabled = false;
                    }
                    if (GUILayout.Button(new GUIContent("Detach", "Detach attached object(s)"), guiButtonStyle, GUILayout.Width(60f)))
                    {
                        moduleHookSuction.DetachSuction();
                    }
                    GUI.enabled = true;
                }

                if (moduleHookGrapple)
                {
                    if (!moduleHookGrapple.attachMode.StaticJoint && !moduleHookGrapple.attachMode.FixedJoint)
                    {
                        GUI.enabled = false;
                    }
                    if (GUILayout.Button(new GUIContent("Detach", "Detach from ground or part"), guiButtonStyle, GUILayout.Width(60f)))
                    {
                        moduleHookGrapple.Detach();
                    }
                    GUI.enabled = true;
                }

                if (!moduleHookMagnet && !moduleHookSuction && !moduleHookGrapple)
                {
                    GUI.enabled = false;
                    GUILayout.Button(new GUIContent("-", "Nothing connected or hook not supported"), guiButtonStyle, GUILayout.Width(60f));
                    GUI.enabled = true;
                }


                #endregion

                GUILayout.EndHorizontal();
            }
            GUILayout.EndVertical();
            //GUILayout.EndScrollView();
            #endregion

            #region GUI - Close
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Close", guiButtonStyle, GUILayout.Width(60f)))
            {
                GuiActive = false;
            }

            remameActived = GUILayout.Toggle(remameActived, new GUIContent("Rename", "Rename a winch"), guiButtonStyle, GUILayout.Width(60f));
            if (remameActived)
            {
                tempWinchName = GUILayout.TextField(tempWinchName, GUILayout.Width(120f));
                if (GUILayout.Button(new GUIContent("Set", "Set selected winch name to current text"), guiButtonStyle, GUILayout.Width(60f)))
                {
                    selectedWinchModule.winchName = tempWinchName;
                    remameActived = false;
                }
            }

            GUILayout.EndHorizontal();
            #endregion

            #region GUI - Tooltip & Drag windows
            GUI.Label(new Rect(0, 18, guiWindowPos.width, 30), GUI.tooltip, guiTooltipStyle);
            GUI.DragWindow();
            #endregion
        }
Ejemplo n.º 16
0
        public void Grab(Vessel kerbalEvaVessel)
        {
            KAS_Shared.DebugLog("Grab - Grabbing part :" + this.part.partInfo.name);

            //Get eva transform
            evaCollider = KAS_Shared.GetEvaCollider(kerbalEvaVessel, evaTransformName);
            if (!evaCollider)
            {
                KAS_Shared.DebugLog("Grab - " + evaTransformName + "transform not found on eva !");
                return;
            }

            //Get attach node
            if (attachNodeName == null || attachNodeName == "")
            {
                if (this.part.srfAttachNode == null)
                {
                    KAS_Shared.DebugLog("Grab - surface attach node cannot be found on the part !");
                    return;
                }
                KAS_Shared.AddNodeTransform(this.part, this.part.srfAttachNode);
                partNode = this.part.srfAttachNode;
            }
            else
            {
                AttachNode an = this.part.findAttachNode(attachNodeName);
                if (an == null)
                {
                    KAS_Shared.DebugLog("Grab - " + attachNodeName + " node cannot be found on the part !");
                    return;
                }
                KAS_Shared.AddNodeTransform(this.part, an);
                partNode = an;
            }

            //Send message to other modules
            base.SendMessage("OnPartGrab", kerbalEvaVessel, SendMessageOptions.DontRequireReceiver);

            //Drop grabbed part on eva if needed
            KASModuleGrab tmpGrabbbedPartModule = KAS_Shared.GetGrabbedPartModule(kerbalEvaVessel);

            if (tmpGrabbbedPartModule)
            {
                KAS_Shared.DebugWarning("Grab - Drop current grabbed part");
                tmpGrabbbedPartModule.Drop();
            }

            evaNodeTransform               = new GameObject("KASEvaNode").transform;
            evaNodeTransform.parent        = evaCollider.transform;
            evaNodeTransform.localPosition = evaPartPos;
            evaNodeTransform.rotation      = KAS_Shared.DirectionToQuaternion(evaCollider.transform, evaPartDir);

            KAS_Shared.MoveAlign(this.part.transform, partNode.nodeTransform, evaNodeTransform);

            //Grab winch connected head if any
            KASModuleWinch moduleWinch = KAS_Shared.GetConnectedWinch(this.part);

            if (moduleWinch)
            {
                KASModulePort modulePort = this.part.GetComponent <KASModulePort>();
                moduleWinch.UnplugHead(false);
                moduleWinch.GrabHead(kerbalEvaVessel, modulePort);
            }

            List <Collider> allColliders = new List <Collider>(this.part.GetComponentsInChildren <Collider>() as Collider[]);

            foreach (Collider col in allColliders)
            {
                col.isTrigger = true;
            }

            Detach();
            KAS_Shared.DecoupleFromAll(this.part);
            this.part.Couple(kerbalEvaVessel.rootPart);
            //Destroy joint to avoid buggy eva move
            Destroy(this.part.attachJoint);

            this.part.rigidbody.velocity = kerbalEvaVessel.rootPart.rigidbody.velocity;

            if (physicJoint)
            {
                if (evaJoint)
                {
                    Destroy(evaJoint);
                }
                evaJoint = this.part.gameObject.AddComponent <FixedJoint>();
                evaJoint.connectedBody = evaCollider.attachedRigidbody;
                evaJoint.breakForce    = 5;
                evaJoint.breakTorque   = 5;
            }
            else
            {
                this.part.physicalSignificance  = Part.PhysicalSignificance.NONE;
                this.part.transform.parent      = evaNodeTransform;
                this.part.rigidbody.isKinematic = true;
            }

            //Add grabbed part mass to eva
            if (addPartMass && !physicJoint)
            {
                orgKerbalMass = kerbalEvaVessel.rootPart.mass;
                kerbalEvaVessel.rootPart.mass += this.part.mass;
            }

            evaHolderVesselName = kerbalEvaVessel.vesselName;
            evaHolderPart       = kerbalEvaVessel.rootPart;
            grabbed             = true;

            RefreshContextMenu();

            //Play grab sound
            fxSndGrab.audio.Play();
            base.SendMessage("OnPartGrabbed", kerbalEvaVessel, SendMessageOptions.DontRequireReceiver);
        }
Ejemplo n.º 17
0
        public void Grab(Vessel kerbalEvaVessel)
        {
            KAS_Shared.DebugLog("Grab - Grabbing part :" + this.part.partInfo.name);

            if (!AlignEvaPosition(kerbalEvaVessel))
            {
                return;
            }

            //Grab winch connected head if any
            KASModuleWinch moduleWinch = KAS_Shared.GetConnectedWinch(this.part);

            if (moduleWinch)
            {
                KASModulePort modulePort = this.part.GetComponent <KASModulePort>();
                moduleWinch.UnplugHead(false);
                moduleWinch.GrabHead(kerbalEvaVessel, modulePort);
            }

            keepTriggers = new List <Collider>();

            List <Collider> allColliders = new List <Collider>(this.part.GetComponentsInChildren <Collider>() as Collider[]);

            foreach (Collider col in allColliders)
            {
                if (col.isTrigger)
                {
                    keepTriggers.Add(col);
                }

                col.isTrigger = true;
            }

            Detach();

            if (this.part.vessel != kerbalEvaVessel)
            {
                KAS_Shared.DecoupleFromAll(this.part);
                this.part.Couple(kerbalEvaVessel.rootPart);
            }
            else
            {
                if (this.part.parent != kerbalEvaVessel.rootPart)
                {
                    this.part.setParent(null);
                    this.part.setParent(kerbalEvaVessel.rootPart);
                }
                this.part.PromoteToPhysicalPart();
            }

            //Destroy joint to avoid buggy eva move
            Destroy(this.part.attachJoint);

            this.part.rigidbody.velocity = kerbalEvaVessel.rootPart.rigidbody.velocity;

            if (physicJoint)
            {
                if (evaJoint)
                {
                    Destroy(evaJoint);
                }
                evaJoint = this.part.gameObject.AddComponent <FixedJoint>();
                evaJoint.connectedBody = evaCollider.attachedRigidbody;
                evaJoint.breakForce    = 5;
                evaJoint.breakTorque   = 5;
                KAS_Shared.ResetCollisionEnhancer(this.part);
            }
            else
            {
                this.part.physicalSignificance  = Part.PhysicalSignificance.NONE;
                this.part.transform.parent      = evaNodeTransform;
                this.part.rigidbody.isKinematic = true;
                KAS_Shared.ResetCollisionEnhancer(this.part, false);
            }

            //Add grabbed part mass to eva
            if (addPartMass && !physicJoint)
            {
                orgKerbalMass = kerbalEvaVessel.rootPart.mass;
                kerbalEvaVessel.rootPart.mass += this.part.mass;
            }

            GameEvents.onCrewBoardVessel.Add(new EventData <GameEvents.FromToAction <Part, Part> > .OnEvent(this.OnCrewBoardVessel));

            evaHolderVesselName = kerbalEvaVessel.vesselName;
            evaHolderPart       = kerbalEvaVessel.rootPart;
            grabbed             = true;
            grab_pending        = false;

            RefreshContextMenu();

            //Play grab sound
            fxSndGrab.audio.Play();
            base.SendMessage("OnPartGrabbed", kerbalEvaVessel, SendMessageOptions.DontRequireReceiver);
        }
Ejemplo n.º 18
0
        public void UpdatePointer()
        {
            if (!running)
            {
                if (pointer)
                {
                    UnityEngine.Object.Destroy(pointer);
                }
                return;
            }

            //Cast ray
            Ray        ray = FlightCamera.fetch.mainCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (!Physics.Raycast(ray, out hit, 500, 557059))
            {
                if (pointer)
                {
                    UnityEngine.Object.Destroy(pointer);
                }
                return;
            }

            //Create pointer if needed
            if (!pointer)
            {
                GameObject modelGo = partToAttach.FindModelTransform("model").gameObject;
                pointer = Mesh.Instantiate(modelGo) as GameObject;
                foreach (Collider col in pointer.GetComponentsInChildren <Collider>())
                {
                    UnityEngine.Object.Destroy(col);
                }

                allModelMr = new List <MeshRenderer>();
                // Remove attached tube mesh renderer if any
                List <MeshRenderer> tmpAllModelMr = new List <MeshRenderer>(pointer.GetComponentsInChildren <MeshRenderer>() as MeshRenderer[]);
                foreach (MeshRenderer mr in tmpAllModelMr)
                {
                    if (mr.name == "KAStube" || mr.name == "KASsrcSphere" || mr.name == "KASsrcTube" || mr.name == "KAStgtSphere" || mr.name == "KAStgtTube")
                    {
                        Destroy(mr);
                        continue;
                    }
                    allModelMr.Add(mr);
                    mr.material = new Material(Shader.Find("Transparent/Diffuse"));
                }
                pointerNodeTransform               = new GameObject("KASPointerPartNode").transform;
                pointerNodeTransform.parent        = pointer.transform;
                pointerNodeTransform.localPosition = partToAttach.srfAttachNode.position;
                pointerNodeTransform.localRotation = Quaternion.Inverse(Quaternion.LookRotation(partToAttach.srfAttachNode.orientation, Vector3.up));
            }

            //Set default color
            Color color = Color.green;

            // Check if object is valid
            bool      isValidObj = false;
            Part      hitPart    = null;
            KerbalEVA hitEva     = null;

            if (hit.rigidbody)
            {
                hitPart = hit.rigidbody.GetComponent <Part>();
                hitEva  = hit.rigidbody.GetComponent <KerbalEVA>();
                if (hitPart && allowPart && !hitEva & hitPart != partToAttach)
                {
                    isValidObj = true;
                }
                if (hitEva && allowEva)
                {
                    isValidObj = true;
                }
            }
            if (!hitPart && !hitEva && allowStatic)
            {
                isValidObj = true;
            }

            //Check distance
            bool isValidSourceDist = true;

            if (sourceTransform)
            {
                isValidSourceDist = Vector3.Distance(FlightGlobals.ActiveVessel.transform.position, sourceTransform.position) <= maxDist;
            }
            bool isValidTargetDist = Vector3.Distance(FlightGlobals.ActiveVessel.transform.position, hit.point) <= maxDist;

            //Set color
            if (!isValidObj)
            {
                color = Color.red;
            }
            else if (!isValidSourceDist || !isValidTargetDist)
            {
                color = Color.yellow;
            }
            color.a = 0.5f;
            foreach (MeshRenderer mr in allModelMr)
            {
                mr.material.color = color;
            }

            //Rotation keys
            Vector3 delta = new Vector3(0, 0, 1);

            if (Input.GetKey(KeyCode.LeftAlt))
            {
                delta = new Vector3(1, 0, 0);
            }
            else if (Input.GetKey(KeyCode.RightAlt))
            {
                delta = new Vector3(0, -1, 0);
            }

            if (Input.GetKeyDown(KASAddonControlKey.rotateLeftKey.ToLower()))
            {
                customRot -= delta * 15;
            }
            if (Input.GetKeyDown(KASAddonControlKey.rotateRightKey.ToLower()))
            {
                customRot += delta * 15;
            }

            Quaternion rotAdjust = Quaternion.Euler(0, 0, customRot.z) * Quaternion.Euler(customRot.x, customRot.y, 0);

            KAS_Shared.MoveAlign(pointer.transform, pointerNodeTransform, hit, rotAdjust);

            //Attach on click
            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                KAS_Shared.DebugLog("Attachment started...");
                if (!isValidObj)
                {
                    ScreenMessages.PostScreenMessage("Can't attach, target is not allowed !");
                    audioBipWrong.Play();
                    return;
                }

                if (!isValidSourceDist)
                {
                    ScreenMessages.PostScreenMessage("Can't attach, too far from source !");
                    audioBipWrong.Play();
                    return;
                }

                if (!isValidTargetDist)
                {
                    ScreenMessages.PostScreenMessage("Can't attach, too far from target !");
                    audioBipWrong.Play();
                    return;
                }

                KASModuleGrab modulegrab = partToAttach.GetComponent <KASModuleGrab>();


                //Move and attach mode
                if (pointerMode == PointerMode.MoveAndAttach)
                {
                    // Drop and detach part if needed
                    if (modulegrab)
                    {
                        if (modulegrab.grabbed)
                        {
                            modulegrab.Drop();
                        }
                        modulegrab.Detach();
                    }

                    KASModuleWinch connectedWinch = KAS_Shared.GetConnectedWinch(partToAttach);
                    if (!connectedWinch)
                    {
                        KAS_Shared.DecoupleFromAll(partToAttach);
                    }

                    //Move part
                    partToAttach.transform.position = pointer.transform.position;
                    partToAttach.transform.rotation = pointer.transform.rotation;

                    if (connectedWinch)
                    {
                        //Set cable lenght to real lenght
                        connectedWinch.cableJointLength = connectedWinch.cableRealLenght;
                    }

                    KAS_Shared.ResetCollisionEnhancer(partToAttach);

                    if (msgOnly)
                    {
                        KAS_Shared.DebugLog("UpdatePointer(Pointer) Attach using send message");
                        if (hitPart)
                        {
                            partToAttach.SendMessage("OnAttachPart", hitPart, SendMessageOptions.DontRequireReceiver);
                        }
                        else
                        {
                            partToAttach.SendMessage("OnAttachStatic", SendMessageOptions.DontRequireReceiver);
                        }
                    }
                    else
                    {
                        KAS_Shared.DebugLog("UpdatePointer(Pointer) Attach with couple or static method");
                        if (!hitPart && !hitEva)
                        {
                            if (modulegrab)
                            {
                                modulegrab.AttachStatic();
                                modulegrab.fxSndAttachStatic.audio.Play();
                            }
                            else
                            {
                                KAS_Shared.DebugWarning("UpdatePointer(Pointer) No grab module found, part cannot be attached on static");
                            }
                        }
                        else
                        {
                            partToAttach.Couple(hitPart);
                            if (modulegrab)
                            {
                                modulegrab.fxSndAttachPart.audio.Play();
                            }
                            else
                            {
                                KAS_Shared.DebugWarning("UpdatePointer(Pointer) No grab module found, cannot fire sound");
                            }
                        }
                        partToAttach.SendMessage("OnAttach", SendMessageOptions.DontRequireReceiver);
                    }
                }

                if (pointerMode == PointerMode.CopyAndAttach)
                {
                    // Not tested !
                    Part newPart = KAS_Shared.CreatePart(partToAttach.partInfo, pointer.transform.position, pointer.transform.rotation, partToAttach);
                    if (msgOnly)
                    {
                        if (hitPart)
                        {
                            StartCoroutine(WaitAndSendMsg(newPart, pointer.transform.position, pointer.transform.rotation, hitPart));
                        }
                        else
                        {
                            StartCoroutine(WaitAndSendMsg(newPart, pointer.transform.position, pointer.transform.rotation));
                        }
                    }
                    else
                    {
                        if (!hitPart && !hitEva)
                        {
                            StartCoroutine(WaitAndAttach(newPart, pointer.transform.position, pointer.transform.rotation, hitPart));
                        }
                        else
                        {
                            StartCoroutine(WaitAndAttach(newPart, pointer.transform.position, pointer.transform.rotation));
                        }
                    }
                }
                running = false;
            }
        }
Ejemplo n.º 19
0
        private IEnumerator GrabCoroutine(Vessel kerbalEvaVessel)
        {
            KAS_Shared.DebugLog("Grab - Grabbing part :" + this.part.partInfo.name);
            //Send message to other modules
            base.SendMessage("OnPartGrab", kerbalEvaVessel, SendMessageOptions.DontRequireReceiver);

            //Set attach node on EVA
            SetEvaNode(kerbalEvaVessel);

            //Drop grabbed eva part if any
            KASModuleGrab grabbbedPartModule = KAS_Shared.GetGrabbedPartModule(kerbalEvaVessel);

            if (grabbbedPartModule)
            {
                grabbbedPartModule.Drop();
            }

            //Unplug winch connected head if any
            KASModuleWinch moduleWinch = KAS_Shared.GetConnectedWinch(this.part);

            if (moduleWinch)
            {
                moduleWinch.UnplugHead(false);
            }

            //Disable all colliders on part
            DisableColliders();

            //Detach if needed
            Detach();

            //Decouple part (if not already done, in case of loading after a save with the part grabbed)
            if (this.part.vessel != kerbalEvaVessel)
            {
                KAS_Shared.DecoupleFromAll(this.part);
            }

            //Wait decouple action (x64 fix)
            yield return(new WaitForFixedUpdate());

            //Move part to eva node
            KAS_Shared.MoveAlign(this.part.transform, partNode.nodeTransform, evaNodeTransform);

            //Grab winch connected head if any
            if (moduleWinch)
            {
                KASModulePort modulePort = this.part.GetComponent <KASModulePort>();
                moduleWinch.GrabHead(kerbalEvaVessel, modulePort);
            }

            //Couple part to eva (if not already done, in case of loading after a save with the part grabbed)
            if (this.part.vessel != kerbalEvaVessel)
            {
                this.part.Couple(kerbalEvaVessel.rootPart);
            }

            //Destroy joint to avoid buggy eva move
            if (this.part.attachJoint)
            {
                this.part.attachJoint.DestroyJoint();
            }

            //Set part to physic join or kinematic with parent
            if (physicJoint)
            {
                if (evaJoint)
                {
                    Destroy(evaJoint);
                }
                evaJoint = this.part.gameObject.AddComponent <FixedJoint>();
                evaJoint.connectedBody = evaCollider.attachedRigidbody;
                evaJoint.breakForce    = 5;
                evaJoint.breakTorque   = 5;
                KAS_Shared.ResetCollisionEnhancer(this.part);
            }
            else
            {
                syncGrab = true;
                KAS_Shared.ResetCollisionEnhancer(this.part, false);
            }

            //Add grabbed part mass to eva
            if (addPartMass && !physicJoint)
            {
                orgKerbalMass = kerbalEvaVessel.rootPart.mass;
                kerbalEvaVessel.rootPart.mass += this.part.mass;
            }

            //Add event
            GameEvents.onCrewBoardVessel.Add(new EventData <GameEvents.FromToAction <Part, Part> > .OnEvent(this.OnCrewBoardVessel));

            //Set variables
            evaHolderVesselName = kerbalEvaVessel.vesselName;
            evaHolderPart       = kerbalEvaVessel.rootPart;
            grabbed             = true;
            grab_pending        = false;

            //Refresh Context Menu
            RefreshContextMenu();

            //Play grab sound
            fxSndGrab.audio.Play();

            //Send message to other modules
            base.SendMessage("OnPartGrabbed", kerbalEvaVessel, SendMessageOptions.DontRequireReceiver);
        }