public Task <IChunkColumn> GetChunk(ChunkWorldPos pos)
        {
            IWorld world          = AttachedObject.GetWorld();
            var    chunkColumnKey = world.MakeAddressByPartitionKey(new ChunkWorldPos(pos.X, pos.Z));

            return(Task.FromResult(GrainFactory.GetGrain <IChunkColumn>(chunkColumnKey)));
        }
        protected override void OnEnter(PlayerInfo player)
        {
            if (TriggerOwner._state != CosmicInflationController.State.ReadyToCollapse)
            {
                return;
            }

            if (player.IsLocalPlayer)
            {
                AttachedObject.OnEntry -= OnEnterEvent;

                AttachedObject.SetTriggerActivation(false);
                TriggerOwner._probeDestroyTrigger.SetTriggerActivation(false);

                var repelVolume = (WhiteHoleFluidVolume)TriggerOwner._repelVolume;
                repelVolume._flowSpeed        = -repelVolume._flowSpeed;
                repelVolume._massiveFlowSpeed = -repelVolume._massiveFlowSpeed;
                repelVolume.SetVolumeActivation(true);
                QSBPlayerManager.HideAllPlayers();

                ReticleController.Hide();
                Locator.GetFlashlight().TurnOff(false);
                Locator.GetPromptManager().SetPromptsVisible(false);
                OWInput.ChangeInputMode(InputMode.None);
            }
            else
            {
                player.SetVisible(false, .3f);
            }

            if (Occupants.Count == QSBPlayerManager.PlayerList.Count)
            {
                StartCollapse();
            }
        }
 protected override void OnAttached()
 {
     _loaded      = false;
     _chunkLoader = GrainFactory.GetGrain <IUserChunkLoader>(AttachedObject.GetPrimaryKey());
     AttachedObject.RegisterPropertyChangedHandler(ViewDistanceComponent.ViewDistanceProperty, OnViewDistanceChanged);
     AttachedObject.GetComponent <GameTickComponent>().Tick += OnGameTick;
 }
        async Task IHandle <PlayerLoggedIn> .Handle(PlayerLoggedIn message)
        {
            _loaded = false;
            await _chunkLoader.JoinGame(AttachedObject.GetWorld(), AttachedObject);

            _loaded = true;
        }
 Task IHandle <BeginLogin> .Handle(BeginLogin message)
 {
     AttachedObject.GetComponent <GameTickComponent>()
     .Tick    -= OnGameTick;
     _isOnline = false;
     return(Task.CompletedTask);
 }
Beispiel #6
0
        private void OnEntityWorldPositionChanged(object sender, PropertyChangedEventArgs <EntityWorldPos> e)
        {
            var generator = AttachedObject.GetComponent <ClientboundPacketComponent>().GetGenerator();

            // Update Collider
            var pos = e.NewValue;
            var box = new Cuboid(new Point3d(pos.X, pos.Z, pos.Y), new Size(0.6f, 0.6f, 1.75f));

            AttachedObject.SetLocalValue(ColliderComponent.ColliderShapeProperty, box);

            // Check if we need to send UpdateViewPosition packet. If the player walk cross chunk borders, send it.
            var oldChunkPos = e.OldValue.ToChunkWorldPos();
            var newChunkPos = e.NewValue.ToChunkWorldPos();

            if (oldChunkPos != newChunkPos)
            {
                generator.UpdateViewPosition(newChunkPos.X, newChunkPos.Z);
            }

            // Broadcast to trackers
            _broadcastComponent = _broadcastComponent ?? AttachedObject.GetComponent <ChunkEventBroadcastComponent>();
            _broadcastComponent.GetGenerator(AttachedObject)
            .EntityRelativeMove(
                AttachedObject.EntityId,
                GetDelta(e.OldValue.X, e.NewValue.X),
                GetDelta(e.OldValue.Y, e.NewValue.Y),
                GetDelta(e.OldValue.Z, e.NewValue.Z),
                AttachedObject.GetValue(EntityOnGroundComponent.IsOnGroundProperty));
        }
