private static void ScrollToTop() { sm_log.Info("Scrolling sidebar to top"); var sidebarRect = new Rectangle(ScreenCapture.ScreenBounds.Location, new Size(ScreenLayout.SidebarWidth, SidebarUtil.MaxHeight)); const int maxIterations = 100; for (int i = 0; i < maxIterations; i++) { // Drag upwards as much as we can MouseUtils.RightDrag(sidebarRect.Location, new Point(sidebarRect.Left, ScreenCapture.ScreenBounds.Height - 1)); // To check if we've reached the top, try to drag upwards one more pixel. If nothing changes, // we're almost definitely at the top! using (var capture1 = new ScreenCapture(sidebarRect)) { MouseUtils.RightDrag(sidebarRect.Location, sidebarRect.Location.Add(new Point(0, 1))); using (var capture2 = new ScreenCapture(sidebarRect)) { if (BitmapComparer.AreBitmapsIdentical(capture1.Bitmap, capture2.Bitmap)) { return; } } } } throw new AnalysisException(Invariant($"Failed to scroll to the top of the sidebar after {maxIterations} attempts.")); }
/// <summary> /// Try to build cable /// </summary> private void Build() { if (startPoint == endPoint || Mathf.Abs(startPointVector.x - endPointVector.x) > 2.5 || Mathf.Abs(startPointVector.y - endPointVector.y) > 2.5) { return; } GameObject target = MouseUtils.GetOrderedObjectsUnderMouse().FirstOrDefault(); ConnectionApply cableApply = ConnectionApply.ByLocalPlayer(target, startPoint, endPoint, null); //if HandObject is null, then its an empty hand apply so we only need to check the receiving object if (cableApply.HandObject != null) { //get all components that can contains CableApply interaction var cableAppliables = cableApply.HandObject.GetComponents <MonoBehaviour>() .Where(c => c != null && c.enabled && (c is IBaseInteractable <ConnectionApply>)); foreach (var cableAppliable in cableAppliables.Reverse()) { var hap = cableAppliable as IBaseInteractable <ConnectionApply>; if (hap.ClientCheckAndTrigger(cableApply)) { return; } } } }
private bool DragAreaWithVerticalCheck(Point start, Point end) { using (var capture1 = new ScreenCapture(VerticalCheckRect.Value)) { MouseUtils.RightDrag(start, end, ScrollDelay); using (var capture2 = new ScreenCapture(VerticalCheckRect.Value)) { if (!BitmapComparer.AreBitmapsIdentical(capture1.Bitmap, capture2.Bitmap)) { sm_log.Info("Drag successful"); return(true); } sm_log.Warn(Invariant($"Attempted to drag from {start} to {end} but detected no vertical movement. Waiting a little while before checking again...")); ThreadUtils.SleepOrAbort(100 + ScrollDelay); using (var capture3 = new ScreenCapture(VerticalCheckRect.Value)) { if (!BitmapComparer.AreBitmapsIdentical(capture1.Bitmap, capture3.Bitmap)) { sm_log.Info("Drag successful"); return(true); } sm_log.Warn("Still no vertical movement detected"); return(false); } } } }
private void DragArea(Point start, Point end) { if (start.X != end.X || !VerticalCheckRect.HasValue) { MouseUtils.RightDrag(start, end, ScrollDelay); return; } const int maxAttempts = 5; if (!DragAreaWithVerticalCheck(start, end)) { for (int i = 1; i < maxAttempts; i++) { ScrollDelay += 100; sm_log.Info("Increasing scroll delay to " + ScrollDelay); sm_log.Info("Retrying scroll..."); if (DragAreaWithVerticalCheck(start, end)) { return; } } throw new InvalidOperationException(Invariant($"Attempted to drag from {start} to {end} but no movement detected after {maxAttempts} attempts.")); } }
private void CheckDragV2() { if (EventSystem.current.IsPointerOverGameObject()) { //currently UI is not a part of interaction framework V2 return; } //currently there is nothing for ghosts to interact with, they only can change facing if (PlayerManager.LocalPlayerScript.IsGhost) { return; } var draggable = MouseUtils.GetOrderedObjectsUnderMouse(layerMask, go => go.GetComponent <MouseDraggable>() != null && go.GetComponent <MouseDraggable>().CanBeginDrag(PlayerManager.LocalPlayer)) //get the root gameobject of the draggable .Select(sr => sr.GetComponentInParent <MouseDraggable>().gameObject) //only want distinct game objects even if we hit multiple renderers on one object. .Distinct() .FirstOrDefault(); if (draggable != null) { //start dragging the first draggable we found draggable.GetComponent <MouseDraggable>().BeginDrag(); } }
public void Calibrate() { sm_log.Info("Calibrating center of hex grid"); // Drag a glyph of equilibrium onto the center of the grid var toolLocation = m_sidebar.ScrollTo(m_sidebar.Glyphs, m_sidebar.Glyphs[GlyphType.Equilibrium]); var gridLocation = m_grid.GetScreenLocationForCell(new Vector2(0, 0)); MouseUtils.LeftDrag(toolLocation, gridLocation); // Find where the glyph actually ended up on the screen - this will be the exact center of a hex // near the center of the screen. var actualCenter = FindGlyph(m_grid.CenterLocation); sm_log.Info(Invariant($"Actual hex center is {actualCenter}")); // Scroll the grid so this actual center is exactly where we want it var desiredCenter = m_grid.Rect.Location.Add(new Point(m_grid.Rect.Width / 2, m_grid.Rect.Height / 2)).Add(CenterOffset); MouseUtils.RightDrag(actualCenter, desiredCenter); m_grid.CenterLocation = desiredCenter; // Delete the glyph from the grid KeyboardUtils.KeyPress(Keys.Z); }
/// <summary> /// Create an AimAPply for the local player aiming at the current mouse position with the item in their /// active hand slot. /// </summary> /// <param name="buttonState">state of mouse (initial click vs. being held after a click)</param> /// <returns></returns> public static AimApply ByLocalPlayer(MouseButtonState buttonState) { //Check for self aim if (PLAYER_LAYER_MASK == -1) { PLAYER_LAYER_MASK = LayerMask.GetMask("Players"); } var InternaltargetPosition = MouseUtils.MouseToWorldPos().ToLocal(PlayerManager.LocalPlayer.RegisterTile().Matrix).To2(); //check for self aim if target vector is sufficiently small so we can avoid raycast var selfAim = false; var targetVector = (Vector2)MouseUtils.MouseToWorldPos() - (Vector2)PlayerManager.LocalPlayer.transform.position; if (targetVector.magnitude < 0.6) { selfAim = MouseUtils.GetOrderedObjectsUnderMouse(PLAYER_LAYER_MASK, go => go == PlayerManager.LocalPlayer).Any(); } return(new AimApply(PlayerManager.LocalPlayer, PlayerManager.LocalPlayerScript.DynamicItemStorage.GetActiveHandSlot().ItemObject, PlayerManager.LocalPlayerScript.DynamicItemStorage.GetActiveHandSlot(), buttonState, selfAim ? PlayerManager.LocalPlayer.transform.localPosition.To2() : InternaltargetPosition, UIManager.DamageZone, UIManager.CurrentIntent, PlayerManager.LocalPlayer.transform.localPosition.To2())); }
private bool CheckClick() { ChangeDirection(); //currently there is nothing for ghosts to interact with, they only can change facing if (PlayerManager.LocalPlayerScript.IsGhost) { return(false); } bool ctrlClick = KeyboardInputManager.IsControlPressed(); if (!ctrlClick) { var handApplyTargets = MouseUtils.GetOrderedObjectsUnderMouse(layerMask); //go through the stack of objects and call any interaction components we find foreach (GameObject applyTarget in handApplyTargets) { if (CheckHandApply(applyTarget)) { return(true); } } } return(false); }
private async Task ExecuteActions(List <ClickAction> actions) { int totalActions = actions.Count; for (int i = 0; i < totalActions; i++) { var action = actions[i]; await Task.Delay(TimeSpan.FromMilliseconds(action.MilisecondsEllapsed)); //skip the last action, where we press the stop button if (i == totalActions - 1) { continue; } MouseUtils.MoveToScreenCoordinate(action.X, action.Y); if (action.ButtonClicked == MouseButtons.Left) { MouseUtils.LeftClick(); } else if (action.ButtonClicked == MouseButtons.Right) { MouseUtils.RightClick(); } } }
/// <summary> /// Creates a CableApply interaction performed by the local player targeting the specified object. /// </summary> /// <param name="targetObject">object targeted by the interaction, null to target empty space</param> /// <param name="wireEndA">cable start connection</param> /// <param name="wireEndB">cable end connection</param> /// <param name="worldPositionTarget">position of target tile (world space)</param> /// <returns></returns> public static ConnectionApply ByLocalPlayer(GameObject targetObject, Connection wireEndA, Connection wireEndB, Vector3?IntargetVector) { if (PlayerManager.LocalPlayerScript.IsGhost) { return(Invalid); } Vector3 targetVec; if (IntargetVector != null) { targetVec = IntargetVector.Value; } else { targetVec = MouseUtils.MouseToWorldPos().ToLocal(PlayerManager.LocalPlayer.RegisterTile().Matrix); } return(new ConnectionApply( PlayerManager.LocalPlayer, PlayerManager.LocalPlayerScript.DynamicItemStorage.GetActiveHandSlot().ItemObject, targetObject, wireEndA, wireEndB, targetVec, PlayerManager.LocalPlayerScript.DynamicItemStorage.GetActiveHandSlot(), UIManager.CurrentIntent )); }
private void OnDragEnd() { UIManager.IsMouseInteractionDisabled = false; Destroy(shadowObject); shadowObject = null; if (lightingSystem.enabled && !lightingSystem.IsScreenPointVisible(CommonInput.mousePosition)) { //do nothing, the point is not visible. return; } //check what we dropped on, which may or may not have mousedrop interaction components //can only drop on things that have a RegisterTile var dropTargets = MouseUtils.GetOrderedObjectsUnderMouse(); //go through the stack of objects and call any drop components we find foreach (GameObject dropTarget in dropTargets) { MouseDrop info = MouseDrop.ByLocalPlayer(gameObject, dropTarget.gameObject); //call this object's mousedrop interaction methods if it has any, for each object we are dropping on if (InteractionUtils.ClientCheckAndTrigger(mouseDrops, info) != null) { return; } var targetComps = dropTarget.GetComponents <IBaseInteractable <MouseDrop> >() .Where(mb => mb != null && (mb as MonoBehaviour).enabled); if (InteractionUtils.ClientCheckAndTrigger(targetComps, info) != null) { return; } } }
private void CheckInitiatePull() { //checks if there is anything in reach we can drag var topObject = MouseUtils.GetOrderedObjectsUnderMouse(null, go => go.GetComponent <PushPull>() != null).FirstOrDefault(); if (topObject != null) { PushPull pushPull = null; // If the topObject has a PlayerMove, we check if he is buckled // The PushPull object we want in this case, is the chair/object on which he is buckled to if (topObject.TryGetComponent <PlayerMove>(out var playerMove) && playerMove.IsBuckled) { pushPull = playerMove.BuckledObject.GetComponent <PushPull>(); } else { pushPull = topObject.GetComponent <PushPull>(); } if (pushPull != null) { pushPull.TryPullThis(); } }
private void FixedUpdate() { if (!changeSpeed) { return; } Vector2 direction = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y")).normalized; //Point cursorSpeed = new Point(Mathf.RoundToInt(direction.x * speed), Mathf.RoundToInt(direction.y * speed)); ////Point difference = MouseUtils.GetSystemMousePos() - lastMousePos; ////Point newPos = MouseUtils.GetSystemMousePos() + new Point(Mathf.RoundToInt(difference.x * speed), Mathf.RoundToInt(difference.y * speed)); Point currentMousePosition = MouseUtils.GetSystemMousePos(); //Vector2 targetPos = new Vector2(currentMousePosition.x + cursorSpeed.x, currentMousePosition.y + cursorSpeed.y); //v2ToSet = Vector2.SmoothDamp(v2ToSet, targetPos, ref velRef, accel); //StartCoroutine(MouseUtils.SetRelativeMousePosUnconstrained(new Point(Mathf.RoundToInt(v2ToSet.x), Mathf.RoundToInt(v2ToSet.y)))); Point newPoint = currentMousePosition + new Point(Mathf.RoundToInt(direction.x * speed), Mathf.RoundToInt(direction.y * speed)); MouseUtils.SetSystemMousePos(newPoint); }
private void CheckHover() { //can only hover on things within FOV if (lightingSystem.enabled && !lightingSystem.IsScreenPointVisible(CommonInput.mousePosition)) { if (lastHoveredThing) { lastHoveredThing.transform.SendMessageUpwards("OnHoverEnd", SendMessageOptions.DontRequireReceiver); } lastHoveredThing = null; return; } var hit = MouseUtils.GetOrderedObjectsUnderMouse(layerMask).FirstOrDefault(); if (hit != null) { if (lastHoveredThing != hit) { if (lastHoveredThing) { lastHoveredThing.transform.SendMessageUpwards("OnHoverEnd", SendMessageOptions.DontRequireReceiver); } hit.transform.SendMessageUpwards("OnHoverStart", SendMessageOptions.DontRequireReceiver); lastHoveredThing = hit; } hit.transform.SendMessageUpwards("OnHover", SendMessageOptions.DontRequireReceiver); } }
private void Update() { var mouseAngle = MouseUtils.GetMouseAndTargetAngle(transform.position); SetMovementParams(); LookAtCursor(mouseAngle); }
private void Update() { if (state == State.SELECTING) { // ignore when we are over UI if (EventSystem.current.IsPointerOverGameObject()) { return; } //check which objects we are over, pick the top one to spawn if (CommonInput.GetMouseButtonDown(0)) { //NOTE: Avoiding multiple enumeration by converting IEnumerables to lists. var hitGOs = MouseUtils.GetOrderedObjectsUnderMouse(layerMask, go => go.GetComponent <CustomNetTransform>() != null).ToList(); //warn about objects which cannot be cloned var nonPooledHits = hitGOs .Where(go => Spawn.DeterminePrefab(go) == null).ToList(); if (nonPooledHits.Any()) { foreach (GameObject nonPooled in nonPooledHits) { Logger.LogWarningFormat("Object {0} does not have a PoolPrefabTracker component and its name" + " did not match one of our existing prefabs " + "therefore cannot be cloned (because we wouldn't know which prefab to instantiate). " + "Please attach this component to the object and specify the prefab" + " to allow it to be cloned.", Category.ItemSpawn, nonPooled.name); } } var pooledHits = hitGOs.Where(go => Spawn.DeterminePrefab(go) != null).ToList(); if (pooledHits.Any()) { toClone = pooledHits.First(); ToState(State.DRAWING); } } } else if (state == State.DRAWING) { cursorObject.transform.position = Camera.main.ScreenToWorldPoint(CommonInput.mousePosition); if (CommonInput.GetMouseButtonDown(0)) { Vector3Int position = cursorObject.transform.position.RoundToInt(); position.z = 0; if (MatrixManager.IsPassableAtAllMatricesOneTile(position, false)) { if (CustomNetworkManager.IsServer) { Spawn.ServerClone(toClone, position); } else { DevCloneMessage.Send(toClone, (Vector3)position, ServerData.UserID, PlayerList.Instance.AdminToken); } } } } }
/// <summary> /// [Message Handler] Perform cable cutting interaction on server side /// </summary> private void ServerPerformCableCuttingInteraction(NetworkConnection conn, CableCuttingWindow.CableCuttingMessage message) { // get object at target position GameObject hit = MouseUtils.GetOrderedObjectsAtPoint(message.targetWorldPosition).FirstOrDefault(); // get matrix Matrix matrix = hit.GetComponentInChildren <Matrix>(); // return if matrix is null if (matrix == null) { return; } // convert world position to cell position and set Z value to Z value from message Vector3Int targetCellPosition = matrix.MetaTileMap.WorldToCell(message.targetWorldPosition); targetCellPosition.z = message.positionZ; // get electical tile from targetCellPosition ElectricalCableTile electricalCable = matrix.UnderFloorLayer.GetTileUsingZ(targetCellPosition) as ElectricalCableTile; if (electricalCable == null) { return; } // add messages to chat string othersMessage = Chat.ReplacePerformer(othersStartActionMessage, message.performer); Chat.AddActionMsgToChat(message.performer, performerStartActionMessage, othersMessage); // source: ElectricalCableDeconstruction.cs var metaDataNode = matrix.GetMetaDataNode(targetCellPosition); foreach (var ElectricalData in metaDataNode.ElectricalData) { if (ElectricalData.RelatedTile != electricalCable) { continue; } // Electrocute the performer. If shock is painful enough, cancel the interaction. ElectricityFunctions.WorkOutActualNumbers(ElectricalData.InData); float voltage = ElectricalData.InData.Data.ActualVoltage; var electrocution = new Electrocution(voltage, message.targetWorldPosition, "cable"); var performerLHB = message.performer.GetComponent <LivingHealthBehaviour>(); var severity = performerLHB.Electrocute(electrocution); if (severity > LivingShockResponse.Mild) { return; } ElectricalData.InData.DestroyThisPlease(); Spawn.ServerPrefab(electricalCable.SpawnOnDeconstruct, message.targetWorldPosition, count: electricalCable.SpawnAmountOnDeconstruct); return; } }
private IEnumerable <PaletteInfo> FindPalettes() { sm_log.Info("Finding palettes"); int startY = 0; int prevNextHeaderY = 0; int scrollPosition = 0; for (int i = 0; i < NumPalettes; i++) { using (var capture = new ScreenCapture(SidebarRect)) { int?headerY = SidebarUtil.FindPaletteHeader(capture.Bitmap, startY); if (headerY == null) { throw new AnalysisException(Invariant($"Expected to find {NumPalettes} palettes but only found {i}.")); } if (i > 0) { scrollPosition += prevNextHeaderY - headerY.Value; } int?nextHeaderY = SidebarUtil.FindPaletteHeader(capture.Bitmap, headerY.Value + 1); if (nextHeaderY.HasValue) { // Capture between the two palette headers int y = headerY.Value + PaletteHeaderHeight; yield return(new PaletteInfo { Capture = capture.Clone(new Rectangle(0, y, capture.Rect.Width, nextHeaderY.Value - y - PaletteBottomSeparationHeight)), ScrollPosition = new Point(0, scrollPosition) }); if (m_isScrollable) { // Scroll the next palette up so it's adjacent to the previous one (if possible) MouseUtils.RightDrag(SidebarRect.Location.Add(new Point(0, nextHeaderY.Value)), SidebarRect.Location.Add(new Point(0, headerY.Value + PaletteHeaderSeparationHeight))); } prevNextHeaderY = nextHeaderY.Value; } else { // This must be the last palette, so capture to the bottom of the sidebar int y = headerY.Value + PaletteHeaderHeight; yield return(new PaletteInfo { Capture = capture.Clone(new Rectangle(0, y, capture.Rect.Width, capture.Rect.Height - y - PaletteFooterHeight)), ScrollPosition = new Point(0, scrollPosition) }); } // Next iteration, start looking for the palette just below the previous one startY = headerY.Value + 1; } } }
private void Update() { if (IsActivated) { bezierRenderer.ControlPoints[0] = transform.position; bezierRenderer.ControlPoints[1] = MouseUtils.MouseWorldPositionAtLevel(transform.position.y); bezierRenderer.DrawCurve(); } }
public bool IsWithinSelectionBounds(GameObject gameObject) { Camera camera = Camera.main; Bounds viewportBounds = MouseUtils.GetViewportBounds(camera, firstPosition, Input.mousePosition); return(viewportBounds.Contains( camera.WorldToViewportPoint(gameObject.transform.position))); }
private void PlaybackMouse(Record record) { //pipeClient.SendRequest(record); //return; CursorPoint newPos = record.EventMouse.Location; MouseHook.MouseEvents mEvent = record.EventMouse.Action; MouseUtils.PerformMouseEvent(mEvent, newPos); }
/// <summary> /// Handle the mouse click events. /// </summary> public virtual void Handle() { MouseButtons button = MouseButtons.None; if (MouseUtils.AnyButtonPressed(out button)) { if (MouseDown != null) { MouseDown(this, new MouseButtonEventArgs(button, MouseUtils.Position)); } else { OnMouseDown(); } if (Click == null || !Click(this, new MouseButtonEventArgs(button, MouseUtils.Position))) { Focus(); switch (button) { case MouseButtons.Left: OnLeftClick(); break; case MouseButtons.Middle: OnMiddleClick(); break; case MouseButtons.Right: OnRightClick(); break; case MouseButtons.XButton1: OnXButton1Click(); break; case MouseButtons.XButton2: OnXButton2Click(); break; } } } if (MouseUtils.AnyButtonReleased(out button)) { if (MouseUp != null) { MouseUp(this, new MouseButtonEventArgs(button, MouseUtils.Position)); } else { OnMouseUp(); } } }
public void OnHover() { if (!UIManager.IsMouseInteractionDisabled && UIManager.Hands.CurrentSlot != null) { // get mouse position Vector3 mousePosition = Camera.main.ScreenToWorldPoint(CommonInput.mousePosition); // round mouse position Vector3Int roundedMousePosition = Vector3Int.RoundToInt(mousePosition); // if distance is greater than interaction distance if (Vector2.Distance(transform.position, (Vector3)roundedMousePosition) > PlayerScript.interactionDistance) { DisableVisualisation(); return; } // if position has changed and player has cable in hand if (roundedMousePosition != lastMouseWordlPositionInt && Validations.HasItemTrait(UIManager.Hands.CurrentSlot.ItemObject, CommonTraits.Instance.Cable)) { lastMouseWordlPositionInt = roundedMousePosition; // get metaTileMap and top tile // MetaTileMap metaTileMap = MatrixManager.AtPoint(roundedMousePosition, false).MetaTileMap; // LayerTile topTile = metaTileMap.GetTile(metaTileMap.WorldToCell(mousePosition), true); // *code above works only on Station matrix // TODO: replace GetComponent solution with some built-in method? var hit = MouseUtils.GetOrderedObjectsUnderMouse().FirstOrDefault(); MetaTileMap metaTileMap = hit.GetComponentInChildren <MetaTileMap>(); if (metaTileMap) { LayerTile topTile = metaTileMap.GetTile(metaTileMap.WorldToCell(roundedMousePosition), true); if (topTile && (topTile.LayerType == LayerType.Base || topTile.LayerType == LayerType.Underfloor)) { // move cable placement visualisation to rounded mouse position and enable it cablePlacementVisualisation.transform.position = roundedMousePosition - new Vector3(0.5f, 0.5f, 0);; cablePlacementVisualisation.SetActive(true); } // disable visualisation if active else { DisableVisualisation(); } } else { DisableVisualisation(); } } } else { DisableVisualisation(); } }
//Spawn a rigid body object, and allow it to live for 10 seconds void SpawnPrimitive(PrimitiveType type) { Vector3 spawnPosition = MouseUtils.GetMouseWorldPositionAtDepth(10); GameObject go = GameObject.CreatePrimitive(type); go.transform.position = spawnPosition; go.AddComponent <Rigidbody>(); GameObject.Destroy(go, 10); }
void OnGUI() { if (drawRect) { // Create a rect from both mouse positions var rect = MouseUtils.GetScreenRect(firstPosition, Input.mousePosition); MouseUtils.DrawScreenRect(rect, new Color(0.8f, 0.8f, 0.95f, 0.25f)); MouseUtils.DrawScreenRectBorder(rect, 2, new Color(0.8f, 0.8f, 0.95f)); } }
// Update is called once per frame void Update() { playerPosition = GameObject.Find("Player").GetComponent <Transform>(); Vector2 mousePos = MouseUtils.GetMousePosition(); float aimAngle = MouseUtils.GetAimAngle(transform.position) * Mathf.Rad2Deg + 180; int stepAngle = Mathf.RoundToInt(360f / rotationSteps); currentStep = Mathf.RoundToInt(aimAngle / stepAngle) % 4 * stepAngle; switch (currentStep) { default: case 0: case 360: playerBody.sprite = rSprite_Torso; playerHead.sprite = rSprite_Head; break; case 45: playerBody.sprite = ruSprite_Torso; playerHead.sprite = ruSprite_Head; break; case 90: playerBody.sprite = uSprite_Torso; playerHead.sprite = uSprite_Head; break; case 135: playerBody.sprite = ulSprite_Torso; playerHead.sprite = ulSprite_Head; break; case 180: playerBody.sprite = lSprite_Torso; playerHead.sprite = lSprite_Head; break; case 225: playerBody.sprite = ldSprite_Torso; playerHead.sprite = ldSprite_Head; break; case 270: playerBody.sprite = dSprite_Torso; playerHead.sprite = dSprite_Head; break; case 315: playerBody.sprite = drSprite_Torso; playerHead.sprite = drSprite_Head; break; } }
/// <summary> /// Checks for a click within the interaction framework v2. Until everything is moved over to V2, /// this will have to be used alongside the old one. /// </summary> private bool CheckClickV2() { //currently there is nothing for ghosts to interact with, they only can change facing if (PlayerManager.LocalPlayerScript.IsGhost) { return(false); } bool ctrlClick = KeyboardInputManager.IsControlPressed(); if (!ctrlClick) { var handApplyTargets = MouseUtils.GetOrderedObjectsUnderMouse(layerMask, go => go.GetComponent <RegisterTile>() != null) //get the root gameobject of the dropped-on sprite renderer .Select(sr => sr.GetComponentInParent <RegisterTile>().gameObject) //only want distinct game objects even if we hit multiple renderers on one object. .Distinct(); //object in hand var handObj = UIManager.Hands.CurrentSlot.Item; //go through the stack of objects and call any drop components we find foreach (GameObject applyTarget in handApplyTargets) { HandApply info = new HandApply(PlayerManager.LocalPlayer, handObj, applyTarget.gameObject); //call the used object's handapply interaction methods if it has any, for each object we are applying to //if handobj is null, then its an empty hand apply so we only need to check the receiving object if (handObj != null) { foreach (IInteractable <HandApply> handApply in handObj.GetComponents <IInteractable <HandApply> >()) { var result = handApply.Interact(info); if (result.SomethingHappened) { //we're done checking, something happened return(true); } } } //call the hand apply interaction methods on the target object if it has any foreach (IInteractable <HandApply> handApply in applyTarget.GetComponents <IInteractable <HandApply> >()) { var result = handApply.Interact(info); if (result.SomethingHappened) { //something happened, done checking return(true); } } } } return(false); }
public void OnHover() { if (!UIManager.IsMouseInteractionDisabled && PlayerManager.LocalPlayerScript?.DynamicItemStorage?.GetActiveHandSlot() != null) { // get mouse position var mousePosition = MouseUtils.MouseToWorldPos().RoundToInt(); // if distance is greater than interaction distance if (Vector2.Distance(transform.position, (Vector3)mousePosition) > PlayerScript.interactionDistance) { DisableVisualisation(); return; } // if position has changed and player has cable in hand if (mousePosition != lastMouseWordlPositionInt && Validations.HasItemTrait(PlayerManager.LocalPlayerScript.OrNull()?.DynamicItemStorage.OrNull()?.GetActiveHandSlot()?.ItemObject, CommonTraits.Instance.Cable)) { lastMouseWordlPositionInt = mousePosition; var metaTileMap = MatrixManager.AtPoint(mousePosition, false).MetaTileMap; var topTile = metaTileMap.GetTile(metaTileMap.WorldToCell(mousePosition), true); if (topTile && (topTile.LayerType == LayerType.Base || topTile.LayerType == LayerType.Underfloor)) { // move cable placement visualisation to rounded mouse position and enable it var RegisterTile = PlayerManager.LocalPlayer.RegisterTile(); if (RegisterTile.Matrix.MatrixMove == null) { cablePlacementVisualisation.transform.position = mousePosition - (new Vector3(0.5f, 0.5f, 0)); cablePlacementVisualisation.SetActive(true); } else { var InQuaternion = RegisterTile.Matrix.MatrixMove .FacingOffsetFromInitial.Quaternion; cablePlacementVisualisation.transform.position = mousePosition - (InQuaternion * (new Vector3(0.5f, 0.5f, 0))); cablePlacementVisualisation.SetActive(true); } } // disable visualisation if active else { DisableVisualisation(); } } } else { DisableVisualisation(); } }
private Renderer IsHit(Transform _transform) { TilemapRenderer tilemapRenderer = _transform.GetComponent <TilemapRenderer>(); if (tilemapRenderer) { return(tilemapRenderer); } return(MouseUtils.IsPixelHit(_transform)); }
public static void DrawScreenRectBorder(Rect rect, float thickness, Color color) { // Top MouseUtils.DrawScreenRect(new Rect(rect.xMin, rect.yMin, rect.width, thickness), color); // Left MouseUtils.DrawScreenRect(new Rect(rect.xMin, rect.yMin, thickness, rect.height), color); // Right MouseUtils.DrawScreenRect(new Rect(rect.xMax - thickness, rect.yMin, thickness, rect.height), color); // Bottom MouseUtils.DrawScreenRect(new Rect(rect.xMin, rect.yMax - thickness, rect.width, thickness), color); }