Exemplo n.º 1
0
    void FixedUpdate()
    {
        ball.localPosition += new Vector3(velocityX, velocityY, 0);
        Debug.Log(ball.localPosition);
        Debug.Log(ball.localPosition + (Vector3.up * ballRadius));
        if (velocityY > 0)
        {
            if (!area.rect.Contains(ball.localPosition + new Vector3(0, ballRadius, 0)))
            {
                velocityY = -velocityY;
            }
        }
        else
        {
            if (!area.rect.Contains(ball.localPosition + new Vector3(0, -ballRadius, 0)))
            {
                velocityY = -velocityY;
            }
        }

        Rect ball2Rect = new Rect(ball.localPosition.x - ballRadius, ball.localPosition.y - ballRadius, ballRadius * 2, ballRadius * 2);
        Rect paddle1Rect = new Rect(paddle1.localPosition.x - 5, paddle1.localPosition.y - 25, 10, 50);
        Rect paddle2Rect = new Rect(paddle2.localPosition.x - 5, paddle2.localPosition.y - 25, 10, 50);
        if (velocityX > 0 && ball2Rect.Overlaps(paddle2Rect))
        {
            velocityX = -velocityX;
        }
        else if (velocityX < 0 && ball2Rect.Overlaps(paddle1Rect))
        {
            velocityX = -velocityX;
        }
    }
Exemplo n.º 2
0
 static void TestOverlop()
 {
     var rect = new Rect(0, 0, 100, 100);
     Assert(true, rect.Overlaps(new Rect(-1, -1, 101, 101)));
     Assert(true, rect.Overlaps(new Rect(1, 1, 50, 50)));
     Assert(true, rect.Overlaps(new Rect(50, 50, 200, 200)));
     Assert(false, rect.Overlaps(new Rect(150, 150, 200, 200)));
 }
Exemplo n.º 3
0
    static int QPYX_Overlaps_YXQP(IntPtr L_YXQP)
    {
        try
        {
            int QPYX_count_YXQP = LuaDLL.lua_gettop(L_YXQP);
            if (QPYX_count_YXQP == 2)
            {
                UnityEngine.Rect QPYX_obj_YXQP  = (UnityEngine.Rect)ToLua.CheckObject(L_YXQP, 1, typeof(UnityEngine.Rect));
                UnityEngine.Rect QPYX_arg0_YXQP = StackTraits <UnityEngine.Rect> .Check(L_YXQP, 2);

                bool QPYX_o_YXQP = QPYX_obj_YXQP.Overlaps(QPYX_arg0_YXQP);
                LuaDLL.lua_pushboolean(L_YXQP, QPYX_o_YXQP);
                ToLua.SetBack(L_YXQP, 1, QPYX_obj_YXQP);
                return(1);
            }
            else if (QPYX_count_YXQP == 3)
            {
                UnityEngine.Rect QPYX_obj_YXQP  = (UnityEngine.Rect)ToLua.CheckObject(L_YXQP, 1, typeof(UnityEngine.Rect));
                UnityEngine.Rect QPYX_arg0_YXQP = StackTraits <UnityEngine.Rect> .Check(L_YXQP, 2);

                bool QPYX_arg1_YXQP = LuaDLL.luaL_checkboolean(L_YXQP, 3);
                bool QPYX_o_YXQP    = QPYX_obj_YXQP.Overlaps(QPYX_arg0_YXQP, QPYX_arg1_YXQP);
                LuaDLL.lua_pushboolean(L_YXQP, QPYX_o_YXQP);
                ToLua.SetBack(L_YXQP, 1, QPYX_obj_YXQP);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L_YXQP, "invalid arguments to method: UnityEngine.Rect.Overlaps"));
            }
        }
        catch (Exception e_YXQP)                {
            return(LuaDLL.toluaL_exception(L_YXQP, e_YXQP));
        }
    }