Beispiel #7
0
        public void PreviousSlide()
        {
            var hasChangedSlide = false;

            if (AttachedObject._slideItem != null && AttachedObject._slideItem.slidesContainer.PrevSlideAvailable())
            {
                hasChangedSlide = AttachedObject._slideItem.slidesContainer.DecreaseSlideIndex();
                if (hasChangedSlide)
                {
                    if (AttachedObject._oneShotSource != null)
                    {
                        AttachedObject._oneShotSource.PlayOneShot(AudioType.Projector_Prev);
                    }

                    if (AttachedObject.IsProjectorFullyLit())
                    {
                        AttachedObject._slideItem.slidesContainer.SetCurrentRead();
                        AttachedObject._slideItem.slidesContainer.TryPlayMusicForCurrentSlideTransition(false);
                    }
                }
            }

            if (AttachedObject._gearInterface != null)
            {
                var audioVolume = hasChangedSlide ? 0f : 0.5f;
                AttachedObject._gearInterface.AddRotation(-45f, audioVolume);
            }
        }
        public void SetRepaired()
        {
            if (!AttachedObject._damaged)
            {
                return;
            }

            DebugLog.DebugWrite($"[SATELLITE NODE] {AttachedObject} Set repaired.");
            AttachedObject._damaged = false;
            var component = Locator.GetPlayerTransform().GetComponent <ReferenceFrameTracker>();

            if (component.GetReferenceFrame() == AttachedObject._rfVolume.GetReferenceFrame())
            {
                component.UntargetReferenceFrame();
            }

            if (AttachedObject._rfVolume != null)
            {
                AttachedObject._rfVolume.gameObject.SetActive(false);
            }

            if (AttachedObject._lanternLight != null)
            {
                AttachedObject._lanternLight.color = AttachedObject._lightRepairedColor;
            }

            if (AttachedObject._lanternEmissiveRenderer != null)
            {
                AttachedObject._lanternEmissiveRenderer.sharedMaterials.CopyTo(AttachedObject._lanternMaterials, 0);
                AttachedObject._lanternMaterials[AttachedObject._lanternMaterialIndex] = AttachedObject._lanternRepairedMaterial;
                AttachedObject._lanternEmissiveRenderer.sharedMaterials = AttachedObject._lanternMaterials;
            }

            AttachedObject.RaiseEvent(nameof(AttachedObject.OnRepaired), AttachedObject);
        }
        protected override Task SendSpawnPacket(ClientPlayPacketGenerator generator)
        {
            MobType type = AttachedObject.GetComponent <MobTypeComponent>().MobType;

            return(generator.SpawnMob(AttachedObject.EntityId, AttachedObject.UUID, (byte)type, AttachedObject.Position, AttachedObject.Pitch, AttachedObject.Yaw, new EntityMetadata.Entity {
            }));
        }
Beispiel #10
0
        public int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, ref IntPtr lpBuffer, int nSize, IntPtr arguments)
        {
            var stopwatch = Stopwatch.StartNew();
            var result    = AttachedObject.FormatMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, ref lpBuffer, nSize, arguments);

            stopwatch.Stop();

            var callEvent = new PInvokeInt32CallCompletedTraceEvent
            {
                DllName    = Kernel32Dll,
                Duration   = stopwatch.Elapsed,
                MethodName = nameof(FormatMessage),
                Result     = result
            };

            callEvent.Args.Add(nameof(dwFlags), dwFlags);
            callEvent.Args.Add(nameof(lpSource), lpSource);
            callEvent.Args.Add(nameof(dwMessageId), dwMessageId);
            callEvent.Args.Add(nameof(dwLanguageId), dwLanguageId);
            callEvent.Args.Add(nameof(nSize), nSize);
            callEvent.Args.Add(nameof(arguments), arguments);

            callEvent.OutArgs.Add(nameof(lpBuffer), lpBuffer);

            LogVerbose(callEvent);
            return(result);
        }
