public override void Update() { //remote? if (RemoteSensorClient.Instance != null && RemoteSensorClient.Instance.OrientationEnabled) { Vector3 sensorAngles = RemoteSensorClient.Instance.CameraAngles; eulerAngles = new Vector3(-sensorAngles.x, -sensorAngles.y, 0); rotation = null; } else { if(!Input.GetMouseButton(0)) { rotation = null; eulerAngles = null; return; } x = playerManager.transform.eulerAngles.y; y = playerManager.transform.eulerAngles.x; x += Input.GetAxis ("Mouse X") * xSpeed * 0.02f; y -= Input.GetAxis ("Mouse Y") * ySpeed * 0.02f; //y = clampAngle (y, yMinLimit, yMaxLimit); rotation = Quaternion.Euler (y, x, 0); } base.Update (); }
public IntBlockBounds(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { MinX = minX; MinY = minY; MinZ = minZ; MaxX = maxX; MaxY = maxY; MaxZ = maxZ; _rotation = null; }
private void DoorBehaviour_Updated(object sender, OpenTK.FrameEventArgs e) { float dt = (float)e.Time; this.initialRotation = this.initialRotation ?? this.Detail.Rotation; float targetRotation = (this.isOpen ? 1.0f : 0.0f); float delta = targetRotation - this.fOpen; this.fOpen += Math.Sign(delta) * Math.Min(Math.Abs(delta), dt); this.Detail.Rotation = this.initialRotation.Value * Quaternion.FromAxisAngle(Vector3.UnitY, 0.7f * MathHelper.Pi * this.fOpen); }
internal void Rotate(Quaternion delta, AxisPivot pivot) { _rotation = delta * Rotation; Vector3 rotatedMin = MathHelper.RotateAroundPivot(Min, pivot.Pivot, delta); Vector3 rotatedMax = MathHelper.RotateAroundPivot(Max, pivot.Pivot, delta); Min = new Vector3( Mathf.Min(rotatedMin.x, rotatedMax.x), Mathf.Min(rotatedMin.y, rotatedMax.y), Mathf.Min(rotatedMin.z, rotatedMax.z)); Max = new Vector3( Mathf.Max(rotatedMin.x, rotatedMax.x), Mathf.Max(rotatedMin.y, rotatedMax.y), Mathf.Max(rotatedMin.z, rotatedMax.z)); }
protected override void OnSceneNodeChanged(ISceneNode sceneNode) { // Copy the position and orientation. if (_localPosition != null) { sceneNode.LocalPosition = (Vector3)_localPosition; _localPosition = null; } if (_localOrientation != null) { sceneNode.LocalOrientation = (Quaternion)_localOrientation; _localOrientation = null; } // Set the parent. if (sceneNode != null) { if (_parent != null && _parent.SceneNode != null) { sceneNode.Parent = _parent.SceneNode; } else { // Default the parent to the scene root. sceneNode.Parent = World.Scene.Root; } } }
void Update() { // in VR mode, no mouse/gyro at all! if (UsingVr()) { return; } bool UseGyro = UseGyroOnMobile; { if (UseGyro) { Input.gyro.enabled = true; } UseGyro &= Input.gyro.enabled; } if (UseGyro) { bool GyroValid = Input.gyro.enabled; { // first usage of the attituide is all zeros, ignore this Vector4 Gyro4 = new Vector4(Input.gyro.attitude.x, Input.gyro.attitude.y, Input.gyro.attitude.z, Input.gyro.attitude.w); GyroValid &= Gyro4.SqrMagnitude() > 0; } if (GyroValid) { // correction stolen from google cardboad SDK var att = Input.gyro.attitude; att = new Quaternion(att.x, att.y, -att.z, -att.w); att = Quaternion.Euler(0, 0, 0) * att; if (mInitialGyro == null) { mInitialGyro = att; } transform.localRotation = Quaternion.Inverse(mInitialGyro.Value) * att; } } else if (axes == RotationAxes.MouseXAndY) { // Read the mouse input axis rotationX += Input.GetAxis("Mouse X") * sensitivityX; rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationX = ClampAngle(rotationX, minimumX, maximumX); rotationY = ClampAngle(rotationY, minimumY, maximumY); Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up); Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, -Vector3.right); transform.localRotation = originalRotation * xQuaternion * yQuaternion; } else if (axes == RotationAxes.MouseX) { rotationX += Input.GetAxis("Mouse X") * sensitivityX; rotationX = ClampAngle(rotationX, minimumX, maximumX); Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up); transform.localRotation = originalRotation * xQuaternion; } else { rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationY = ClampAngle(rotationY, minimumY, maximumY); Quaternion yQuaternion = Quaternion.AngleAxis(-rotationY, Vector3.right); transform.localRotation = originalRotation * yQuaternion; } }
public virtual NetworkBehavior InstantiateInScene(string pSceneName, int pCreateCode = -1, IRPCSerializable pBehaviorData = null, Vector3?pPosition = null, Quaternion?pRotation = null, bool pSendTransform = true) { NetworkSceneItem item = FindNetworkSceneItem(pSceneName, true, true); if (item == null || !item.HasManager) { return(null); } return(item.Manager.InstantiateNetworkBehavior(pCreateCode, pBehaviorData, pPosition, pRotation, pSendTransform)); }
/// <summary> /// The Teleport/4 method calls the teleport to update position without needing to listen for a Destination Marker event. /// It will build a destination marker out of the provided parameters. /// </summary> /// <param name="target">The Transform of the destination object.</param> /// <param name="destinationPosition">The world position to teleport to.</param> /// <param name="destinationRotation">The world rotation to teleport to.</param> /// <param name="forceDestinationPosition">If `true` then the given destination position should not be altered by anything consuming the payload.</param> public virtual void Teleport(Transform target, Vector3 destinationPosition, Quaternion?destinationRotation = null, bool forceDestinationPosition = false) { DestinationMarkerEventArgs teleportArgs = BuildTeleportArgs(target, destinationPosition, destinationRotation, forceDestinationPosition); Teleport(teleportArgs); }
// Only ran on Client internal static NetworkedObject CreateLocalNetworkedObject(bool softCreate, ulong instanceId, ulong prefabHash, ulong?parentNetworkId, Vector3?position, Quaternion?rotation) { NetworkedObject parent = null; if (parentNetworkId != null && SpawnedObjects.ContainsKey(parentNetworkId.Value)) { parent = SpawnedObjects[parentNetworkId.Value]; } else if (parentNetworkId != null) { if (LogHelper.CurrentLogLevel <= LogLevel.Normal) { LogHelper.LogWarning("Cannot find parent. Parent objects always have to be spawned and replicated BEFORE the child"); } } if (!NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkingManager.Singleton.NetworkConfig.UsePrefabSync || !softCreate) { // Create the object if (customSpawnHandlers.ContainsKey(prefabHash)) { NetworkedObject networkedObject = customSpawnHandlers[prefabHash](position.GetValueOrDefault(Vector3.zero), rotation.GetValueOrDefault(Quaternion.identity)); if (parent != null) { networkedObject.transform.SetParent(parent.transform, true); } if (NetworkSceneManager.isSpawnedObjectsPendingInDontDestroyOnLoad) { GameObject.DontDestroyOnLoad(networkedObject.gameObject); } return(networkedObject); } else { int prefabIndex = GetNetworkedPrefabIndexOfHash(prefabHash); if (prefabIndex < 0) { if (LogHelper.CurrentLogLevel <= LogLevel.Error) { LogHelper.LogError("Failed to create object locally. [PrefabHash=" + prefabHash + "]. Hash could not be found. Is the prefab registered?"); } return(null); } else { GameObject prefab = NetworkingManager.Singleton.NetworkConfig.NetworkedPrefabs[prefabIndex].Prefab; NetworkedObject networkedObject = ((position == null && rotation == null) ? MonoBehaviour.Instantiate(prefab) : MonoBehaviour.Instantiate(prefab, position.GetValueOrDefault(Vector3.zero), rotation.GetValueOrDefault(Quaternion.identity))).GetComponent <NetworkedObject>(); if (parent != null) { networkedObject.transform.SetParent(parent.transform, true); } if (NetworkSceneManager.isSpawnedObjectsPendingInDontDestroyOnLoad) { GameObject.DontDestroyOnLoad(networkedObject.gameObject); } return(networkedObject); } } } else { // SoftSync them by mapping if (!pendingSoftSyncObjects.ContainsKey(instanceId)) { // TODO: Fix this message if (LogHelper.CurrentLogLevel <= LogLevel.Error) { LogHelper.LogError("Cannot find pending soft sync object. Is the projects the same?"); } return(null); } NetworkedObject networkedObject = pendingSoftSyncObjects[instanceId]; pendingSoftSyncObjects.Remove(instanceId); if (parent != null) { networkedObject.transform.SetParent(parent.transform, true); } return(networkedObject); } }
public void ResetCam() { m_EndPos = null; m_EndRot = null; LookTarget = null; }
void OnWidgetRotation() { Vector3 worldPosition = GetBrushesPivotPoint(); if (Event.current.type == EventType.MouseUp) { initialRotationOffset = null; } DrawRotationAxis(Color.red, Vector3.right, worldPosition); DrawRotationAxis(Color.green, Vector3.up, worldPosition); DrawRotationAxis(Color.blue, Vector3.forward, worldPosition); }
public static GameObject PoolNetworkInstantiate(GameObject prefab, Vector3?position = null, Transform parent = null, Quaternion?rotation = null) { if (!IsInstanceInit()) { return(null); } bool isPooled; GameObject tempObject = Instance.PoolInstantiate(prefab, position ?? TransformState.HiddenPos, rotation ?? Quaternion.identity, parent, out isPooled); if (!isPooled) { NetworkServer.Spawn(tempObject); tempObject.GetComponent <CustomNetTransform>()?.NotifyPlayers(); //Sending clientState for newly spawned items } //fire the hooks for spawning tempObject.GetComponent <CustomNetTransform>()?.FireGoingOnStageHooks(); return(tempObject); }
/// <summary> /// Spawn the specified prefab locally, for this client only. /// </summary> /// <param name="prefabName">name of prefab to spawn an instance of. This is intended to be made to work for pretty much any prefab, but don't /// be surprised if it doesn't as there are LOTS of prefabs in the game which all have unique behavior for how they should spawn. If you are trying /// to instantiate something and it isn't properly setting itself up, check to make sure each component that needs to set something up has /// properly implemented necessary lifecycle methods.</param> /// <param name="worldPosition">world position to appear at. Defaults to HiddenPos (hidden / invisible)</param> /// <param name="localRotation">local rotation to spawn with, defaults to Quaternion.identity</param> /// <param name="parent">Parent to spawn under, defaults to no parent. Most things /// should always be spawned under the Objects transform in their matrix. Many objects (due to RegisterTile) /// usually take care of properly parenting themselves when spawned so in many cases you can leave it null.</param> /// <param name="count">number of instances to spawn, defaults to 1</param> /// <param name="scatterRadius">radius to scatter the spawned instances by from their spawn position. Defaults to /// null (no scatter).</param> /// <returns>the newly created GameObject</returns> public static SpawnResult ClientPrefab(string prefabName, Vector3?worldPosition = null, Transform parent = null, Quaternion?localRotation = null, int count = 1, float?scatterRadius = null) { return(Client( SpawnInfo.Spawnable( SpawnablePrefab.For(prefabName), SpawnDestination.At(worldPosition, parent, localRotation), count, scatterRadius))); }
/// <summary> /// Spawn the item locally without syncing it over the network. Only client-side lifecycle hooks will be called. /// </summary> /// <param name="prefab">Prefab to spawn an instance of. </param> /// <param name="position">world position to appear at. Defaults to HiddenPos (hidden / invisible)</param> /// <param name="rotation">rotation to spawn with, defaults to Quaternion.identity</param> /// <param name="parent">Parent to spawn under, defaults to no parent. Most things /// should always be spawned under the Objects transform in their matrix. Many objects (due to RegisterTile) /// usually take care of properly parenting themselves when spawned so in many cases you can leave it null.</param> /// <returns>the newly created GameObject</returns> public static GameObject PoolClientInstantiate(GameObject prefab, Vector3?position = null, Transform parent = null, Quaternion?rotation = null) { if (!IsInstanceInit()) { return(null); } bool isPooled; // not used for Client-only instantiation var go = Instance.PoolInstantiate(prefab, position ?? TransformState.HiddenPos, rotation ?? Quaternion.identity, parent, out isPooled); //fire client side lifecycle hooks var hooks = go.GetComponents <IOnStageClient>(); if (hooks != null) { foreach (var hook in hooks) { hook.GoingOnStageClient(OnStageInfo.Default()); } } return(go); }
public static GameObject NetworkClone(GameObject toClone, Vector3?position = null, Transform parent = null, Quaternion?rotation = null) { if (!IsInstanceInit()) { return(null); } var prefab = DeterminePrefab(toClone); if (prefab == null) { Logger.LogErrorFormat("Object {0} at {1} cannot be cloned because it has no PoolPrefabTracker and its name" + " does not match a prefab name, so we cannot" + " determine the prefab to instantiate. Please fix this object so that it" + " has an attached PoolPrefabTracker or so its name matches the prefab it was created from.", Category.ItemSpawn, toClone.name, position); } GameObject tempObject = Instance.PoolInstantiate(prefab, position ?? TransformState.HiddenPos, rotation ?? Quaternion.identity, parent, out var isPooled); if (!isPooled) { NetworkServer.Spawn(tempObject); tempObject.GetComponent <CustomNetTransform>()?.NotifyPlayers(); //Sending clientState for newly spawned items } //fire the hooks for cloning tempObject.GetComponent <CustomNetTransform>()?.FireCloneHooks(toClone); return(tempObject); }
public static GameObject PoolNetworkInstantiate(String prefabName, Vector3?position = null, Transform parent = null, Quaternion?rotation = null) { GameObject prefab = GetPrefabByName(prefabName); if (prefab == null) { Logger.LogErrorFormat("Attempted to spawn prefab with name {0} which is either not an actual prefab name or" + " is a prefab which is not spawnable. Request to spawn will be ignored.", Category.ItemSpawn, prefabName); return(null); } return(PoolNetworkInstantiate(prefab, position, parent, rotation)); }
/// <summary> /// Instantiate an instance of NetworkCamera /// </summary> /// <returns> /// A local instance of NetworkCameraBehavior /// </returns> /// <param name="index">The index of the NetworkCamera prefab in the NetworkManager to Instantiate</param> /// <param name="position">Optional parameter which defines the position of the created GameObject</param> /// <param name="rotation">Optional parameter which defines the rotation of the created GameObject</param> /// <param name="sendTransform">Optional Parameter to send transform data to other connected clients on Instantiation</param> public NetworkCameraBehavior InstantiateNetworkCamera(int index = 0, Vector3?position = null, Quaternion?rotation = null, bool sendTransform = true) { var go = Instantiate(NetworkCameraNetworkObject[index]); var netBehavior = go.GetComponent <NetworkCameraBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) { obj = netBehavior.CreateNetworkObject(Networker, index); } else { metadata.Clear(); if (position == null && rotation == null) { byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) { ObjectMapper.Instance.MapBytes(metadata, position.Value); } if (rotation != null) { ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent <NetworkCameraBehavior>().networkObject = (NetworkCameraNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return(netBehavior); }
/// <summary> /// Spawn destination at the indicated position. /// </summary> /// <param name="worldPosition">position to spawn at, defaults to HiddenPos</param> /// <param name="parent">Parent transform to spawn under. This does not usually need to be specified because the RegisterTile /// automatically figures out the correct parent.</param> /// <param name="rotation">rotation to spawn with ,defaults to Quaternion.identity</param> /// <param name="cancelIfImpassable">If true, the spawn will be cancelled if the location being spawned into is totally impassable.</param> /// <returns></returns> public static SpawnDestination At(Vector3?worldPosition = null, Transform parent = null, Quaternion?rotation = null, bool cancelIfImpassable = false) { return(new SpawnDestination(worldPosition.GetValueOrDefault(TransformState.HiddenPos), DefaultParent(parent, worldPosition), rotation.GetValueOrDefault(Quaternion.identity), cancelIfImpassable)); }
void Update () { // in VR mode, no mouse/gyro at all! if (UsingVr() ) return; bool UseGyro = UseGyroOnMobile; { if (UseGyro) Input.gyro.enabled = true; UseGyro &= Input.gyro.enabled; } if (UseGyro) { bool GyroValid = Input.gyro.enabled; { // first usage of the attituide is all zeros, ignore this Vector4 Gyro4 = new Vector4( Input.gyro.attitude.x, Input.gyro.attitude.y, Input.gyro.attitude.z, Input.gyro.attitude.w ); GyroValid &= Gyro4.SqrMagnitude() > 0; } if ( GyroValid ) { // correction stolen from google cardboad SDK var att = Input.gyro.attitude; att = new Quaternion(att.x, att.y, -att.z, -att.w); att = Quaternion.Euler(0, 0, 0) * att; if ( mInitialGyro == null ) { mInitialGyro = att; } transform.localRotation = Quaternion.Inverse(mInitialGyro.Value) * att; } } else if (axes == RotationAxes.MouseXAndY) { // Read the mouse input axis rotationX += Input.GetAxis("Mouse X") * sensitivityX; rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationX = ClampAngle (rotationX, minimumX, maximumX); rotationY = ClampAngle (rotationY, minimumY, maximumY); Quaternion xQuaternion = Quaternion.AngleAxis (rotationX, Vector3.up); Quaternion yQuaternion = Quaternion.AngleAxis (rotationY, -Vector3.right); transform.localRotation = originalRotation * xQuaternion * yQuaternion; } else if (axes == RotationAxes.MouseX) { rotationX += Input.GetAxis("Mouse X") * sensitivityX; rotationX = ClampAngle (rotationX, minimumX, maximumX); Quaternion xQuaternion = Quaternion.AngleAxis (rotationX, Vector3.up); transform.localRotation = originalRotation * xQuaternion; } else { rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationY = ClampAngle (rotationY, minimumY, maximumY); Quaternion yQuaternion = Quaternion.AngleAxis (-rotationY, Vector3.right); transform.localRotation = originalRotation * yQuaternion; } }
/// <summary> /// Clone the item and syncs it over the network. This only works if toClone has a PoolPrefabTracker /// attached or its name matches a prefab name, otherwise we don't know what prefab to create. /// </summary> /// <param name="toClone">GameObject to clone. This only works if toClone has a PoolPrefabTracker /// attached or its name matches a prefab name, otherwise we don't know what prefab to create.. Intended to work for any object, but don't /// be surprised if it doesn't as there are LOTS of prefabs in the game which might need unique behavior for how they should spawn. If you are trying /// to clone something and it isn't properly setting itself up, check to make sure each component that needs to set something up has /// properly implemented IOnStageServer or IOnStageClient when IsCloned = true</param> /// <param name="worldPosition">world position to appear at. Defaults to HiddenPos (hidden / invisible)</param> /// <param name="localRotation">local rotation to spawn with, defaults to Quaternion.identity</param> /// <param name="parent">Parent to spawn under, defaults to no parent. Most things /// should always be spawned under the Objects transform in their matrix. Many objects (due to RegisterTile) /// usually take care of properly parenting themselves when spawned so in many cases you can leave it null.</param> /// <returns>the newly created GameObject</returns> public static SpawnResult ServerClone(GameObject toClone, Vector3?worldPosition = null, Transform parent = null, Quaternion?localRotation = null) { return(Server( SpawnInfo.Clone(toClone, SpawnDestination.At(worldPosition, parent, localRotation)))); }
public void SetCameraRot(Quaternion rot, bool bRightNow = false) { if (bRightNow) { transform.rotation = rot; m_EndRot = null; } else { m_EndRot = rot; } }
private void SetMotion(float speed, Quaternion targetRotation) { //Calculate motion m_velocity = transform.forward * speed; m_eulerAngleVelocity = Vector3.zero; m_targetRotation = targetRotation; }
public void Add(DesignPart part) { HideModifiers(); _parts.Add(part); part.Part3D.IsSelected = true; if (_parts.Count > 1) { _orientation = _options.DefaultOrientation; } //No need to listen to this event anymore, the transform changed is now called directly by this class's propert sets //part.Part3D.TransformChanged += new EventHandler(Part3D_TransformChanged); // Point Light PointLight pointLight = new PointLight(); pointLight.Color = _options.EditorColors.SelectionLightColor; pointLight.QuadraticAttenuation = 1d; pointLight.Range = 10d; ModelVisual3D pointLightModel = new ModelVisual3D(); pointLightModel.Content = pointLight; _viewport.Children.Add(pointLightModel); _pointLights.Add(pointLightModel); if (!this.IsLocked) { ShowModifiers(); } // Move the visuals to be relative to the part TransformChanged(); }
private void SetMotion(float throttle, float roll, float pitch, float yaw) { //Calculate motion m_velocity = transform.forward * Mathf.Lerp(MinSpeed, MaxSpeed, throttle); m_eulerAngleVelocity = new Vector3(TurnSpeed * pitch, TurnSpeed * yaw, TurnSpeed * roll); m_targetRotation = null; }
public void RotateToFaceTarget(Vector3 target) { Vector3 upDirection = World != null ? World.Camera.UpVector : Vector3.Up; Vector3 targetDirection = Vector3.Normalize (target - Position); _rotationQuaternion = VectorHelper.RotateToFaceTarget (sourceDirection: Vector3.Forward, destDirection: targetDirection, up: upDirection); UpdatePrecomputed (overrideValues: true); }
/// <summary> /// Draw a cube with color for a duration of time and with or without depth testing. /// If duration is 0 then the square is renderer 1 frame. /// </summary> /// <param name="pos">Center of the cube in world space.</param> /// <param name="rot">Rotation of the cube in world space.</param> /// <param name="scale">Size of the cube.</param> /// <param name="color">Color of the cube.</param> /// <param name="duration">How long the cube should be visible for.</param> /// <param name="depthTest">Should the cube be obscured by objects closer to the camera ?</param> public static void DrawCube(Vector3 pos, Quaternion?rot = null, Vector3?scale = null, Color?color = null, float duration = 0, bool depthTest = false) { DrawCube(Matrix4x4.TRS(pos, rot ?? Quaternion.identity, scale ?? Vector3.one), color, duration, depthTest); }
public virtual T Spawn <T>(GameObject prefab, BaseCoreMono castMono, Vector3?position = null, Quaternion?quaternion = null, params object[] ps) where T : BasePerform { if (prefab == null) { return(null); } var temp = SelfBaseGlobal.PoolMgr.Perform.Spawn(prefab, position, quaternion); return(Spawn <T>(castMono, position, quaternion, temp, ps)); }
public ExampleProximityPlayerBehavior InstantiateExampleProximityPlayerNetworkObject(int index = 0, Vector3?position = null, Quaternion?rotation = null, bool sendTransform = true) { var go = Instantiate(ExampleProximityPlayerNetworkObject[index]); var netBehavior = go.GetComponent <NetworkBehavior>() as ExampleProximityPlayerBehavior; var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent <ExampleProximityPlayerBehavior>().networkObject = (ExampleProximityPlayerNetworkObject)obj; FinializeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return(netBehavior); }
public void ResetOrientation() { mInitialGyro = null; }
internal virtual void OnPositionUpdate(ref PositionUpdateMsg msg, MyNetworkClient sender) { // Validate that client sending position update to server is reponsible for update if (Sync.IsServer && !ResponsibleForUpdate(sender)) return; if (!Sync.IsServer && ResponsibleForUpdate(Sync.Clients.LocalClient)) return; var q = msg.Orientation; var m = Matrix.CreateFromQuaternion(q); var world = MatrixD.CreateWorld(msg.Position, m.Forward, m.Up); Debug.Assert(Entity.PositionComp != null, "Entity doesn't not have position component"); if (Entity.PositionComp != null) Entity.PositionComp.SetWorldMatrix(world, this); if (Entity.Physics != null) { Entity.Physics.LinearVelocity = msg.LinearVelocity; Entity.Physics.AngularVelocity = msg.AngularVelocity; if (MyPerGameSettings.EnableMultiplayerVelocityCompensation) { float ratio = MathHelper.Clamp(Sandbox.Engine.Physics.MyPhysics.SimulationRatio, 0.1f, 2); Entity.Physics.LinearVelocity /= ratio; Entity.Physics.AngularVelocity /= ratio; } Entity.Physics.UpdateAccelerations(); if (!Entity.Physics.IsMoving && Entity.Physics.RigidBody != null && Entity.Physics.RigidBody.IsAddedToWorld) { Entity.Physics.RigidBody.Deactivate(); } } if (Sync.IsServer) { MarkPhysicsDirty(); } else { // Store last update from server m_isLocallyDirty = false; m_lastUpdateFrame = MyMultiplayer.Static.FrameCounter; m_lastServerPosition = msg.Position; m_lastServerOrientation = msg.Orientation; } }
public virtual NetworkBehavior InstantiateInScene(string pSceneName, string pNetworkBehaviorName, IRPCSerializable pBehaviorData = null, Vector3?pPosition = null, Quaternion?pRotation = null, bool pSendTransform = true) { return(InstantiateInScene(pSceneName, _networkSceneBehaviorListSO.behaviorList.GetCreateCodeFromName(pNetworkBehaviorName), pBehaviorData, pPosition, pRotation, pSendTransform)); }
protected virtual DestinationMarkerEventArgs BuildTeleportArgs(Transform target, Vector3 destinationPosition, Quaternion?destinationRotation = null, bool forceDestinationPosition = false) { DestinationMarkerEventArgs teleportArgs = new DestinationMarkerEventArgs(); teleportArgs.distance = (ValidRigObjects() ? Vector3.Distance(new Vector3(headset.position.x, playArea.position.y, headset.position.z), destinationPosition) : 0f); teleportArgs.target = target; teleportArgs.raycastHit = new RaycastHit(); teleportArgs.destinationPosition = destinationPosition; teleportArgs.destinationRotation = destinationRotation; teleportArgs.forceDestinationPosition = forceDestinationPosition; teleportArgs.enableTeleport = true; return(teleportArgs); }
public virtual ServiceCallback <RPCInstantiateInNode, ServiceCallbackStateEnum> InstantiateInNode(uint pTargetNodeId, string pSceneName, string pNetworkBehaviorName, IRPCSerializable pBehaviorData = null, Vector3?pPosition = null, Quaternion?pRotation = null, bool pSendTransform = true) { return(InstantiateInNode(_currentNode.NodeId, pTargetNodeId, pSceneName, _networkSceneBehaviorListSO.behaviorList.GetCreateCodeFromName(pNetworkBehaviorName), pBehaviorData, pPosition, pRotation, pSendTransform)); }
// Token: 0x060017A3 RID: 6051 RVA: 0x0007E6E0 File Offset: 0x0007C8E0 protected virtual DestinationMarkerEventArgs BuildTeleportArgs(Transform target, Vector3 destinationPosition, Quaternion?destinationRotation = null, bool forceDestinationPosition = false) { return(new DestinationMarkerEventArgs { distance = (this.ValidRigObjects() ? Vector3.Distance(new Vector3(this.headset.position.x, this.playArea.position.y, this.headset.position.z), destinationPosition) : 0f), target = target, raycastHit = default(RaycastHit), destinationPosition = destinationPosition, destinationRotation = destinationRotation, forceDestinationPosition = forceDestinationPosition, enableTeleport = true }); }
public void Seed(Vector3 from, Vector3?to, float duration, Quaternion?fromRot = null, Quaternion?toRot = null, float _time = 0f) { affectRotation = fromRot.HasValue && toRot.HasValue; FromPosition = from; if (affectRotation) { FromRotation = fromRot.Value; } if (to.HasValue) { ToPosition = to.Value; if (affectRotation) { ToRotation = toRot.Value; } } this.Time = _time; this.Duration = Mathf.Max(duration, 0.00001f); //prevent divide by zero errors this.Done = false; }
/// <summary> /// The SetActualTeleportDestination method forces the destination of a teleport event to the given Vector3. /// </summary> /// <param name="actualPosition">The actual position that the teleport event should use as the final location.</param> /// <param name="actualRotation">The actual rotation that the teleport event should use as the final location.</param> public virtual void SetActualTeleportDestination(Vector3 actualPosition, Quaternion?actualRotation) { useGivenForcedPosition = true; givenForcedPosition = actualPosition; givenForcedRotation = actualRotation; }
public void setTargetTurn(Quaternion target) { targetTurn = target; rotSpeed = Quaternion.Angle (transform.rotation, target) / 30f; if (rotSpeed < 2f) { rotSpeed = 2f; } }
internal static NetworkedObject CreateSpawnedObject(int networkedPrefabId, uint networkId, uint owner, bool playerObject, uint sceneSpawnedInIndex, bool sceneDelayedSpawn, bool destroyWithScene, Vector3?position, Quaternion?rotation, bool isActive, Stream stream, bool readPayload, int payloadLength, bool readNetworkedVar) { if (networkedPrefabId >= netManager.NetworkConfig.NetworkedPrefabs.Count || networkedPrefabId < 0) { if (LogHelper.CurrentLogLevel <= LogLevel.Normal) { LogHelper.LogWarning("Cannot spawn the object, invalid prefabIndex: " + networkedPrefabId); } return(null); } //Delayed spawning if (sceneDelayedSpawn && sceneSpawnedInIndex != NetworkSceneManager.CurrentActiveSceneIndex) { GameObject prefab = netManager.NetworkConfig.NetworkedPrefabs[networkedPrefabId].prefab; bool prefabActive = prefab.activeSelf; prefab.SetActive(false); GameObject go = (position == null && rotation == null) ? MonoBehaviour.Instantiate(prefab) : MonoBehaviour.Instantiate(prefab, position.GetValueOrDefault(Vector3.zero), rotation.GetValueOrDefault(Quaternion.identity)); prefab.SetActive(prefabActive); //Appearantly some wierd behavior when switching scenes can occur that destroys this object even though the scene is //not destroyed, therefor we set it to DontDestroyOnLoad here, to prevent that problem. MonoBehaviour.DontDestroyOnLoad(go); NetworkedObject netObject = go.GetComponent <NetworkedObject>(); if (netObject == null) { if (LogHelper.CurrentLogLevel <= LogLevel.Normal) { LogHelper.LogWarning("Please add a NetworkedObject component to the root of all spawnable objects"); } netObject = go.AddComponent <NetworkedObject>(); } netObject.NetworkedPrefabName = netManager.NetworkConfig.NetworkedPrefabs[networkedPrefabId].name; netObject.IsSpawned = false; netObject.IsPooledObject = false; if (netManager.IsServer) { netObject.NetworkId = GetNetworkObjectId(); } else { netObject.NetworkId = networkId; } netObject.destroyWithScene = destroyWithScene; netObject.OwnerClientId = owner; netObject.IsPlayerObject = playerObject; netObject.SceneDelayedSpawn = sceneDelayedSpawn; netObject.sceneSpawnedInIndex = sceneSpawnedInIndex; Dictionary <ushort, List <INetworkedVar> > dummyNetworkedVars = new Dictionary <ushort, List <INetworkedVar> >(); List <NetworkedBehaviour> networkedBehaviours = new List <NetworkedBehaviour>(netObject.GetComponentsInChildren <NetworkedBehaviour>()); for (ushort i = 0; i < networkedBehaviours.Count; i++) { dummyNetworkedVars.Add(i, networkedBehaviours[i].GetDummyNetworkedVars()); } PendingSpawnObject pso = new PendingSpawnObject() { netObject = netObject, dummyNetworkedVars = dummyNetworkedVars, sceneSpawnedInIndex = sceneSpawnedInIndex, playerObject = playerObject, owner = owner, isActive = isActive, payload = null }; PendingSpawnObjects.Add(netObject.NetworkId, pso); pso.SetNetworkedVarData(stream); if (readPayload) { MLAPI.Serialization.BitStream payloadStream = new MLAPI.Serialization.BitStream(); payloadStream.CopyUnreadFrom(stream, payloadLength); stream.Position += payloadLength; pso.payload = payloadStream; } return(netObject); } //Normal spawning { GameObject prefab = netManager.NetworkConfig.NetworkedPrefabs[networkedPrefabId].prefab; GameObject go = (position == null && rotation == null) ? MonoBehaviour.Instantiate(prefab) : MonoBehaviour.Instantiate(prefab, position.GetValueOrDefault(Vector3.zero), rotation.GetValueOrDefault(Quaternion.identity)); NetworkedObject netObject = go.GetComponent <NetworkedObject>(); if (netObject == null) { if (LogHelper.CurrentLogLevel <= LogLevel.Normal) { LogHelper.LogWarning("Please add a NetworkedObject component to the root of all spawnable objects"); } netObject = go.AddComponent <NetworkedObject>(); } if (readNetworkedVar) { netObject.SetNetworkedVarData(stream); } netObject.NetworkedPrefabName = netManager.NetworkConfig.NetworkedPrefabs[networkedPrefabId].name; netObject.IsSpawned = true; netObject.IsPooledObject = false; if (netManager.IsServer) { netObject.NetworkId = GetNetworkObjectId(); } else { netObject.NetworkId = networkId; } netObject.destroyWithScene = destroyWithScene; netObject.OwnerClientId = owner; netObject.IsPlayerObject = playerObject; netObject.SceneDelayedSpawn = sceneDelayedSpawn; netObject.sceneSpawnedInIndex = sceneSpawnedInIndex; SpawnedObjects.Add(netObject.NetworkId, netObject); SpawnedObjectsList.Add(netObject); if (playerObject) { NetworkingManager.Singleton.ConnectedClients[owner].PlayerObject = netObject; } if (readPayload) { using (PooledBitStream payloadStream = PooledBitStream.Get()) { payloadStream.CopyUnreadFrom(stream, payloadLength); stream.Position += payloadLength; netObject.InvokeBehaviourNetworkSpawn(payloadStream); } } else { netObject.InvokeBehaviourNetworkSpawn(null); } netObject.gameObject.SetActive(isActive); return(netObject); } }
public void ResetOrientation() { mInitialGyro = null; }
internal static void HandleConnectionApproved(ulong clientId, Stream stream, float receiveTime) { using (PooledBitReader reader = PooledBitReader.Get(stream)) { NetworkingManager.Singleton.LocalClientId = reader.ReadUInt64Packed(); uint sceneIndex = reader.ReadUInt32Packed(); Guid sceneSwitchProgressGuid = new Guid(reader.ReadByteArray()); float netTime = reader.ReadSinglePacked(); NetworkingManager.Singleton.UpdateNetworkTime(clientId, netTime, receiveTime, true); NetworkingManager.Singleton.ConnectedClients.Add(NetworkingManager.Singleton.LocalClientId, new NetworkedClient() { ClientId = NetworkingManager.Singleton.LocalClientId }); bool sceneSwitch = NetworkSceneManager.HasSceneMismatch(sceneIndex); void DelayedSpawnAction(Stream continuationStream) { using (PooledBitReader continuationReader = PooledBitReader.Get(continuationStream)) { if (NetworkingManager.Singleton.NetworkConfig.UsePrefabSync) { SpawnManager.DestroySceneObjects(); } else { SpawnManager.ClientCollectSoftSyncSceneObjectSweep(null); } uint objectCount = continuationReader.ReadUInt32Packed(); for (int i = 0; i < objectCount; i++) { bool isPlayerObject = continuationReader.ReadBool(); ulong networkId = continuationReader.ReadUInt64Packed(); ulong ownerId = continuationReader.ReadUInt64Packed(); bool hasParent = continuationReader.ReadBool(); ulong?parentNetworkId = null; if (hasParent) { parentNetworkId = continuationReader.ReadUInt64Packed(); } ulong prefabHash; ulong instanceId; bool softSync; if (NetworkingManager.Singleton.NetworkConfig.UsePrefabSync) { softSync = false; instanceId = 0; prefabHash = continuationReader.ReadUInt64Packed(); } else { softSync = continuationReader.ReadBool(); if (softSync) { instanceId = continuationReader.ReadUInt64Packed(); prefabHash = 0; } else { prefabHash = continuationReader.ReadUInt64Packed(); instanceId = 0; } } Vector3? pos = null; Quaternion?rot = null; if (continuationReader.ReadBool()) { pos = new Vector3(continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked()); rot = Quaternion.Euler(continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked()); } NetworkedObject netObject = SpawnManager.CreateLocalNetworkedObject(softSync, instanceId, prefabHash, parentNetworkId, pos, rot); SpawnManager.SpawnNetworkedObjectLocally(netObject, networkId, softSync, isPlayerObject, ownerId, continuationStream, false, 0, true, false); } NetworkingManager.Singleton.IsConnectedClient = true; if (NetworkingManager.Singleton.OnClientConnectedCallback != null) { NetworkingManager.Singleton.OnClientConnectedCallback.Invoke(NetworkingManager.Singleton.LocalClientId); } } } if (sceneSwitch) { UnityAction <Scene, Scene> onSceneLoaded = null; Serialization.BitStream continuationStream = new Serialization.BitStream(); continuationStream.CopyUnreadFrom(stream); continuationStream.Position = 0; void OnSceneLoadComplete() { SceneManager.activeSceneChanged -= onSceneLoaded; NetworkSceneManager.isSpawnedObjectsPendingInDontDestroyOnLoad = false; DelayedSpawnAction(continuationStream); } onSceneLoaded = (oldScene, newScene) => { OnSceneLoadComplete(); }; SceneManager.activeSceneChanged += onSceneLoaded; NetworkSceneManager.OnFirstSceneSwitchSync(sceneIndex, sceneSwitchProgressGuid); } else { DelayedSpawnAction(stream); } } }
public BlockBounds SetToRotationFrom(Quaternion rotation, Vector3 pivot, BlockBounds originalBounds = null) { if (originalBounds == null) { originalBounds = this; } _rotation = rotation; Vector3 r1 = MathHelper.RotateAroundPivot(new Vector3(originalBounds.MinX, originalBounds.MinY, originalBounds.MinZ), pivot, rotation); Vector3 r2 = MathHelper.RotateAroundPivot(new Vector3(originalBounds.MaxX, originalBounds.MaxY, originalBounds.MaxZ), pivot, rotation); MinX = MathHelper.RoundToDp(Mathf.Min(r1.x, r2.x), 4); MinY = MathHelper.RoundToDp(Mathf.Min(r1.y, r2.y), 4); MinZ = MathHelper.RoundToDp(Mathf.Min(r1.z, r2.z), 4); MaxX = MathHelper.RoundToDp(Mathf.Max(r1.x, r2.x), 4); MaxY = MathHelper.RoundToDp(Mathf.Max(r1.y, r2.y), 4); MaxZ = MathHelper.RoundToDp(Mathf.Max(r1.z, r2.z), 4); return this; }
public static List <KeyValuePair <string, ImportedAnimationSampledTrack> > CopySampledAnimation(WorkspaceAnimation wsAnimation, int resampleCount, bool linear) { List <ImportedAnimationSampledTrack> trackList = ((ImportedSampledAnimation)wsAnimation.importedAnimation).TrackList; List <KeyValuePair <string, ImportedAnimationSampledTrack> > newTrackList = new List <KeyValuePair <string, ImportedAnimationSampledTrack> >(trackList.Count); List <Tuple <ImportedAnimationTrack, ImportedAnimationSampledTrack> > interpolateTracks = new List <Tuple <ImportedAnimationTrack, ImportedAnimationSampledTrack> >(); foreach (var wsTrack in trackList) { if (!wsAnimation.isTrackEnabled(wsTrack)) { continue; } ImportedAnimationSampledTrack track = new ImportedAnimationSampledTrack(); bool interpolateTrack = false; Vector3?[] scalings = wsTrack.Scalings; Vector3?[] newScalings = null; if (resampleCount < 0 || scalings.Length == resampleCount) { newScalings = new Vector3?[scalings.Length]; for (int i = 0; i < scalings.Length; i++) { Vector3?scale = scalings[i]; if (scale == null) { continue; } newScalings[i] = scale.Value; } } else { if (scalings.Length < 1) { newScalings = new Vector3?[resampleCount]; for (int i = 0; i < newScalings.Length; i++) { newScalings[i] = new Vector3(1, 1, 1); } } else { interpolateTrack = true; } } Quaternion?[] rotations = wsTrack.Rotations; Quaternion?[] newRotations = null; if (resampleCount < 0 || rotations.Length == resampleCount) { newRotations = new Quaternion?[rotations.Length]; for (int i = 0; i < rotations.Length; i++) { Quaternion?rotate = rotations[i]; if (rotate == null) { continue; } newRotations[i] = rotate.Value; } } else { if (rotations.Length < 1) { newRotations = new Quaternion?[resampleCount]; for (int i = 0; i < newRotations.Length; i++) { newRotations[i] = Quaternion.Identity; } } else { interpolateTrack = true; } } Vector3?[] translations = wsTrack.Translations; Vector3?[] newTranslations = null; if (resampleCount < 0 || translations.Length == resampleCount) { newTranslations = new Vector3?[translations.Length]; for (int i = 0; i < translations.Length; i++) { Vector3?translate = translations[i]; if (translate == null) { continue; } newTranslations[i] = translate.Value; } } else { if (translations.Length < 1) { newTranslations = new Vector3?[resampleCount]; for (int i = 0; i < newTranslations.Length; i++) { newTranslations[i] = new Vector3(0, 0, 0); } } else { interpolateTrack = true; } } if (interpolateTrack) { interpolateTracks.Add(new Tuple <ImportedAnimationTrack, ImportedAnimationSampledTrack>(wsTrack, track)); } track.Scalings = newScalings; track.Rotations = newRotations; track.Translations = newTranslations; newTrackList.Add(new KeyValuePair <string, ImportedAnimationSampledTrack>(wsTrack.Name, track)); } if (interpolateTracks.Count > 0) { Fbx.InterpolateSampledTracks(interpolateTracks, resampleCount, linear); } return(newTrackList); }
public void SetCameraRot(Vector3 euler, bool bRightNow = false) { if (bRightNow) { transform.rotation = Quaternion.Euler(euler); m_EndRot = null; } else { m_EndRot = Quaternion.Euler(euler); } }
public CommandTarget(SerializationInfo info, StreamingContext context) { _target = info.GetValue(nameof(_target), _target); _explicitPosition = ((SerializedV3)info.GetValue(nameof(_explicitPosition), typeof(SerializedV3))).Value; _explicitRotation = ((SerializedQuaternion)info.GetValue(nameof(_explicitRotation), typeof(SerializedQuaternion))).Value; }
void Recenter() { VR.InputTracking.Recenter(); baseRot = camera.localRotation; }
public GenericNetworkBehavior InstantiateGenericNetworkNetworkObject(int index = 0, Vector3?position = null, Quaternion?rotation = null, bool sendTransform = true) { var go = Instantiate(GenericNetworkNetworkObject[index]); var netBehavior = go.GetComponent <GenericNetworkBehavior>(); var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent <GenericNetworkBehavior>().networkObject = (GenericNetworkNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return(netBehavior); }
public void Remove(DesignPart part) { int index = _parts.IndexOf(part); if (index < 0) { // This should never happen, but no need to complain return; } if (_parts.Count != _pointLights.Count) { throw new ApplicationException("The parts and lights should always be synced"); } HideModifiers(); // PointLight _viewport.Children.Remove(_pointLights[index]); _pointLights.RemoveAt(index); // Part //_parts[index].Part3D.TransformChanged -= new EventHandler(Part3D_TransformChanged); _parts[index].Part3D.IsSelected = false; _parts.RemoveAt(index); if (_parts.Count > 1) { _orientation = _options.DefaultOrientation; } if (_parts.Count > 0 && !this.IsLocked) { // Recalculate the modifiers ShowModifiers(); } }
/// <summary> /// Instantiate an instance of GenericNetwork /// </summary> /// <returns> /// A local instance of GenericNetworkBehavior /// </returns> /// <param name="index">The index of the GenericNetwork prefab in the NetworkManager to Instantiate</param> /// <param name="position">Optional parameter which defines the position of the created GameObject</param> /// <param name="rotation">Optional parameter which defines the rotation of the created GameObject</param> /// <param name="sendTransform">Optional Parameter to send transform data to other connected clients on Instantiation</param> public GenericNetworkBehavior InstantiateGenericNetwork(int index = 0, Vector3?position = null, Quaternion?rotation = null, bool sendTransform = true) { if (GenericNetworkNetworkObject.Length <= index) { Debug.Log("Prefab(s) missing for: GenericNetwork. Add them at the NetworkManager prefab."); return(null); } var go = Instantiate(GenericNetworkNetworkObject[index]); var netBehavior = go.GetComponent <GenericNetworkBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) { obj = netBehavior.CreateNetworkObject(Networker, index); } else { metadata.Clear(); if (position == null && rotation == null) { byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) { ObjectMapper.Instance.MapBytes(metadata, position.Value); } if (rotation != null) { ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent <GenericNetworkBehavior>().networkObject = (GenericNetworkNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return(netBehavior); }
// Quaternion compoundRotation = Quaternion.identity; void DrawRotationAxis(Color color, Vector3 axis, Vector3 worldPosition) { // EventType source = Event.current.rawType; // Make the handle respect the Unity Editor's Local/World orientation mode // Quaternion handleDirection = Quaternion.identity; // if(Tools.pivotRotation == PivotRotation.Local) // { // handleDirection = targetBrush.transform.rotation; // } // Grab a source point and convert from local space to world Vector3 sourceWorldPosition = worldPosition; EditorGUI.BeginChangeCheck(); // Display a handle and allow the user to determine a new position in world space // Vector3 lastEulerAngles = handleDirection.eulerAngles; Handles.color = color; float snapValue = 0; if(CurrentSettings.AngleSnappingEnabled) { snapValue = CurrentSettings.AngleSnapDistance; } Quaternion sourceRotation = Quaternion.identity;// targetBrushTransform.rotation; // Quaternion sourceRotation = targetBrushTransform.rotation; Quaternion newRotation = Handles.Disc(sourceRotation, sourceWorldPosition, axis, HandleUtility.GetHandleSize(sourceWorldPosition), true, snapValue); if(EditorGUI.EndChangeCheck()) { Quaternion deltaRotation = Quaternion.Inverse(targetBrushTransform.rotation) * newRotation; if(!initialRotationOffset.HasValue) { initialRotationOffset = deltaRotation; return; } deltaRotation = Quaternion.Inverse(initialRotationOffset.Value) * deltaRotation; // Quaternion deltaRotation = newRotation; // Quaternion deltaRotation = newRotation * Quaternion.Inverse(targetBrushTransform.rotation); // Debug.Log(deltaRotation.eulerAngles); if(CurrentSettings.AngleSnappingEnabled) { Quaternion plusSnap = Quaternion.AngleAxis(CurrentSettings.AngleSnapDistance, axis);// * baseRotation; Quaternion zeroSnap = Quaternion.identity;// * baseRotation; Quaternion negativeSnap = Quaternion.AngleAxis(-CurrentSettings.AngleSnapDistance, axis);// * baseRotation; float angleZero = Quaternion.Angle(deltaRotation, zeroSnap); float anglePlus = Quaternion.Angle(deltaRotation, plusSnap); float angleNegative = Quaternion.Angle(deltaRotation, negativeSnap); // Debug.Log("A0 " + angleZero + ", A+ " + anglePlus + ", A- " + angleNegative); if(anglePlus < angleZero) { RotateBrushes(plusSnap, sourceWorldPosition); } else if(angleNegative < angleZero) { RotateBrushes(negativeSnap, sourceWorldPosition); } } else { RotateBrushes(deltaRotation, sourceWorldPosition); } } }
public virtual T Spawn <T>(string performName, BaseCoreMono castMono, Vector3?position = null, Quaternion?quaternion = null, params object[] ps) where T : BasePerform { if (performName.IsInvStr()) { return(null); } if (SelfBaseGlobal.PoolMgr.Perform == null) { return(null); } GameObject temp = null; temp = SelfBaseGlobal.PoolMgr.Perform.Spawn(SelfBaseGlobal.GRMgr.GetPerform(performName), position, quaternion); return(Spawn <T>(castMono, position, quaternion, temp, ps)); }
public override void DragItem(RayHitTestParameters ray) { if (_circleCenter == null || _circleOrientation == null) { throw new InvalidOperationException("CircleCenter and CircleOrientation need to be set before calling this method"); } // See where on the circle they clicked // If the method comes back false, it's a very rare case, so just don't drag the ring Point3D[] nearestCirclePoints, nearestLinePoints; if (Math3D.GetClosestPoints_Circle_Line(out nearestCirclePoints, out nearestLinePoints, _circlePlane, _circleCenter.Value, _radius, ray.Origin, ray.Direction, Math3D.RayCastReturn.ClosestToRay)) { // Figure out what angle they clicked on Quaternion clickQuat = GetAngle(nearestCirclePoints[0]); // Subtract off off where they first clicked (start drag already negated _mouseDownAngle and made it unit) clickQuat = Quaternion.Multiply(_mouseDownAngle, clickQuat.ToUnit()); // Now store the new location _circleOrientation = Quaternion.Multiply(clickQuat.ToUnit(), _circleOrientation.Value.ToUnit()); } }
void Recenter() { VR.InputTracking.Recenter(); baseRot = camera.localRotation; }