Exemplo n.º 4
0
    static int Overlaps(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Rect), typeof(UnityEngine.Rect)))
            {
                UnityEngine.Rect obj  = (UnityEngine.Rect)ToLua.ToObject(L, 1);
                UnityEngine.Rect arg0 = (UnityEngine.Rect)ToLua.ToObject(L, 2);
                bool             o    = obj.Overlaps(arg0);
                LuaDLL.lua_pushboolean(L, o);
                ToLua.SetBack(L, 1, obj);
                return(1);
            }
            else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Rect), typeof(UnityEngine.Rect), typeof(bool)))
            {
                UnityEngine.Rect obj  = (UnityEngine.Rect)ToLua.ToObject(L, 1);
                UnityEngine.Rect arg0 = (UnityEngine.Rect)ToLua.ToObject(L, 2);
                bool             arg1 = LuaDLL.lua_toboolean(L, 3);
                bool             o    = obj.Overlaps(arg0, arg1);
                LuaDLL.lua_pushboolean(L, o);
                ToLua.SetBack(L, 1, obj);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Rect.Overlaps"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Exemplo n.º 5
0
 static public int Overlaps(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(UnityEngine.Rect)))
         {
             UnityEngine.Rect self = (UnityEngine.Rect)checkSelf(l);
             UnityEngine.Rect a1;
             checkType(l, 2, out a1);
             System.Boolean ret = self.Overlaps(a1);
             pushValue(l, ret);
             return(1);
         }
         else if (matchType(l, 2, typeof(UnityEngine.Rect), typeof(bool)))
         {
             UnityEngine.Rect self = (UnityEngine.Rect)checkSelf(l);
             UnityEngine.Rect a1;
             checkType(l, 2, out a1);
             System.Boolean a2;
             checkType(l, 3, out a2);
             System.Boolean ret = self.Overlaps(a1, a2);
             pushValue(l, ret);
             return(1);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Exemplo n.º 6
0
 public static bool Intersects(Rect r1, Rect r2)
 {
     if (!r1.Overlaps(r2) && !r2.Overlaps(r1))
     {
         return false;
     }
     return true;
 }
Exemplo n.º 7
0
        public static bool Overlaps(Rect screenRect, Renderer renderer)
        {
            if (!renderer)
                return false;

            Rect boundsRect = BoundsToScreenRect(renderer.bounds);
            return screenRect.Overlaps(boundsRect);
        }
Exemplo n.º 8
0
	/// <summary>
	/// Gets whether any part of this object is touching the given region of world space.
	/// </summary>
	public bool IsInRegion(Rect region)
	{
		Bounds myBounds3D = MyCollider.bounds;
		Rect myBounds = new Rect(myBounds3D.min.x, myBounds3D.min.y,
								 myBounds3D.size.x, myBounds3D.size.y);

		return region.Overlaps(myBounds, true);
	}
Exemplo n.º 9
0
 public static bool Intersection(Rect r1, Rect r2, out Rect intersection)
 {
     if (!r1.Overlaps(r2) && !r2.Overlaps(r1))
     {
         intersection = new Rect(0f, 0f, 0f, 0f);
         return false;
     }
     float x = Mathf.Max(r1.xMin, r2.xMin);
     float y = Mathf.Max(r1.yMin, r2.yMin);
     float num3 = Mathf.Min(r1.xMax, r2.xMax);
     float num4 = Mathf.Min(r1.yMax, r2.yMax);
     intersection = new Rect(x, y, num3 - x, num4 - y);
     return true;
 }
    void Update()
    {
        Rect PlayerRect = new Rect(Player.transform.position.x - Player.sprite.bounds.extents.x, Player.transform.position.y - Player.sprite.bounds.extents.y, Player.sprite.bounds.extents.x * 2, Player.sprite.bounds.extents.y * 2),
             BuildingRect = new Rect(_buildingBoxCollider.transform.position.x - _buildingBoxCollider.bounds.extents.x, _buildingBoxCollider.transform.position.y - _buildingBoxCollider.bounds.extents.y, _buildingBoxCollider.bounds.extents.x * 2, _buildingBoxCollider.bounds.extents.y * 2);

        if (PlayerRect.Overlaps(BuildingRect))
        {
            if (_buildingRenderer.color.a > 0.1)
                _buildingRenderer.color = new Color(_buildingRenderer.color.r, _buildingRenderer.color.g, _buildingRenderer.color.b, _buildingRenderer.color.a - Time.deltaTime);
        }
        else
        {
            if(_buildingRenderer.color.a < 1)
                _buildingRenderer.color = new Color(_buildingRenderer.color.r, _buildingRenderer.color.g, _buildingRenderer.color.b, _buildingRenderer.color.a + Time.deltaTime);
        }
    }
Exemplo n.º 11
0
        /// <summary>
        /// Find the intersection of two rectangles, returns the amount of overlap as a Rectangle.
        /// </summary>
        /// <param name="one">One.</param>
        /// <param name="two">Two.</param>
        public static Rect Intersect(Rect one, Rect two)
        {
            if (one.Overlaps(two))
            {
               	float left, right, top, bottom;

               	if (one.xMin > two.xMin)
               	{
               		left = one.xMin;
               	} else {
               		left = two.xMin;
               	}

               	if (one.xMax < two.xMax)
               	{
               		right = one.xMax;
               	} else{
               		right = two.xMax;
               	}

               	if (one.yMax < two.yMax)
               	{
               		top = one.yMax;
               	} else {
               		top = two.yMax;
               	}

               	if (one.yMin > two.yMin)
               	{
               		bottom = one.yMin;
               	} else {
               		bottom = two.yMin;
               	}

                return new Rect(left, top, right - left, top - bottom);
            } else {
                return new Rect(0, 0, 0, 0);
            }
        }
Exemplo n.º 12
0
 // Update is called once per frame
 void Update()
 {
     if (playerTime.playTime > 0 && !lost)
     {
         for (int i = arrows.Count - 1; i >= 0; i--)
         {
             GameObject obj = arrows[i];
             obj.transform.Translate(-speed, 0, 0);
             Rect rectObj, rectZone;
             rectObj = new Rect(obj.transform.position.x - obj.GetComponent<RectTransform>().rect.width,
                 obj.transform.position.y - obj.GetComponent<RectTransform>().rect.height,
                 obj.GetComponent<RectTransform>().rect.width, obj.GetComponent<RectTransform>().rect.height);
             rectZone = new Rect(pointZone.transform.position.x - pointZone.GetComponent<RectTransform>().rect.width,
                pointZone.transform.position.y - pointZone.GetComponent<RectTransform>().rect.height,
                pointZone.GetComponent<RectTransform>().rect.width, pointZone.GetComponent<RectTransform>().rect.height);
             bool hit = false;
             if (rectObj.Overlaps(rectZone))
             {
                 Debug.Log("Obj " + rectObj + rectObj.size.x * rectObj.size.y);
                 Debug.Log("Zone " + rectZone + rectZone.size.x * rectZone.size.y);
                 Rect inter = new Rect(rectObj.xMin, rectObj.yMin, Mathf.Abs(rectObj.xMin - rectZone.xMax),
                     Mathf.Abs(rectObj.yMin - rectZone.yMax));
                 Debug.Log("inter " + inter + inter.size.x * inter.size.y);
                 int image = 0;
                 for (int j = 0; j < images.Length; j++)
                 {
                     if (obj.GetComponent<Image>().sprite == images[j])
                     {
                         image = j;
                     }
                 }
                 switch (image)
                 {
                     case 0:
                         if (Input.GetKeyDown("up"))
                         {
                             Debug.Log("Acertado");
                             hit = true;
                             Debug.Log("Obj " + rectObj + rectObj.size.x * rectObj.size.y);
                             Debug.Log("Zone " + rectZone + rectZone.size.x * rectZone.size.y);
                             inter = new Rect(rectObj.xMin, rectObj.yMin, Mathf.Abs(rectObj.xMin - rectZone.xMax),
                                 Mathf.Abs(rectObj.yMin - rectZone.yMax));
                             Debug.Log("inter " + inter + inter.size.x * inter.size.y);
                         }
                         break;
                     case 1:
                         if (Input.GetKeyDown("right"))
                         {
                             Debug.Log("Acertado");
                             hit = true;
                             Debug.Log("Obj " + rectObj + rectObj.size.x * rectObj.size.y);
                             Debug.Log("Zone " + rectZone + rectZone.size.x * rectZone.size.y);
                             inter = new Rect(rectObj.xMin, rectObj.yMin, Mathf.Abs(rectObj.xMin - rectZone.xMax),
                                 Mathf.Abs(rectObj.yMin - rectZone.yMax));
                             Debug.Log("inter " + inter + inter.size.x * inter.size.y);
                         }
                         break;
                     case 2:
                         if (Input.GetKeyDown("left"))
                         {
                             Debug.Log("Acertado");
                             hit = true;
                             Debug.Log("Obj " + rectObj + rectObj.size.x * rectObj.size.y);
                             Debug.Log("Zone " + rectZone + rectZone.size.x * rectZone.size.y);
                             inter = new Rect(rectObj.xMin, rectObj.yMin, Mathf.Abs(rectObj.xMin - rectZone.xMax),
                                 Mathf.Abs(rectObj.yMin - rectZone.yMax));
                             Debug.Log("inter " + inter + inter.size.x * inter.size.y);
                         }
                         break;
                     case 3:
                         if (Input.GetKeyDown("down"))
                         {
                             Debug.Log("Acertado");
                             hit = true;
                             Debug.Log("Obj " + rectObj + rectObj.size.x * rectObj.size.y);
                             Debug.Log("Zone " + rectZone + rectZone.size.x * rectZone.size.y);
                             inter = new Rect(rectObj.xMin, rectObj.yMin, Mathf.Abs(rectObj.xMin - rectZone.xMax),
                                 Mathf.Abs(rectObj.yMin - rectZone.yMax));
                             Debug.Log("inter " + inter + inter.size.x * inter.size.y);
                         }
                         break;
                     default:
                         break;
                 }
             }
             if (obj.transform.position.x <= 0 || hit)
             {
                 arrows.Remove(obj);
                 Destroy(obj);
                 lost = !hit;
             }
             if (lost)
             {
                 defeatBanner.SetActive(true);
             }
         }
         separation -= speed;
         if (separation <= 0)
         {
             separation = separationIni;
             instance = Instantiate(Resources.Load("Arrow", typeof(GameObject))) as GameObject;
             instance.transform.SetParent(this.transform);
             instance.transform.localScale = new Vector3(1, 1, 1);
             instance.transform.localPosition = new Vector3(this.GetComponent<RectTransform>().rect.width / 2 +
                 instance.GetComponent<RectTransform>().rect.width, 0, 0);
             int rand = Random.Range(0, 4);
             instance.GetComponent<Image>().sprite = images[rand];
             arrows.Add(instance);
         }
     }
     else if(playerTime.playTime <= 0 && !lost && !won)
     {
         won = true;
         winBanner.SetActive(true);
     }
 }
Exemplo n.º 13
0
	bool doRoomsOverlapCorridor(Corridor alreadyPlaced, Room toBePlaced)
	{
		bool doesOverlap = false;
		//finds the direction of the corridor and makes the correct rectangle
		switch(alreadyPlaced.direction)
		{
		case Direction.North:
			alreadyPlacedRect = new Rect (alreadyPlaced.startXPos, alreadyPlaced.startYPos, alreadyPlaced.corridorWidth+2, alreadyPlaced.corridorLength);
			break;
		case Direction.East:
			alreadyPlacedRect = new Rect (alreadyPlaced.startXPos, alreadyPlaced.startYPos, alreadyPlaced.corridorLength, alreadyPlaced.corridorWidth+2);
			break;
		case Direction.South:
			alreadyPlacedRect = new Rect (alreadyPlaced.startXPos, alreadyPlaced.EndPositionY, alreadyPlaced.corridorWidth+2, alreadyPlaced.corridorLength);
			break;
		case Direction.West:
			alreadyPlacedRect = new Rect (alreadyPlaced.EndPositionX, alreadyPlaced.startYPos, alreadyPlaced.corridorLength, alreadyPlaced.corridorWidth+2);
			break;
		}

		//makes the room rectangle
		toBePlacedRect = new Rect (toBePlaced.xPos-2, toBePlaced.yPos-2, toBePlaced.roomWidth+3, toBePlaced.roomHeight+3);

		//checks to see if the toBePlaced rectangle overlaps the already placed
		if (alreadyPlacedRect.Overlaps (toBePlacedRect)) 
		{
			doesOverlap = true;
		}
		//if previous did not register then checks vise versa
		else if (toBePlacedRect.Overlaps (alreadyPlacedRect)) 
		{
			doesOverlap = true;
		} 
		else 
		{
			//Lastly if code gets here then it individually checks each tile and checks if it is within the other rect
			for (float i = toBePlacedRect.x; i <= toBePlacedRect.x + toBePlacedRect.width; i++) {
				for (float j = toBePlacedRect.y; j <= toBePlacedRect.y + toBePlacedRect.height; j++) {
					if (alreadyPlacedRect.Contains (new Vector2 (i, j))) {
						doesOverlap = true;
						break;
					}
				}
			}
		}
		return doesOverlap;
	}
Exemplo n.º 14
0
 /// <summary>
 /// Tells whether the bounds of an interactor intersects with a given rectangle.
 /// </summary>
 /// <param name="rectangle">Bounds in GUI coordinates.</param>
 /// <returns>True if the interactor bounds and the rectangle intersect.</returns>
 public bool IntersectsWith(Rect rectangle)
 {
     return Location.isValid &&
         rectangle.Overlaps(Location.rect);
 }
Exemplo n.º 15
0
				// Find all points which appear within a range
				public List<Rect> GetAllQuadsInRectCorners (Rect bbox)
				{
						// Prepare an array of results
						List<Rect> foundQuads = new List<Rect> ();
						// Automatically abort if the range does not collide with this quad
						if (!BoundingBox.Contains (new Vector2 (bbox.xMin, bbox.yMin)) && !BoundingBox.Contains (new Vector2 (bbox.xMin, bbox.yMax)) &&
								!BoundingBox.Contains (new Vector2 (bbox.xMax, bbox.yMin)) && !BoundingBox.Contains (new Vector2 (bbox.xMax, bbox.yMax))
								&& !BoundingBox.Overlaps (bbox))
								return foundQuads;

						// Check objects at this quad level
						if (bbox.Overlaps (BoundingBox)
								|| bbox.Contains (new Vector2 (BoundingBox.xMin, BoundingBox.yMin))
								|| bbox.Contains (new Vector2 (BoundingBox.xMin, BoundingBox.yMax))
								|| bbox.Contains (new Vector2 (BoundingBox.xMax, BoundingBox.yMin))
								|| bbox.Contains (new Vector2 (BoundingBox.xMax, BoundingBox.yMax)) 
								|| bbox.Contains (BoundingBox.center))
								foundQuads.Add (BoundingBox);

						// Terminate here, if there are no children
						if (Children == null)
								return foundQuads;
						// Otherwise, add the points from the children
						foundQuads.AddRange (Children [0].GetAllQuadsInRectCorners (bbox));
						foundQuads.AddRange (Children [1].GetAllQuadsInRectCorners (bbox));
						foundQuads.AddRange (Children [2].GetAllQuadsInRectCorners (bbox));
						foundQuads.AddRange (Children [3].GetAllQuadsInRectCorners (bbox));
			
						return foundQuads;
				}
Exemplo n.º 16
0
				public List<Cell> FindNearestCellsToARect (Rect bbox)
				{
						List<Cell> foundCells = new List<Cell> ();

						// Automatically abort if the range does not collide with this quad
						if (!BoundingBox.Contains (new Vector2 (bbox.xMin, bbox.yMin)) && !BoundingBox.Contains (new Vector2 (bbox.xMin, bbox.yMax)) &&
								!BoundingBox.Contains (new Vector2 (bbox.xMax, bbox.yMin)) && !BoundingBox.Contains (new Vector2 (bbox.xMax, bbox.yMax))
								&& !BoundingBox.Overlaps (bbox))
								return foundCells;
			
						// Check objects at this quad level
						if (bbox.Overlaps (BoundingBox)
								|| bbox.Contains (new Vector2 (BoundingBox.xMin, BoundingBox.yMin))
								|| bbox.Contains (new Vector2 (BoundingBox.xMin, BoundingBox.yMax))
								|| bbox.Contains (new Vector2 (BoundingBox.xMax, BoundingBox.yMin))
								|| bbox.Contains (new Vector2 (BoundingBox.xMax, BoundingBox.yMax)) 
								|| bbox.Contains (BoundingBox.center)) {
								if (Cells.Count > 0) {
										foreach (Cell c in Cells) {
												foundCells.Add (c);
										}
								}
						}

						// Terminate here, if there are no children
						if (Children == null)
								return foundCells;

						// Otherwise, add the points from the children
						foundCells.AddRange (Children [0].FindNearestCellsToARect (bbox));
						foundCells.AddRange (Children [1].FindNearestCellsToARect (bbox));
						foundCells.AddRange (Children [2].FindNearestCellsToARect (bbox));
						foundCells.AddRange (Children [3].FindNearestCellsToARect (bbox));
			
						return foundCells;
				}
Exemplo n.º 17
0
 public static bool Intersects(Rect nodeBound, IQtUserData userData)
 {
     Rect r = new Rect(
         userData.GetCenter().x - userData.GetExtends().x,
         userData.GetCenter().z - userData.GetExtends().z,
         userData.GetExtends().x * 2.0f,
         userData.GetExtends().z * 2.0f);
     return nodeBound.Overlaps(r);
 }
Exemplo n.º 18
0
    public void Attack()
    {
        if (animator.GetInteger("dolphin_int") != 2)
        {
            animator.SetInteger("dolphin_int", 2);
            transform.Translate(0f, -0.5f, 0f);
            transform.Rotate(0f, 0f, 180f);

            AttackCounter = Time.time + AttackTimer;
            splashEvent(new Vector3(gameObject.transform.position.x,gameObject.transform.position.y + 0.2f, gameObject.transform.position.z));

        }

        transform.Rotate(Vector3.forward * (0.5f));

        dolphin.transform.Rotate(0f, 0f, -300.0f * Time.deltaTime);
        transform.Translate(new Vector3(1 * 11f * Time.deltaTime, 0f, 0f));

        //hit test
        pr = getRect(playerHitArea);
        //rg = getRect(objectMesh);

        if (pr.Overlaps(rg))
        {
            if(!playerAttacked)
            {
                DolphinAttackEvent(12f);
                playerAttacked = true;
            }

        }

        if (Time.time > AttackCounter)
        {
            currentState = dolphinStates.escaping;
        }
    }
Exemplo n.º 19
0
    /// <summary>
    /// Gets the projection for a given set of corner points and camera.
    /// </summary>
    /// <param name="boundingCornerPoints">The bounding corner points of the game object (in World space).</param>
    /// <param name="camera">The camera.</param>
    /// <returns>The projection.</returns>
    public static ProjectedRect GetProjectedRect(IEnumerable<Vector3> boundingCornerPoints, Camera camera)
    {
        float xMin = 0, xMax = 0, yMin = 0, yMax = 0, zMin = 0, zMax = 0;

        bool first = true;
        foreach (var point in boundingCornerPoints)
        {
            var projectedPoint = camera.WorldToScreenPoint(point);

            // convert to GUI space
            projectedPoint.y = Screen.height - projectedPoint.y;

            if (first)
            {
                xMin = xMax = projectedPoint.x;
                yMin = yMax = projectedPoint.y;
                zMin = zMax = projectedPoint.z;
            }
            else
            {
                if (projectedPoint.x < xMin)
                {
                    xMin = projectedPoint.x;
                }
                else if (projectedPoint.x > xMax)
                {
                    xMax = projectedPoint.x;
                }

                if (projectedPoint.y < yMin)
                {
                    yMin = projectedPoint.y;
                }
                else if (projectedPoint.y > yMax)
                {
                    yMax = projectedPoint.y;
                }

                if (projectedPoint.z < zMin)
                {
                    zMin = projectedPoint.z;
                }
                else if (projectedPoint.z > zMax)
                {
                    zMax = projectedPoint.z;
                }
            }

            first = false;
        }

        var potentialRect = new Rect(xMin, yMin, xMax - xMin, yMax - yMin);
        var screenRect = new Rect(0, 0, Screen.width, Screen.height);

        // Return invalid rect if projection is outside or covering more than the whole screen
        if (!potentialRect.Overlaps(screenRect) ||
            (potentialRect.width > Screen.width && potentialRect.height > Screen.height))
        {
            return new ProjectedRect { isValid = false };
        }

        // Remaining projection rects are at least partially within the screen bounds.
        // Clip projection rects at screen bounds (so no interactors extend outside
        // the game window).
        xMin = xMin < 0 ? 0 : xMin;
        xMax = xMax > Screen.width ? Screen.width : xMax;
        yMin = yMin < 0 ? 0 : yMin;
        yMax = yMax > Screen.height ? Screen.height : yMax;

        if (camera.nearClipPlane <= zMax && zMax <= camera.farClipPlane)
        {
            // Use mean z value as an approximation
            var zMean = (zMin + zMax) / 2.0f;
            return new ProjectedRect
            {
                isValid = true,
                rect = new Rect(xMin, yMin, xMax - xMin, yMax - yMin),
                relativeZ = camera.farClipPlane - zMean
            };
        }
        else
        {
            return new ProjectedRect { isValid = false };
        }
    }
        private void HandleGraphGUIEvents()
        {
            //mouse drag event handling.
            switch (Event.current.type) {
            // draw line while dragging.
            case EventType.MouseDrag: {
                    switch (modifyMode) {
                    case ModifyMode.NONE: {
                            switch (Event.current.button) {
                            case 0:{// left click
                                    if (Event.current.command) {
                                        scalePoint = new ScalePoint(Event.current.mousePosition, NodeGUI.scaleFactor, 0);
                                        modifyMode = ModifyMode.SCALING;
                                        break;
                                    }

                                    selection = new AssetBundleGraphSelection(Event.current.mousePosition);
                                    modifyMode = ModifyMode.SELECTING;
                                    break;
                                }
                            case 2:{// middle click.
                                    scalePoint = new ScalePoint(Event.current.mousePosition, NodeGUI.scaleFactor, 0);
                                    modifyMode = ModifyMode.SCALING;
                                    break;
                                }
                            }
                            break;
                        }
                    case ModifyMode.SELECTING: {
                            // do nothing.
                            break;
                        }
                    case ModifyMode.SCALING: {
                            var baseDistance = (int)Vector2.Distance(Event.current.mousePosition, new Vector2(scalePoint.x, scalePoint.y));
                            var distance = baseDistance / NodeGUI.SCALE_WIDTH;
                            var direction = (0 < Event.current.mousePosition.y - scalePoint.y);

                            if (!direction) distance = -distance;

                            // var before = NodeGUI.scaleFactor;
                            NodeGUI.scaleFactor = scalePoint.startScale + (distance * NodeGUI.SCALE_RATIO);

                            if (NodeGUI.scaleFactor < NodeGUI.SCALE_MIN) NodeGUI.scaleFactor = NodeGUI.SCALE_MIN;
                            if (NodeGUI.SCALE_MAX < NodeGUI.scaleFactor) NodeGUI.scaleFactor = NodeGUI.SCALE_MAX;
                            break;
                        }
                    }

                    HandleUtility.Repaint();
                    Event.current.Use();
                    break;
                }
            }

            // mouse up event handling.
            // use rawType for detect for detectiong mouse-up which raises outside of window.
            switch (Event.current.rawType) {
            case EventType.MouseUp: {
                    switch (modifyMode) {
                    /*
                                select contained nodes & connections.
                            */
                    case ModifyMode.SELECTING: {
                            var x = 0f;
                            var y = 0f;
                            var width = 0f;
                            var height = 0f;

                            if (Event.current.mousePosition.x < selection.x) {
                                x = Event.current.mousePosition.x;
                                width = selection.x - Event.current.mousePosition.x;
                            }
                            if (selection.x < Event.current.mousePosition.x) {
                                x = selection.x;
                                width = Event.current.mousePosition.x - selection.x;
                            }

                            if (Event.current.mousePosition.y < selection.y) {
                                y = Event.current.mousePosition.y;
                                height = selection.y - Event.current.mousePosition.y;
                            }
                            if (selection.y < Event.current.mousePosition.y) {
                                y = selection.y;
                                height = Event.current.mousePosition.y - selection.y;
                            }

                            var activeObjectIds = new List<string>();

                            var selectedRect = new Rect(x, y, width, height);

                            foreach (var node in nodes) {
                                var nodeRect = new Rect(node.GetRect());
                                nodeRect.x = nodeRect.x * NodeGUI.scaleFactor;
                                nodeRect.y = nodeRect.y * NodeGUI.scaleFactor;
                                nodeRect.width = nodeRect.width * NodeGUI.scaleFactor;
                                nodeRect.height = nodeRect.height * NodeGUI.scaleFactor;
                                // get containd nodes,
                                if (nodeRect.Overlaps(selectedRect)) {
                                    activeObjectIds.Add(node.Id);
                                }
                            }

                            foreach (var connection in connections) {
                                // get contained connection badge.
                                if (connection.GetRect().Overlaps(selectedRect)) {
                                    activeObjectIds.Add(connection.Id);
                                }
                            }

                            if (Event.current.shift) {
                                // add current active object ids to new list.
                                foreach (var alreadySelectedObjectId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                    if (!activeObjectIds.Contains(alreadySelectedObjectId)) activeObjectIds.Add(alreadySelectedObjectId);
                                }
                            } else {
                                // do nothing, means cancel selections if nodes are not contained by selection.
                            }

                            Undo.RecordObject(this, "Select Objects");

                            activeObject = RenewActiveObject(activeObjectIds);
                            UpdateActivationOfObjects(activeObject);

                            selection = new AssetBundleGraphSelection(Vector2.zero);
                            modifyMode = ModifyMode.NONE;

                            HandleUtility.Repaint();
                            Event.current.Use();
                            break;
                        }

                    case ModifyMode.SCALING: {
                            modifyMode = ModifyMode.NONE;
                            break;
                        }
                    }
                    break;
                }
            }
        }
Exemplo n.º 21
0
    int getLimbHit(OmniObject player, Rect r, ref Vector2 pos)
    {
        if (player.skeleton == null)
            return -1;

        Rect b = new Rect();

                for (int i = 0; i < player.skeleton.Length; i++)
                {
                    if (player.skeleton[i].name == "bounds")
                        continue;

                    b.x = player.bounds.x;
                    b.y = player.bounds.y;
                    b.x += player.skeleton[i].bounds.x * player.item.Size;
                    b.y += player.skeleton[i].bounds.y * player.item.Size;
                    b.width = player.skeleton[i].bounds.width * player.item.Size;
                    b.height = player.skeleton[i].bounds.height * player.item.Size;
                    if (r.Overlaps(b))
                    {
                        pos = new Vector2(r.x - b.x, r.y - b.y);
                        return i;
                    }
                }

        return -1;
    }
Exemplo n.º 22
0
    public List<int> GetIndex(Rect rect)
    {
        List<int> toReturn = new List<int>();

        for (int i = 0; i < nodes.Length; i++)
            if (rect.Overlaps(nodes[i].Bounds))
                toReturn.Add(i);

        return toReturn;
    }
Exemplo n.º 23
0
		public void SelectWindowsInRect(Rect rect, System.Func<FlowWindow, bool> predicate = null) {

			//this.selectionRect = rect;

			this.selected.Clear();
			foreach (var window in this.windows) {

				if (window.IsContainer() == false && rect.Overlaps(window.rect, true) == true && (predicate == null || predicate(window) == true)) {

					this.selected.Add(window.id);

				}

			}

		}
 private void FinishLasso()
 {
     if (currentConversation == null) return;
     isLassoing = false;
     lassoRect = new Rect(Mathf.Min(lassoRect.x, lassoRect.x + lassoRect.width),
                          Mathf.Min(lassoRect.y, lassoRect.y + lassoRect.height),
                          Mathf.Abs(lassoRect.width),
                          Mathf.Abs(lassoRect.height));
     currentEntry = null;
     if (!IsShiftDown()) multinodeSelection.nodes.Clear();
     foreach (var entry in currentConversation.dialogueEntries) {
         if (lassoRect.Overlaps(entry.canvasRect)) {
             currentEntry = entry;
             if (!multinodeSelection.nodes.Contains(entry)) multinodeSelection.nodes.Add(entry);
         }
     }
     UpdateEntrySelection();
 }
Exemplo n.º 25
0
        private void HandleLeftClick(Event e) {
            if (e.type == EventType.MouseDown) {
                if (state.mouseOverNode != null) {
                    state.isDraggingNodes = true;
                    if (!state.selectedNodes.Contains(state.mouseOverNode)) {
                        //Start dragging on new node
                        state.selectedNodes.Clear();
                        state.selectedNodes.Add(state.mouseOverNode);
                    }
                } else if (state.mouseOverHandle != null) {
                    state.isDraggingHandle = true;
                    state.selectedHandle = state.mouseOverHandle;
                } else {
                    state.isSelecting = true;
                    state.selectedNodes.Clear();
                    state.startSelection = e.mousePosition;
                }
            } else if (e.type == EventType.MouseDrag) {
                if (state.isDraggingNodes) {
                    //Drag nodes
                    foreach (BaseNode n in state.selectedNodes) {
                        n.Move(e.delta, e.shift);
                    }
                    Repaint();
                }else if (state.isDraggingHandle) {
                    state.selectedHandle.Move(state.mousePos);
                }
            } else if (e.type == EventType.MouseUp) {
                if (state.isSelecting) {

                    //Grab selection
                    state.selectedNodes.Clear();
                    Rect selectionRect = new Rect(state.startSelection, e.mousePosition - state.startSelection);
                    foreach (BaseNode n in nodes) {
                        if (selectionRect.Overlaps(n.rect, true)) {
                            state.selectedNodes.Add(n);
                            //Debug.Log("Intersection with " + n.windowTag);
                        }
                    }
                }

                //Reset
                state.isSelecting = false;
                state.isDraggingNodes = false;
                state.isDraggingHandle = false;
            }
        }
Exemplo n.º 26
0
 public override bool Overlaps(Rect rect)
 {
     return rect.Overlaps(WorldRect);
 }
Exemplo n.º 27
0
		//chamto noUsed function !!
		//chamto need Optimization !!
		public MonoDrop CalcCollision(MonoDrop srcDrop)
		{


			const float BOX_WIDTH = 0.57f;
			const float BOX_HEIGHT = 0.57f;
			if(null == srcDrop) return null;

			Rect srcBox = new Rect();
			Rect dstBox = new Rect();
			srcBox.width = BOX_WIDTH;
			srcBox.height = BOX_HEIGHT;
			srcBox.center = new Vector2(srcDrop.transform.position.x,srcDrop.transform.position.y);
			dstBox = srcBox;
			foreach(MonoDrop dstDrop in m_mapDrop.DtnrId.Values)
			{
				//self exclusion
				if(srcDrop == dstDrop) continue;

				//dstBox.center = new Vector2(dstDrop.transform.position.x,dstDrop.transform.position.y);
				dstBox.center = new Vector2(dstDrop.gotoWorldPosition.x , dstDrop.gotoWorldPosition.y);

				if(true == srcBox.Overlaps(dstBox,true)) //include allowInverse
				{
					return dstDrop;
				}

			}

			return null;
		}
Exemplo n.º 28
0
    public static Vector3 TestCollision(HitBox[] hitBoxes, HurtBox[] hurtBoxes, HitConfirmType hitConfirmType, int mirror)
    {
        foreach (HitBox hitBox in hitBoxes) {
            if (hitBox.hide) continue;
            if (hitBox.collisionType == CollisionType.noCollider) continue;
            if (hitConfirmType == HitConfirmType.Throw && hitBox.collisionType != CollisionType.throwCollider) continue;
            if (hitConfirmType == HitConfirmType.Hit && hitBox.collisionType == CollisionType.throwCollider) continue;

            hitBox.state = 0;
            foreach (HurtBox hurtBox in hurtBoxes) {
                Vector3 hurtBoxPosition = hurtBox.position;
                Vector3 hitBoxPosition = hitBox.position.position;
                float dist = 0;
                bool collisionConfirm = false;

                if (!UFE.config.detect3D_Hits){
                    hurtBoxPosition.z = -1;
                    hitBoxPosition.z = -1;
                }

                if (hurtBox.shape == HitBoxShape.circle){
                    if (hitBox.shape == HitBoxShape.circle){
                        dist = Vector3.Distance(hurtBoxPosition, hitBoxPosition);
                        if (dist <= hurtBox.radius + hitBox.radius) collisionConfirm = true;

                    }else if (hitBox.shape == HitBoxShape.rectangle){
                        float mirrorDiff = mirror > 0 ? hitBox.rect.width : 0f;
                        Rect hitBoxRectanglePosition = new Rect(((hitBox.rect.x + mirrorDiff) * mirror) + hitBoxPosition.x,
                                                                hitBox.rect.y + hitBoxPosition.y,
                                                                hitBox.rect.width, hitBox.rect.height);
                        if (hitBox.followXBounds){
                            hitBoxRectanglePosition.x = hitBox.rendererBounds.x - (hitBox.rect.width/2);
                            hitBoxRectanglePosition.width = (hitBox.rendererBounds.width + hitBox.rect.width) - hitBox.rendererBounds.x;
                        }
                        if (hitBox.followYBounds){
                            hitBoxRectanglePosition.y = hitBox.rendererBounds.y - (hitBox.rect.height/2);
                            hitBoxRectanglePosition.height = (hitBox.rendererBounds.height + hitBox.rect.height) - hitBox.rendererBounds.y;
                        }

                        dist = distancePointToRectangle(hurtBoxPosition, hitBoxRectanglePosition);
                        if (dist <= hurtBox.radius) collisionConfirm = true;
                    }
                }else if (hurtBox.shape == HitBoxShape.rectangle){
                    Rect hurtBoxRectanglePosition;
                    if (hitBox.shape == HitBoxShape.circle){
                        float mirrorDiff = mirror < 0 ? hurtBox.rect.width : 0f;
                        hurtBoxRectanglePosition = new Rect(((hurtBox.rect.x + mirrorDiff) * mirror) + hurtBoxPosition.x,
                                                            hurtBox.rect.y + hurtBoxPosition.y,
                                                            hurtBox.rect.width, hurtBox.rect.height);
                        if (hurtBox.followXBounds){
                            hurtBoxRectanglePosition.x = hurtBox.rendererBounds.x - (hurtBox.rect.width/2);
                            hurtBoxRectanglePosition.width = (hurtBox.rendererBounds.width + hurtBox.rect.width) - hurtBox.rendererBounds.x;
                        }
                        if (hurtBox.followYBounds){
                            hurtBoxRectanglePosition.y = hurtBox.rendererBounds.y - (hurtBox.rect.height/2);
                            hurtBoxRectanglePosition.height = (hurtBox.rendererBounds.height + hurtBox.rect.height) - hurtBox.rendererBounds.y;
                        }

                        dist = distancePointToRectangle(hitBoxPosition, hurtBoxRectanglePosition);
                        if (dist <= hitBox.radius) collisionConfirm = true;

                    }else if (hitBox.shape == HitBoxShape.rectangle){
                        float mirrorDiff = mirror < 0 ? hurtBox.rect.width : 0f;
                        hurtBoxRectanglePosition = new Rect(((hurtBox.rect.x + mirrorDiff) * mirror) + hurtBoxPosition.x,
                                                            hurtBox.rect.y + hurtBoxPosition.y,
                                                            hurtBox.rect.width, hurtBox.rect.height);

                        mirrorDiff = mirror > 0 ? hitBox.rect.width : 0f;
                        Rect hitBoxRectanglePosition = new Rect(((hitBox.rect.x + mirrorDiff) * - mirror) + hitBoxPosition.x,
                                                           hitBox.rect.y + hitBoxPosition.y,
                                                           hitBox.rect.width, hitBox.rect.height);
                        if (hitBox.followXBounds){
                            hitBoxRectanglePosition.x = hitBox.rendererBounds.x - (hitBox.rect.width/2);
                            hitBoxRectanglePosition.width = (hitBox.rendererBounds.width + hitBox.rect.width) - hitBox.rendererBounds.x;
                        }
                        if (hitBox.followYBounds){
                            hitBoxRectanglePosition.y = hitBox.rendererBounds.y - (hitBox.rect.height/2);
                            hitBoxRectanglePosition.height = (hitBox.rendererBounds.height + hitBox.rect.height) - hitBox.rendererBounds.y;
                        }

                        if (hurtBox.followXBounds){
                            hurtBoxRectanglePosition.x = hurtBox.rendererBounds.x - (hurtBox.rect.width/2);
                            hurtBoxRectanglePosition.width = (hurtBox.rendererBounds.width + hurtBox.rect.width) - hurtBox.rendererBounds.x;
                        }
                        if (hurtBox.followYBounds){
                            hurtBoxRectanglePosition.y = hurtBox.rendererBounds.y - (hurtBox.rect.height/2);
                            hurtBoxRectanglePosition.height = (hurtBox.rendererBounds.height + hurtBox.rect.height) - hurtBox.rendererBounds.y;
                        }

                        if (hurtBoxRectanglePosition.Overlaps(hitBoxRectanglePosition)) collisionConfirm = true;
                    }
                }

                if (collisionConfirm) {
                    if (hitConfirmType == HitConfirmType.Hit) {
                        hitBox.state = 1;
                    }
                    return (hurtBoxPosition + hitBoxPosition)/2;
                }
            }
        }

        foreach (HitBox hitBox in hitBoxes) {
            if (hitBox.state == 1) hitBox.state = 0;
        }
        return Vector3.zero;
    }
Exemplo n.º 29
0
        /**
         * Updates dropzone states
         */
        public void UpdateDropzones(UIInventoryGridEntry uiEntry = null)
        {
            // Define the entry rect, including current position
            Rect entryRect = new Rect();

            if(uiEntry == null)
            {
                uiEntry = this.entryBeingDragged;
            }

            if(uiEntry != null)
            {
                entryRect = uiEntry.rectTransform.rect;

                entryRect.x = uiEntry.rectTransform.anchoredPosition.x;
                entryRect.y = uiEntry.rectTransform.anchoredPosition.y;

                // TODO: Why is this necessary? A Y coordinate is inverted somewhere
                entryRect.y -= this.slotSize * (uiEntry.entry.item.inventorySize.y - 1);

                // Clamp rect position to grid
                entryRect.x = (float) Math.Round(entryRect.x / this.slotSize) * this.slotSize;
                entryRect.y = (float) Math.Round(entryRect.y / this.slotSize) * this.slotSize;
            }

            // Look for dropzones
            for(int i = 0; i < this.transform.childCount; i++)
            {
                UIDropzone zone = this.transform.GetChild(i).GetComponent<UIDropzone>();

                if(zone != null)
                {
                    // Define the dropzone rect, including position
                    Rect zoneRect = zone.GetImage().rectTransform.rect;

                    zoneRect.x = zone.GetImage().rectTransform.anchoredPosition.x;
                    zoneRect.y = zone.GetImage().rectTransform.anchoredPosition.y;

                    // Set the dropzone hover state based on rect overlap
                    bool isHovering = entryRect.Overlaps(zoneRect);
                    zone.SetHover(isHovering);
                }
            }
        }
Exemplo n.º 30
0
    static bool Rect_Overlaps__Rect(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 1)
        {
            UnityEngine.Rect arg0    = (UnityEngine.Rect)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            UnityEngine.Rect argThis = (UnityEngine.Rect)vc.csObj;                JSApi.setBooleanS((int)JSApi.SetType.Rval, (System.Boolean)(argThis.Overlaps(arg0)));
            JSMgr.changeJSObj(vc.jsObjID, argThis);
        }

        return(true);
    }