Beispiel #11
0
 protected override void OnAttached()
 {
     AttachedObject.GetComponent <AddressByPartitionKeyComponent>()
     .KeyChanged += AddressByPartitionKeyChanged;
     AttachedObject.RegisterPropertyChangedHandler(IsEnabledComponent.IsEnabledProperty, OnIsEnabledChanged);
     AttachedObject.QueueOperation(TrySubscribe);
 }
Beispiel #12
0
 private Task DispatchPacket(PlayerPosition packet)
 {
     // TODO: check if player movement is valid
     AttachedObject.SetLocalValue(EntityWorldPositionComponent.EntityWorldPositionProperty, new EntityWorldPos((float)packet.X, (float)packet.FeetY, (float)packet.Z));
     AttachedObject.SetLocalValue(EntityOnGroundComponent.IsOnGroundProperty, packet.OnGround);
     return(Task.CompletedTask);
 }
        public Task Teleport(EntityWorldPos position, float yaw, float pitch)
        {
            var  generator  = AttachedObject.GetComponent <ClientboundPacketComponent>().GetGenerator();
            uint teleportId = AttachedObject.GetComponent <TeleportComponent>().StartNew();

            return(generator.PositionAndLook(position.X, position.Y, position.Z, yaw, pitch, 0, teleportId));
        }
        private void StartCollapse()
        {
            var repelVolume = (WhiteHoleFluidVolume)TriggerOwner._repelVolume;

            repelVolume.SetVolumeActivation(false);
            QSBPlayerManager.ShowAllPlayers();

            TriggerOwner._state            = CosmicInflationController.State.Collapsing;
            TriggerOwner._stateChangeTime  = Time.time;
            TriggerOwner._collapseStartPos = TriggerOwner._possibilitySphereRoot.localPosition;
            AttachedObject.SetTriggerActivation(false);
            TriggerOwner._inflationLight.FadeTo(1f, 1f);
            TriggerOwner._possibilitySphereController.OnCollapse();
            if (TriggerOwner._campsiteController.GetUseAltPostCollapseSocket())
            {
                TriggerOwner._playerPostCollapseSocket = TriggerOwner._altPlayerPostCollapseSocket;
                TriggerOwner._altTravelerToHidePostCollapse.SetActive(false);
            }

            Locator.GetPlayerBody().SetPosition(TriggerOwner._playerPostCollapseSocket.position);
            Locator.GetPlayerBody().SetRotation(TriggerOwner._playerPostCollapseSocket.rotation);
            Locator.GetPlayerBody().SetVelocity(-TriggerOwner._playerPostCollapseSocket.forward);
            Locator.GetPlayerTransform().GetRequiredComponent <PlayerLockOnTargeting>().LockOn(TriggerOwner._possibilitySphereRoot, 2f);
            foreach (var particles in TriggerOwner._smokeSphereParticles)
            {
                particles.Stop();
            }
        }
Beispiel #15
0
        public static void AttachObjectToPlayer(Client player, uint model, int bone, Vector3 posOffset, Vector3 rotOffset)
        {
            var attObj = new AttachedObject(model, bone, posOffset, rotOffset);

            player.SetSharedData("attachedObject", JsonConvert.SerializeObject(attObj));
            Trigger.ClientEventInRange(player.Position, 550, "attachObject", player);
        }
 public AttachedObject()
 {
     if (instance == null)
     {
         instance = this;
     }
 }
    void DetachObject()
    {
        if (Parts.CheckIfNull())
        {
            return;
        }

        for (int i = 0; i < Parts.Fingers.Length; i++)
        {
            Parts.Fingers[i].IsHoldingObject = false;
        }

        if (AttachedObject == null)
        {
            return;
        }

        if (AttachedObject.Rigidbody != null)
        {
            Parts.IgnoreCollisions(AttachedObject.Rigidbody, false);
        }
        AttachedObject.Detach();
        AttachedObject = null;

        OnObjectDetached();
    }