Exemplo n.º 31
0
 /// <summary>
 /// Tells whether the bounds of an interactor intersects with a given rectangle.
 /// </summary>
 /// <param name="rectangle">Bounds in GUI coordinates.</param>
 /// <returns>True if the interactor bounds and the rectangle intersect.</returns>
 public bool IntersectsWith(Rect rectangle)
 {
     return(Location.isValid &&
            rectangle.Overlaps(Location.rect));
 }
Exemplo n.º 32
0
    void CheckIfPlayerHit(Rect b,int i,OmniObject owner,OmniObject victim)
    {
        if (b.Overlaps(victim.bounds))
        {

            Vector2 vel = Vector2.zero;
            if (owner is ControllableObject)
                vel = owner.itemBoundsVel[i].normalized * Mathf.Abs(((ControllableObject)owner).fireVel * 0.01f);
            if (owner is PhysicsObject)
            {
                PhysicsObject p = ((PhysicsObject)owner);
                Vector2 pos = Vector2.zero;
                if (p.isProjectile)
                {
                    vel = p.vel * 0.3f;

                    int limb = getLimbHit(victim, owner.itemBounds[i], ref pos);
                    owner.item.OnHit(owner, victim, vel, pos, limb);
                }
                else
                {
                    if (owner.mount0 >= 0)
                        OmniItems.itemTypes[owner.mount0].OnHit(owner, victim, vel, new Vector2(owner.itemBounds[i].x, owner.itemBounds[i].y), getLimbHit(owner, owner.itemBounds[i], ref pos));
                }
            }

        }
    }
Exemplo n.º 33
0
        public void OnGUI()
        {
            using (new EditorGUILayout.HorizontalScope(GUI.skin.box)) {
                if (GUILayout.Button(reloadButtonTexture, GUILayout.Height(18))) {
                    Setup();
                }

                if (GUILayout.Button("Build (active build target is " + EditorUserBuildSettings.activeBuildTarget + ")", GUILayout.Height(18))) {
                    Run();
                }
            }

            /*
                scroll view.
            */
            // var scaledScrollPos = Node.ScaleEffect(scrollPos);
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
            // scrollPos = scrollPos + (movedScrollPos - scaledScrollPos);
            {

                // draw node window x N.
                {
                    BeginWindows();

                    nodes.ForEach(node => node.DrawNode());

                    EndWindows();
                }

                // draw connection input point marks.
                foreach (var node in nodes) {
                    node.DrawConnectionInputPointMark(currentEventSource, modifyMode == ModifyMode.CONNECT_STARTED);
                }

                // draw connections.
                foreach (var con in connections) {
                    if (connectionThroughputs.ContainsKey(con.connectionId)) {
                        var throughputListDict = connectionThroughputs[con.connectionId];
                        con.DrawConnection(nodes, throughputListDict);
                    } else {
                        con.DrawConnection(nodes, new Dictionary<string, List<ThroughputAsset>>());
                    }
                }

                // draw connection output point marks.
                foreach (var node in nodes) {
                    node.DrawConnectionOutputPointMark(currentEventSource, modifyMode == ModifyMode.CONNECT_STARTED, Event.current);
                }

                /*
                    draw connecting line if modifing connection.
                */
                switch (modifyMode) {
                    case ModifyMode.CONNECT_STARTED: {
                        // from start node to mouse.
                        DrawStraightLineFromCurrentEventSourcePointTo(Event.current.mousePosition, currentEventSource);

                        break;
                    }
                    case ModifyMode.CONNECT_ENDED: {
                        // do nothing
                        break;
                    }
                    case ModifyMode.SELECTION_STARTED: {
                        GUI.DrawTexture(new Rect(selection.x, selection.y, Event.current.mousePosition.x - selection.x, Event.current.mousePosition.y - selection.y), selectionTex);
                        break;
                    }
                }

                /*
                    mouse drag event handling.
                */
                switch (Event.current.type) {

                    // draw line while dragging.
                    case EventType.MouseDrag: {
                        switch (modifyMode) {
                            case ModifyMode.CONNECT_ENDED: {
                                switch (Event.current.button) {
                                    case 0:{// left click
                                        if (Event.current.command) {
                                            scalePoint = new ScalePoint(Event.current.mousePosition, Node.scaleFactor, 0);
                                            modifyMode = ModifyMode.SCALING_STARTED;
                                            break;
                                        }

                                        selection = new AssetBundleGraphSelection(Event.current.mousePosition);
                                        modifyMode = ModifyMode.SELECTION_STARTED;
                                        break;
                                    }
                                    case 2:{// middle click.
                                        scalePoint = new ScalePoint(Event.current.mousePosition, Node.scaleFactor, 0);
                                        modifyMode = ModifyMode.SCALING_STARTED;
                                        break;
                                    }
                                }
                                break;
                            }
                            case ModifyMode.SELECTION_STARTED: {
                                // do nothing.
                                break;
                            }
                            case ModifyMode.SCALING_STARTED: {
                                var baseDistance = (int)Vector2.Distance(Event.current.mousePosition, new Vector2(scalePoint.x, scalePoint.y));
                                var distance = baseDistance / Node.SCALE_WIDTH;
                                var direction = (0 < Event.current.mousePosition.y - scalePoint.y);

                                if (!direction) distance = -distance;

                                // var before = Node.scaleFactor;
                                Node.scaleFactor = scalePoint.startScale + (distance * Node.SCALE_RATIO);

                                if (Node.scaleFactor < Node.SCALE_MIN) Node.scaleFactor = Node.SCALE_MIN;
                                if (Node.SCALE_MAX < Node.scaleFactor) Node.scaleFactor = Node.SCALE_MAX;
                                break;
                            }
                        }

                        HandleUtility.Repaint();
                        Event.current.Use();
                        break;
                    }
                }

                /*
                    mouse up event handling.
                    use rawType for detect for detectiong mouse-up which raises outside of window.
                */
                switch (Event.current.rawType) {
                    case EventType.MouseUp: {
                        switch (modifyMode) {
                            /*
                                select contained nodes & connections.
                            */
                            case ModifyMode.SELECTION_STARTED: {
                                var x = 0f;
                                var y = 0f;
                                var width = 0f;
                                var height = 0f;

                                if (Event.current.mousePosition.x < selection.x) {
                                    x = Event.current.mousePosition.x;
                                    width = selection.x - Event.current.mousePosition.x;
                                }
                                if (selection.x < Event.current.mousePosition.x) {
                                    x = selection.x;
                                    width = Event.current.mousePosition.x - selection.x;
                                }

                                if (Event.current.mousePosition.y < selection.y) {
                                    y = Event.current.mousePosition.y;
                                    height = selection.y - Event.current.mousePosition.y;
                                }
                                if (selection.y < Event.current.mousePosition.y) {
                                    y = selection.y;
                                    height = Event.current.mousePosition.y - selection.y;
                                }

                                var activeObjectIds = new List<string>();

                                var selectedRect = new Rect(x, y, width, height);

                                foreach (var node in nodes) {
                                    var nodeRect = new Rect(node.GetRect());
                                    nodeRect.x = nodeRect.x * Node.scaleFactor;
                                    nodeRect.y = nodeRect.y * Node.scaleFactor;
                                    nodeRect.width = nodeRect.width * Node.scaleFactor;
                                    nodeRect.height = nodeRect.height * Node.scaleFactor;
                                    // get containd nodes,
                                    if (nodeRect.Overlaps(selectedRect)) {
                                        activeObjectIds.Add(node.nodeId);
                                    }
                                }

                                foreach (var connection in connections) {
                                    // get contained connection badge.
                                    if (connection.GetRect().Overlaps(selectedRect)) {
                                        activeObjectIds.Add(connection.connectionId);
                                    }
                                }

                                if (Event.current.shift) {
                                    // add current active object ids to new list.
                                    foreach (var alreadySelectedObjectId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                        if (!activeObjectIds.Contains(alreadySelectedObjectId)) activeObjectIds.Add(alreadySelectedObjectId);
                                    }
                                } else {
                                    // do nothing, means cancel selections if nodes are not contained by selection.
                                }

                                Undo.RecordObject(this, "Select Objects");

                                activeObject = RenewActiveObject(activeObjectIds);
                                UpdateActivationOfObjects(activeObject);

                                selection = new AssetBundleGraphSelection(Vector2.zero);
                                modifyMode = ModifyMode.CONNECT_ENDED;

                                HandleUtility.Repaint();
                                Event.current.Use();
                                break;
                            }

                            case ModifyMode.SCALING_STARTED: {
                                modifyMode = ModifyMode.CONNECT_ENDED;
                                break;
                            }
                        }
                        break;
                    }
                }

                // set rect for scroll.
                if (nodes.Any()) {
                    GUILayoutUtility.GetRect(new GUIContent(string.Empty), GUIStyle.none, GUILayout.Width(spacerRectRightBottom.x), GUILayout.Height(spacerRectRightBottom.y));
                }
            }
            EditorGUILayout.EndScrollView();

            /*
                detect
                    dragging some script into window.
                    right click.
                    connection end mouse up.
                    command(Delete, Copy, and more)
            */
            switch (Event.current.type) {
                // detect dragging script then change interface to "(+)" icon.
                case EventType.DragUpdated: {
                    var refs = DragAndDrop.objectReferences;

                    foreach (var refe in refs) {
                        if (refe.GetType() == typeof(UnityEditor.MonoScript)) {
                            var type = ((MonoScript)refe).GetClass();

                            var inherited = IsAcceptableScriptType(type);

                            if (inherited != null) {
                                // at least one asset is script. change interface.
                                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                                break;
                            }
                        }
                    }
                    break;
                }

                // script drop on editor.
                case EventType.DragPerform: {
                    var pathAndRefs = new Dictionary<string, object>();
                    for (var i = 0; i < DragAndDrop.paths.Length; i++) {
                        var path = DragAndDrop.paths[i];
                        var refe = DragAndDrop.objectReferences[i];
                        pathAndRefs[path] = refe;
                    }
                    var shouldSave = false;
                    foreach (var item in pathAndRefs) {
                        var path = item.Key;
                        var refe = (MonoScript)item.Value;
                        if (refe.GetType() == typeof(UnityEditor.MonoScript)) {
                            var type = refe.GetClass();
                            var inherited = IsAcceptableScriptType(type);

                            if (inherited != null) {
                                var dropPos = Event.current.mousePosition;
                                var scriptName = refe.name;
                                var scriptType = scriptName;// name = type.
                                var scriptPath = path;
                                AddNodeFromCode(scriptName, scriptType, scriptPath, inherited, Guid.NewGuid().ToString(), dropPos.x, dropPos.y);
                                shouldSave = true;
                            }
                        }
                    }

                    if (shouldSave) SaveGraphWithReload();
                    break;
                }

                // show context menu
                case EventType.ContextClick: {
                    var rightClickPos = Event.current.mousePosition;
                    var menu = new GenericMenu();
                    foreach (var menuItemStr in AssetBundleGraphSettings.GUI_Menu_Item_TargetGUINodeDict.Keys) {
                        var targetGUINodeNameStr = AssetBundleGraphSettings.GUI_Menu_Item_TargetGUINodeDict[menuItemStr];
                        menu.AddItem(
                            new GUIContent(menuItemStr),
                            false,
                            () => {
                                AddNodeFromGUI(string.Empty, targetGUINodeNameStr, Guid.NewGuid().ToString(), rightClickPos.x, rightClickPos.y);
                                SaveGraphWithReload();
                                Repaint();
                            }
                        );
                    }
                    menu.ShowAsContext();
                    break;
                }

                /*
                    handling mouse up
                         -> drag released -> release modifyMode.
                */
                case EventType.MouseUp: {
                    modifyMode = ModifyMode.CONNECT_ENDED;
                    HandleUtility.Repaint();

                    if (activeObject.idPosDict.ReadonlyDict().Any()) {
                        Undo.RecordObject(this, "Unselect");

                        foreach (var activeObjectId in activeObject.idPosDict.ReadonlyDict().Keys) {
                            // unselect all.
                            foreach (var node in nodes) {
                                if (activeObjectId == node.nodeId) node.SetInactive();
                            }
                            foreach (var connection in connections) {
                                if (activeObjectId == connection.connectionId) connection.SetInactive();
                            }
                        }

                        activeObject = RenewActiveObject(new List<string>());
                    }

                    break;
                }

                /*
                    scale up or down by command & + or command & -.
                */
                case EventType.KeyDown: {
                    if (Event.current.command) {
                        if (Event.current.shift && Event.current.keyCode == KeyCode.Semicolon) {
                            Node.scaleFactor = Node.scaleFactor + 0.1f;
                            if (Node.scaleFactor < Node.SCALE_MIN) Node.scaleFactor = Node.SCALE_MIN;
                            if (Node.SCALE_MAX < Node.scaleFactor) Node.scaleFactor = Node.SCALE_MAX;
                            Event.current.Use();
                            break;
                        }

                        if (Event.current.keyCode == KeyCode.Minus) {
                            Node.scaleFactor = Node.scaleFactor - 0.1f;
                            if (Node.scaleFactor < Node.SCALE_MIN) Node.scaleFactor = Node.SCALE_MIN;
                            if (Node.SCALE_MAX < Node.scaleFactor) Node.scaleFactor = Node.SCALE_MAX;
                            Event.current.Use();
                            break;
                        }
                    }
                    break;
                }

                case EventType.ValidateCommand: {
                    switch (Event.current.commandName) {
                        // Delete active node or connection.
                        case "Delete": {

                            if (!activeObject.idPosDict.ReadonlyDict().Any()) break;
                            Undo.RecordObject(this, "Delete Selection");

                            foreach (var targetId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                DeleteNode(targetId);
                                DeleteConnectionById(targetId);
                            }

                            SaveGraphWithReload();
                            InitializeGraph();

                            activeObject = RenewActiveObject(new List<string>());
                            UpdateActivationOfObjects(activeObject);

                            Event.current.Use();
                            break;
                        }

                        case "Copy": {
                            if (!activeObject.idPosDict.ReadonlyDict().Any()) {
                                break;
                            }

                            Undo.RecordObject(this, "Copy Selection");

                            var targetNodeIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList();
                            var targetNodeJsonRepresentations = JsonRepresentations(targetNodeIds);
                            copyField = new CopyField(targetNodeJsonRepresentations, CopyType.COPYTYPE_COPY);

                            Event.current.Use();
                            break;
                        }

                        case "Cut": {
                            if (!activeObject.idPosDict.ReadonlyDict().Any()) {
                                break;
                            }

                            Undo.RecordObject(this, "Cut Selection");
                            var targetNodeIds = activeObject.idPosDict.ReadonlyDict().Keys.ToList();
                            var targetNodeJsonRepresentations = JsonRepresentations(targetNodeIds);
                            copyField = new CopyField(targetNodeJsonRepresentations, CopyType.COPYTYPE_CUT);

                            foreach (var targetId in activeObject.idPosDict.ReadonlyDict().Keys) {
                                DeleteNode(targetId);
                                DeleteConnectionById(targetId);
                            }

                            SaveGraphWithReload();
                            InitializeGraph();

                            activeObject = RenewActiveObject(new List<string>());
                            UpdateActivationOfObjects(activeObject);

                            Event.current.Use();
                            break;
                        }

                        case "Paste": {
                            var nodeNames = nodes.Select(node => node.name).ToList();
                            var duplicatingData = new List<Node>();

                            if (copyField.datas.Any()) {
                                var pasteType = copyField.type;
                                foreach (var copyFieldData in copyField.datas) {
                                    var nodeJsonDict = Json.Deserialize(copyFieldData) as Dictionary<string, object>;
                                    var pastingNode = NodeFromJsonDict(nodes.Count, nodeJsonDict);
                                    var pastingNodeName = pastingNode.name;

                                    var nameOverlapping = nodeNames.Where(name => name == pastingNodeName).ToList();

              									switch (pasteType) {
              										case CopyType.COPYTYPE_COPY: {
              											if (2 <= nameOverlapping.Count) continue;
              											break;
              										}
              										case CopyType.COPYTYPE_CUT: {
              											if (1 <= nameOverlapping.Count) continue;
              											break;
              										}
              									}

              									duplicatingData.Add(pastingNode);
                                }
                            }

                            if (!duplicatingData.Any()) break;

                            Undo.RecordObject(this, "Paste");
                            foreach (var newNode in duplicatingData) {
                                DuplicateNode(newNode);
                            }

                            SaveGraphWithReload();
                            InitializeGraph();

                            Event.current.Use();
                            break;
                        }

                        case "SelectAll": {
                            Undo.RecordObject(this, "Select All Objects");

                            var nodeIds = nodes.Select(node => node.nodeId).ToList();
                            activeObject = RenewActiveObject(nodeIds);

                            // select all.
                            foreach (var node in nodes) {
                                node.SetActive();
                            }
                            foreach (var connection in connections) {
                                connection.SetActive();
                            }

                            Event.current.Use();
                            break;
                        }

                        default: {
                            break;
                        }
                    }
                    break;
                }
            }
        }