Beispiel #18
0
 Task IHandle <KickPlayer> .Handle(KickPlayer message)
 {
     AttachedObject.GetComponent <GameTickComponent>()
     .Tick    -= OnGameTick;
     _isOnline = false;
     return(Task.CompletedTask);
 }
        public virtual bool AcceptsItem(IQSBOWItem item)
        {
            var itemType       = item.GetItemType();
            var acceptableType = AttachedObject.GetValue <ItemType>("_acceptableType");

            return((itemType & acceptableType) == itemType);
        }
Beispiel #20
0
        private async Task ActionLook()
        {
            // 通知周围creature entity看着玩家
            EntityWorldPos    entityPos = AttachedObject.GetValue(EntityWorldPositionComponent.EntityWorldPositionProperty);
            ChunkWorldPos     chunkPos  = entityPos.ToChunkWorldPos();
            IChunkTrackingHub tracker   = GrainFactory.GetGrain <IChunkTrackingHub>(AttachedObject.GetAddressByPartitionKey());
            var list = await tracker.GetTrackedPlayers();

            // TODO 多位玩家的话只看一位
            foreach (IPlayer each in list)
            {
                EntityWorldPos playerPosition = await each.GetPosition();

                // 三格内玩家
                if (EntityWorldPos.Distance(playerPosition, entityPos) < 3)
                {
                    (var yaw, var pitch) = VectorToYawAndPitch(entityPos, playerPosition);

                    await AttachedObject.SetLocalValue(EntityLookComponent.YawProperty, yaw);

                    await AttachedObject.SetLocalValue(EntityLookComponent.HeadYawProperty, yaw);

                    await AttachedObject.SetLocalValue(EntityLookComponent.PitchProperty, pitch);

                    break;
                }
            }
        }
Beispiel #21
0
        //-------------------------------------------------
        // Attach a GameObject to this GameObject
        //
        // objectToAttach - The GameObject to attach
        // flags - The flags to use for attaching the object
        // attachmentPoint - Name of the GameObject in the hierarchy of this Hand which should act as the attachment point for this GameObject
        //-------------------------------------------------
        public void AttachObject(GameObject objectToAttach, AttachmentFlags flags = defaultAttachmentFlags, string attachmentPoint = "")
        {
            if (flags == 0)
            {
                flags = defaultAttachmentFlags;
            }

            //Make sure top object on stack is non-null
            CleanUpAttachedObjectStack();

            //Detach the object if it is already attached so that it can get re-attached at the top of the stack
            DetachObject(objectToAttach);

            //Detach from the other hand if requested
            if (((flags & AttachmentFlags.DetachFromOtherHand) == AttachmentFlags.DetachFromOtherHand) && otherHand)
            {
                otherHand.DetachObject(objectToAttach);
            }

            if ((flags & AttachmentFlags.DetachOthers) == AttachmentFlags.DetachOthers)
            {
                //Detach all the objects from the stack
                while (attachedObjects.Count > 0)
                {
                    DetachObject(attachedObjects[0].attachedObject);
                }
            }

            if (currentAttachedObject)
            {
                currentAttachedObject.SendMessage("OnHandFocusLost", this, SendMessageOptions.DontRequireReceiver);
            }

            AttachedObject attachedObject = new AttachedObject();

            attachedObject.attachedObject = objectToAttach;
            attachedObject.originalParent = objectToAttach.transform.parent != null ? objectToAttach.transform.parent.gameObject : null;
            if ((flags & AttachmentFlags.ParentToHand) == AttachmentFlags.ParentToHand)
            {
                //Parent the object to the hand
                objectToAttach.transform.parent = GetAttachmentTransform(attachmentPoint);
                attachedObject.isParentedToHand = true;
            }
            else
            {
                attachedObject.isParentedToHand = false;
            }
            attachedObjects.Add(attachedObject);

            if ((flags & AttachmentFlags.SnapOnAttach) == AttachmentFlags.SnapOnAttach)
            {
                objectToAttach.transform.localPosition = Vector3.zero;
                objectToAttach.transform.localRotation = Quaternion.identity;
            }

            HandDebugLog("AttachObject " + objectToAttach);
            objectToAttach.SendMessage("OnAttachedToHand", this, SendMessageOptions.DontRequireReceiver);

            UpdateHovering();
        }
Beispiel #22
0
 protected override void OnAttached()
 {
     Register();
     AttachedObject.SetLocalValue(EntityAiComponent.CreatureStateProperty, CreatureState.Stop);
     CreateAi(MobType);
     AttachedObject.RegisterPropertyChangedHandler(MobTypeComponent.MobTypeProperty, OnMobTypeChanged);
 }
Beispiel #23
0
 public LuerlockConnector(LuerlockAdapter.Side side, LuerlockAdapter luerlock, GameObject collider) : base(luerlock.transform)
 {
     GeneralItem   = luerlock;
     attached      = new AttachedObject();
     this.side     = side;
     this.Collider = collider;
 }
Beispiel #24
0
 public virtual void Detach()
 {
     if (null != AttachedObject)
     {
         AttachedObject.RemoveDataContextChangedHandler(DoDataContextChanged);
     }
 }
        async Task IHandle <PlayerLoggedIn> .Handle(PlayerLoggedIn message)
        {
            var generator = AttachedObject.GetComponent <ClientboundPacketComponent>().GetGenerator();

            // PositionAndLook
            var position      = AttachedObject.GetEntityWorldPosition();
            var lookComponent = AttachedObject.GetComponent <EntityLookComponent>();
            await generator.PositionAndLook(position.X, position.Y, position.Z, lookComponent.Yaw, lookComponent.Pitch, 0, AttachedObject.GetComponent <TeleportComponent>().StartNew());

            // Health
            var healthComponent = AttachedObject.GetComponent <HealthComponent>();
            var foodComponent   = AttachedObject.GetComponent <FoodComponent>();
            await generator.UpdateHealth(healthComponent.Health, healthComponent.MaxHealth, foodComponent.Food, foodComponent.MaxFood, foodComponent.FoodSaturation);

            // Experience
            var expComponent = AttachedObject.GetComponent <ExperienceComponent>();
            await generator.SetExperience(expComponent.ExperienceBar, expComponent.Level, expComponent.TotalExperience);

            // Inventory
            var slots = await AttachedObject.GetComponent <InventoryComponent>().GetInventoryWindow().GetSlots(AttachedObject);

            await generator.WindowItems(0, slots);

            InstallPropertyChangedHandlers();
        }
        private Task OnEntityWorldPositionChanged(object sender, PropertyChangedEventArgs <EntityWorldPos> e)
        {
            var pos = e.NewValue;
            var box = new Cuboid(new Point3d(pos.X, pos.Z, pos.Y), new Size(0.6f, 0.6f, 1.75f));

            return(AttachedObject.SetLocalValue(ColliderComponent.ColliderShapeProperty, box));
        }
Beispiel #27
0
        public async Task PlaceBlock(BlockWorldPos location, EntityInteractHand hand, PlayerDiggingFace face, Vector3 cursorPosition)
        {
            if (face != PlayerDiggingFace.Special)
            {
                var world      = AttachedObject.GetWorld();
                var blockState = await world.GetBlockState(GrainFactory, location);

                var blockHandler = BlockHandler.Create((BlockId)blockState.Id);
                if (blockHandler.IsUsable)
                {
                    await blockHandler.UseBy(AttachedObject, GrainFactory, world, location, cursorPosition);
                }
                else
                {
                    var heldItem = await AttachedObject.GetComponent <HeldItemComponent>().GetHeldItem();

                    if (!heldItem.slot.IsEmpty)
                    {
                        var itemHandler = ItemHandler.Create((uint)heldItem.slot.BlockId);
                        if (itemHandler.IsPlaceable)
                        {
                            var inventory = AttachedObject.GetComponent <InventoryComponent>().GetInventoryWindow();
                            await itemHandler.PlaceBy(AttachedObject, GrainFactory, world, location, inventory, heldItem.index, face, cursorPosition);
                        }
                    }
                }
            }
        }