Exemplo n.º 34
0
        //This is called while within Begin/End windows and ScrollArea from the GraphEditor. This is the main function that calls others
        public void ShowNodesGUI(Event e, Rect drawCanvas, bool fullDrawPass, Vector2 canvasMousePos, float zoomFactor)
        {
            GUI.color = Color.white;
            GUI.backgroundColor = Color.white;

            UpdateNodeIDs(false);

            //first pass: Nodes
            for (var i = 0; i < allNodes.Count; i++){
                if (fullDrawPass || drawCanvas.Overlaps(allNodes[i].nodeRect)){
                    allNodes[i].ShowNodeGUI(canvasMousePos, zoomFactor);
                }
            }

            //second pass: Connections
            for (var i = 0; i < allNodes.Count; i++){
                allNodes[i].DrawNodeConnections(canvasMousePos, zoomFactor);
            }

            if (primeNode != null){
                GUI.Box(new Rect(primeNode.nodeRect.x, primeNode.nodeRect.y - 20, primeNode.nodeRect.width, 20), "<b>START</b>");
            }
        }
Exemplo n.º 35
0
 public static bool WorldRectInView(this Camera camera, Rect worldRect, float depth = 0f)
 {
     return worldRect.Overlaps(camera.GetWorldRect(depth));
 }