Beispiel #28
0
        public int RasEnumDevices(RASDEVINFO[] lpRasDevInfo, ref int lpCb, ref int lpcDevices)
        {
            var callEvent = new PInvokeInt32CallCompletedTraceEvent
            {
                DllName    = RasApi32Dll,
                MethodName = nameof(RasEnumDevices)
            };

            callEvent.Args.Add(nameof(lpRasDevInfo), lpRasDevInfo);
            callEvent.Args.Add(nameof(lpCb), lpCb);
            callEvent.Args.Add(nameof(lpcDevices), lpcDevices);

            var stopwatch = Stopwatch.StartNew();
            var result    = AttachedObject.RasEnumDevices(lpRasDevInfo, ref lpCb, ref lpcDevices);

            stopwatch.Stop();

            callEvent.Duration = stopwatch.Elapsed;
            callEvent.Result   = result;
            callEvent.OutArgs.Add(nameof(lpCb), lpCb);
            callEvent.OutArgs.Add(nameof(lpcDevices), lpcDevices);

            LogVerbose(callEvent);
            return(result);
        }
Beispiel #29
0
        public int RasDial(ref RASDIALEXTENSIONS lpRasDialExtensions, string lpszPhoneBook, ref RASDIALPARAMS lpRasDialParams, NotifierType dwNotifierType, RasDialFunc2 lpvNotifier, out IntPtr lphRasConn)
        {
            var stopwatch = Stopwatch.StartNew();
            var result    = AttachedObject.RasDial(ref lpRasDialExtensions, lpszPhoneBook, ref lpRasDialParams, dwNotifierType, lpvNotifier, out lphRasConn);

            stopwatch.Stop();

            var callEvent = new PInvokeInt32CallCompletedTraceEvent
            {
                DllName    = RasApi32Dll,
                Duration   = stopwatch.Elapsed,
                MethodName = nameof(RasDial),
                Result     = result,
            };

            callEvent.Args.Add(nameof(lpRasDialExtensions), lpRasDialExtensions);
            callEvent.Args.Add(nameof(lpszPhoneBook), lpszPhoneBook);
            callEvent.Args.Add(nameof(lpRasDialParams), lpRasDialParams);
            callEvent.Args.Add(nameof(dwNotifierType), dwNotifierType);
            callEvent.Args.Add(nameof(lpvNotifier), lpvNotifier);
            callEvent.OutArgs.Add(nameof(lphRasConn), lphRasConn);

            LogVerbose(callEvent);
            return(result);
        }
        private async Task DispatchPacket(PlayerDigging packet)
        {
            var face      = ConvertDiggingFace(packet.Face);
            var component = AttachedObject.GetComponent <DiggingComponent>();

            switch (packet.Status)
            {
            case PlayerDiggingStatus.StartedDigging:
                await component.StartDigging(packet.Location, face);

                break;

            case PlayerDiggingStatus.CancelledDigging:
                await component.CancelDigging(packet.Location, face);

                break;

            case PlayerDiggingStatus.FinishedDigging:
                await component.FinishDigging(packet.Location, face);

                break;

            default:
                Logger.LogWarning($"Not implemented digging status: {packet.Status}");
                break;
            }
        }
	/// <summary>
	/// Attach a GameObject to this GameObject.
	/// </summary>
	/// <param name="objectToAttach">The GameObject to attach.</param>
	/// <param name="flags">The flags to use for attaching the object.</param>
	/// <param name="attachmentPoint">Name of the GameObject in the hierarchy of this VRHand which should act as the attachment point for this GameObject.</param>
	/// <seealso cref="DetachObject"/>
	public void AttachObject( GameObject objectToAttach, AttachmentFlags flags = defaultAttachmentFlags, string attachmentPoint = "" )
	{
		if ( flags == 0 )
		{
			flags = defaultAttachmentFlags;
		}

		//Make sure top object on stack is non-null
		CleanUpAttachedObjectStack();

		//Detach the object if it is already attached so that it can get re-attached at the top of the stack
		DetachObject( objectToAttach );

		//Detach from the other hand if requested
		if ( ( ( flags & AttachmentFlags.DetachFromOtherHand ) == AttachmentFlags.DetachFromOtherHand ) && otherHand )
		{
			otherHand.DetachObject( objectToAttach );
		}

		if ( ( flags & AttachmentFlags.DetachOthers ) == AttachmentFlags.DetachOthers )
		{
			//Detach all the objects from the stack
			while ( attachedObjects.Count > 0 )
			{
				DetachObject( attachedObjects[0].attachedObject );
			}
		}

		if ( currentAttachedObject )
		{
			currentAttachedObject.SendMessage( "OnHandFocusLost", this, SendMessageOptions.DontRequireReceiver );
		}

		AttachedObject attachedObject = new AttachedObject();
		attachedObject.attachedObject = objectToAttach;
		attachedObject.originalParent = objectToAttach.transform.parent != null ? objectToAttach.transform.parent.gameObject : null;
		if ( ( flags & AttachmentFlags.ParentToHand ) == AttachmentFlags.ParentToHand )
		{
			//Parent the object to the hand
			objectToAttach.transform.parent = GetAttachmentTransform( attachmentPoint );
			attachedObject.isParentedToHand = true;
		}
		else
		{
			attachedObject.isParentedToHand = false;
		}
		attachedObjects.Add( attachedObject );

		if ( ( flags & AttachmentFlags.SnapOnAttach ) == AttachmentFlags.SnapOnAttach )
		{
			objectToAttach.transform.localPosition = Vector3.zero;
			objectToAttach.transform.localRotation = Quaternion.identity;
		}

		VRHandDebugLog( "AttachObject " + objectToAttach );
		objectToAttach.SendMessage( "OnAttachedToHand", this, SendMessageOptions.DontRequireReceiver );

		UpdateHovering();
	}
Beispiel #32
0
	/// <summary>
	/// Attach a GameObject to this GameObject.
	/// </summary>
	/// <param name="objectToAttach">The GameObject to attach.</param>
	/// <param name="snapOnAttach">Should the GameObject snap to an attachment point?</param>
	/// <param name="attachmentPoint">Name of the GameObject in the hierarchy of this VRHand which should act as the attachment point for this GameObject.</param>
	/// <param name="detachOthers">Should all other attached objects in the attached object stack of this VRHand be detached?</param>
	/// <seealso cref="DetachObject"/>
	public void AttachObject( GameObject objectToAttach, bool snapOnAttach = true, string attachmentPoint = "", bool detachOthers = true )
	{
		//Make sure top object on stack is non-null
		CleanUpAttachedObjectStack();

		//Detach the object if it is already attached so that it can get re-attached at the top of the stack
		DetachObject( objectToAttach );
		if ( otherHand )
		{
			otherHand.DetachObject( objectToAttach );
		}

		if ( detachOthers )
		{
			//Detach all the objects from the stack
			while ( attachedObjects.Count > 0 )
			{
				DetachObject( attachedObjects[0].attachedObject );
			}
		}

		if ( currentAttachedObject )
		{
			currentAttachedObject.SendMessage( "OnHandFocusLost", this, SendMessageOptions.DontRequireReceiver );
		}
		AttachedObject attachedObject = new AttachedObject();
		attachedObject.attachedObject = objectToAttach;
		attachedObject.originalParent = objectToAttach.transform.parent != null ? objectToAttach.transform.parent.gameObject : null;
		attachedObjects.Add( attachedObject );

		//Parent the object to the hand
		objectToAttach.transform.parent = GetAttachmentTransform( attachmentPoint );
		
		if ( snapOnAttach )
		{
			objectToAttach.transform.localPosition = Vector3.zero;
			objectToAttach.transform.localRotation = Quaternion.identity;
		}

		objectToAttach.SendMessage( "OnAttachedToHand", this, SendMessageOptions.DontRequireReceiver );
		
		UpdateHovering();
	}