Пример #1
0
        public void Vector2ToStringTest()
        {
            string separator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
            CultureInfo enUsCultureInfo = new CultureInfo("en-US");

            Vector2 v1 = new Vector2(2.0f, 3.0f);

            string v1str = v1.ToString();
            string expectedv1 = string.Format(CultureInfo.CurrentCulture
                , "<{1:G}{0} {2:G}>"
                , new object[] { separator, 2, 3 });
            Assert.Equal(expectedv1, v1str);

            string v1strformatted = v1.ToString("c", CultureInfo.CurrentCulture);
            string expectedv1formatted = string.Format(CultureInfo.CurrentCulture
                , "<{1:c}{0} {2:c}>"
                , new object[] { separator, 2, 3 });
            Assert.Equal(expectedv1formatted, v1strformatted);

            string v2strformatted = v1.ToString("c", enUsCultureInfo);
            string expectedv2formatted = string.Format(enUsCultureInfo
                , "<{1:c}{0} {2:c}>"
                , new object[] { enUsCultureInfo.NumberFormat.NumberGroupSeparator, 2, 3 });
            Assert.Equal(expectedv2formatted, v2strformatted);

            string v3strformatted = v1.ToString("c");
            string expectedv3formatted = string.Format(CultureInfo.CurrentCulture
                , "<{1:c}{0} {2:c}>"
                , new object[] { separator, 2, 3 });
            Assert.Equal(expectedv3formatted, v3strformatted);
        }
 public void TakeDamage(int damage, Vector2 knockBack)
 {
     Debug.Log ("taking " + damage + " damage, knockback = " + knockBack.ToString ());
     currentHealth -= damage;
     CheckHealth ();
     //transform.position += (Vector3)knockBack;
 }
Пример #3
0
        internal ControllerState Update(GameTime time)
        {
            lastState = currentState;
            currentState = GamePad.GetState(PlayerIndex.One);
            if (currentState.IsConnected == false) { _disconnected = true; }
            else if (currentState.IsConnected == true) { _disconnected = false; }

            // Allows the game to exit
            if (currentState.Buttons.Back == ButtonState.Pressed)
                return ControllerState.Exit;
            if (currentState.Buttons.Start == ButtonState.Pressed && lastState.Buttons.Start == ButtonState.Released)
                _paused = (_paused) ? false : true;

            if (!_paused)
            {
                Vector2 moveUnit = new Vector2(currentState.ThumbSticks.Left.X,
                    currentState.ThumbSticks.Left.Y);
                if (moveUnit.Length() > 0.1f)
                {
                    Console.Out.WriteLine(moveUnit.ToString());
                    unit.MoveUnit(moveUnit);
                }

                unit.MoveAimer(new Vector2(currentState.ThumbSticks.Right.X,
                    currentState.ThumbSticks.Right.Y));
            }

            if (currentState.Buttons.RightShoulder == ButtonState.Pressed)
            {
                unit.Fire();
            }

            return ControllerState.Normal;
        }
Пример #4
0
 public void Draw(SpriteBatch spriteBatch, Vector2 position, float rotation, Vector2 scale, SpriteEffects spriteEffects = SpriteEffects.None)
 {
     if (texture != null && frameSequence != null)
     {
             spriteBatch.Draw(texture, position, FrameSequence.CurrentFrameRect, colorOverlay, rotation,
                 FrameSequence.CurrentFrameOrigin, scale, spriteEffects, renderDepth);
     }
     else
     {
         if (texture == null)
         {
             gxtLog.WriteLineV(gxtVerbosityLevel.WARNING, "Drawable Sprite Sheet Does Not Have A Texture (Position: {0})", position.ToString());
             if (gxtDebugDrawer.SingletonIsInitialized)
             {
                 // check if debug drawer has a spritefont??
                 gxtDebugDrawer.Singleton.AddString("NO SPRITE SHEET TEXTURE", position, Color.Magenta, 0.0f);
             }
         }
         if (frameSequence == null)
         {
             gxtLog.WriteLineV(gxtVerbosityLevel.WARNING, "Drawable Sprite Sheet Does Not Have A Frame Sequence (Position: {0}, Texture: {1})", position.ToString(), texture.Name);
             {
                 if (gxtDebugDrawer.SingletonIsInitialized)
                 {
                     gxtDebugDrawer.Singleton.AddString("NO SPRITE SHEET FRAME SEQUENCE", position, Color.Magenta, 0.0f);
                 }
             }
         }
     }
 }
Пример #5
0
    // Update is called once per frame
    void Update()
    {
        gleft = gazeModel.posGazeLeft;
        gright = gazeModel.posGazeRight;
        Debug.Log (gright.ToString());

        xcord = gright [0];
        ycord = gright [1];
    }
Пример #6
0
 // Use this for initialization
 void Start()
 {
     originalPos = transform.position;
     if (Speed.x != 0)
         horizontal = true;
     if (Speed.y != 0)
         vertical = true;
     Debug.Log(originalPos.ToString());
 }
	public Path get(Vector2 position)
	{
		int keyIndex = findKey (position);
		if (keyIndex != -1)
		{
			return paths[keyIndex];
		}
		throw new KeyNotFoundException ("ShortestPaths instance did not contain index: " + position.ToString ());
	}
Пример #8
0
	void Awake()
	{
		Angle = transform.rotation.eulerAngles.z / 180f * Mathf.PI;
		direction = new Vector2( Mathf.Cos( Angle ) 
			,  Mathf.Sin( Angle )  );

		Debug.Log("wind init " + Angle.ToString() + " " + direction.ToString());
		changeWind = ChangeWind();
		StartCoroutine(changeWind);
	}
Пример #9
0
    public void DragCamera(Vector2 drag)
    {
        //
        text.text = drag.ToString() + "\ndpi: " + Screen.dpi + "\nspeed:" + dragSpeedWithZoom + "\nspeed zoom:" + zoomSpeed;
        //

        cameraToUse.transform.position =
            new Vector3(Mathf.Clamp(cameraToUse.transform.position.x - (drag.x * dragSpeedWithZoom), dragMinX, dragMaxX),
                        cameraToUse.transform.position.y,
                        Mathf.Clamp(cameraToUse.transform.position.z - (drag.y * dragSpeedWithZoom), dragMinY, dragMaxY));
    }
Пример #10
0
 public PlayArea(GameObject top, GameObject bottom, GameObject left, GameObject right)
 {
     TopBar = new Vector2(top.GetComponent<Renderer>().bounds.min.x, (top.GetComponent<Renderer>().bounds.min.y));
     Debug.Log("New Top: " + TopBar.ToString());
     BottomBar = new Vector2(bottom.GetComponent<Renderer>().bounds.min.x, (bottom.GetComponent<Renderer>().bounds.min.y));
     Debug.Log("New Bottom: " + BottomBar.ToString());
     LeftBar = new Vector2(left.GetComponent<Renderer>().bounds.min.x, left.GetComponent<Renderer>().bounds.max.y);
     Debug.Log("New Left: " + LeftBar.ToString());
     RightBar = new Vector2(right.GetComponent<Renderer>().bounds.min.x, right.GetComponent<Renderer>().bounds.max.y);
     Debug.Log("New Right: " + RightBar.ToString());
 }
Пример #11
0
 public Tile getTile(Vector2 coordinate)
 {
     Tile tile;
     try{
         tile = tiles[coordinate.ToString()];
         return tile;
     }
     catch(Exception e){
         e.ToString();
         return null;
     }
 }
 /// <summary>
 /// Constructor for damage 3d
 /// </summary>
 public CombatText(bool isGood, float amount, GameTime gameTime, Vector3 pos, Screens.GameplayScreen screen, Camera cam)
 {
     System.Console.WriteLine("Creating Combat Text");
     camRef = cam;
     CombatColor = isGood ? Color.Blue : Color.Red;
     Text = amount.ToString();
     ExpireTime = gameTime.TotalGameTime.Seconds;
     Position = new Vector2(pos.X, pos.Y);
     Position = camRef.Relative3Dto2D(Position);
     System.Console.WriteLine(Position.ToString());
     Font = screen.ScreenManager.Game.Content.Load<SpriteFont>("Fonts\\monofont");
     Origin = new Vector2(0, 0);
 }
Пример #13
0
 public void resetTiles()
 {
     for(int i=1; i <= lines; i++){
         for(int j=1; j <= columns; j++){
             Vector2 tileCoord = new Vector2(i,j);
             Tile tmp = getTile(tileCoord);
             if(tmp == null){
                 tiles.Add(tileCoord.ToString(),new Tile(tileCoord));
             }
         }
     }
     loaded = true;
 }
Пример #14
0
        public String getRightStick()
        {
            Vector2 RightStick = new Vector2(0, 0);

            GamePadState currentState = GamePad.GetState(PlayerIndex.One);
            if (currentState.ThumbSticks.Right.X != 0 || currentState.ThumbSticks.Right.Y != 0)
            {
                RightStick.X = currentState.ThumbSticks.Right.X;
                RightStick.Y = currentState.ThumbSticks.Right.Y;
            }

            return RightStick.ToString();
        }
Пример #15
0
    public Vector2 GetAcceleration()
    {
        Vector3 acc = new Vector3( RoundUp(Input.acceleration.x ), Input.acceleration.y + 0.4f , RoundUp(Input.acceleration.z + 1f) );
        Vector2 reculca = new Vector2( acc.x , acc.y);

        // on Screen Debug.Log
        if( UIDebugLabel != null ){
            UIDebugLabel.text = acc.ToString()
                + "\n" + reculca.ToString();
        }

        return reculca;
    }
Пример #16
0
    public bool TileCheck(Vector2 desiredPos)
    {
        Debug.Log ("CHECKING " + desiredPos.ToString ());
        if (tiles [(int)desiredPos.x, (int)desiredPos.y].isExit) {
            Debug.Log ("YOUR WINNER");
            Reset();
            return true;
        } else if (tiles [(int)desiredPos.x, (int)desiredPos.y].isWalkable) {

            return true;
        } else {
            return false;
        }
    }
Пример #17
0
 public void Draw(gxtSpriteBatch spriteBatch, Vector2 position, float rotation, Vector2 scale, SpriteEffects spriteEffects, Color colorOverlay, float renderDepth)
 {
     if (spriteFont != null)
         spriteBatch.DrawString(spriteFont, text, position, colorOverlay, rotation, origin, scale, spriteEffects, renderDepth);
     else
     {
         gxtLog.WriteLineV(gxtVerbosityLevel.CRITICAL, "Drawable Text Field Does Not Have A Sprite Font (Position {0}, Text: {1})", position.ToString(), text);
         if (gxtDebugDrawer.SingletonIsInitialized)
         {
             // check if debug drawer has a spritefont??
             // why not just get the debug drawer spritefont and feed it in here?
             gxtDebugDrawer.Singleton.AddString("NO SPRITEFONT", position, Color.Magenta, 0.0f);
         }
     }
 }
Пример #18
0
 public void Draw(gxtSpriteBatch spriteBatch, Vector2 position, float rotation, Vector2 scale, SpriteEffects spriteEffects, Color colorOverlay, float renderDepth)
 {
     if (texture != null)
         spriteBatch.DrawSprite(Texture, position, colorOverlay, rotation, origin, scale, spriteEffects, renderDepth);
     else
     {
         gxtLog.WriteLineV(gxtVerbosityLevel.CRITICAL, "Drawable Sprite Does Not Have A Texture (Position: " + position.ToString() + " )");
         if (gxtDebugDrawer.SingletonIsInitialized)
         {
             //if (!gxtDebugDrawer.Singleton.IsSet(true))
             //    gxtLog.WriteLineV(gxtVerbosityLevel.WARNING, "The Debug Drawer Is Not Set: A \"NO TEXTURE\" string will not be drawn");
             gxtDebugDrawer.Singleton.AddString("NO TEXTURE", position, Color.Magenta, 0.0f);
         }
     }
 }
    // Update is called once per frame
    void Update()
    {
        if (ClusterNetwork.IsMasterOfCluster()) {
            Vector3 mousepos = Input.mousePosition;
            mousepos.x /= Screen.width;
            mousepos.y /= Screen.height;
            ClusterInput.SetAxis("MouseTestX", mousepos.x);
            ClusterInput.SetAxis("MouseTestY", mousepos.y);
            Debug.Log ("SetAxis to" + mousepos.ToString());

        }

        Vector2 pos = new Vector2();
        pos.x = ClusterInput.GetAxis("MouseTestX");
        pos.y = ClusterInput.GetAxis("MouseTestY");
        this.transform.position =new Vector3 (pos.x,pos.y,5.0f);
        Debug.Log ("getAxis" + pos.ToString());
    }
Пример #20
0
        public void Draw(SpriteBatch spriteBatch )
        {
            //global::System.Windows.Forms.MessageBox.Show("Drawing a car at " +
            //"\nX: " +drawPosition.X +
            //"\nY: " + drawPosition.Y);
            Vector2 drawPosition = new Vector2( position.X - physicalBounds.Left, position.Y + physicalBounds.Top);
            spriteBatch.Draw(texture,drawPosition, Color.White);

            if( level.game.showDebugInfo)
            spriteBatch.DrawString(level.debufInfoFont,
                position.ToString() +
                "\n Pos:  " + position.ToString() +
                "\n Draw: " + drawPosition.ToString() +
                "\nydiff: " + (level.playerCar.Position.Y-position.Y).ToString(),
                new Vector2(
                    drawPosition.X + boundingBox.Width + 20,
                    drawPosition.Y ),
                Color.LightCyan
                );
        }
Пример #21
0
	public void Use(Vector3 origin, Vector3 aim)
	{
		if(Network.isServer)
		{
			if(true)
			{
				//Vector2 origin = new Vector2(transform.position.x,transform.position.y);
				
				Vector3 point = new Vector3(aim.x,aim.y,0) - origin;

				GameObject player = NetworkManager.GetPlayer(networkView.owner);
				origin = player.transform.position;
				float charRadius = player.GetComponent<CircleCollider2D>().radius + 0.1f;

				Vector2 direction = new Vector2 (point.x, point.y).normalized;
				origin += new Vector3(direction.x,direction.y,0) * charRadius;

				RaycastHit2D hit = Physics2D.Raycast (origin, direction, 1, Layers);
				GameManager.WriteMessage("Player: " + origin.ToString() + " : " + direction.ToString());
				if(hit != false)
				{
					if(HitEffect != null && HitEffect != "")
					{
						EffectManager.CreateNetworkEffect(transform.position, HitEffect);
					}

					HealthSystem health = hit.collider.GetComponent<HealthSystem>();

					health.TakeDamage(Damage, gameObject);
				}
			}
		}
		else
		{
			networkView.RPC("Use", RPCMode.Server, origin, aim);
			networkView.RPC("UseEffects", RPCMode.All);
		}
	}
Пример #22
0
	public void Move(Vector2 move){
		moveText.text = move.ToString();
	}
Пример #23
0
	// ---------------------------------------------------
	/**
	* Do the search A* in the matrix to search a type or a position
	* @param x_ori	Initial position X
	* @param y_ori	Initial position Y
	* @param x_des	Final position X
	* @param y_des	Final position Y
	*/ 
	public static Vector2 SearchAStar( int x_ori, int y_ori, int x_des, int y_des)		
	{
		 int i;
		 int j;
		 int numCellsGenerated;
		 int directionInitial;
		 int posx;
		 int posy;
		 int sizeMatrix;
		 float minimalValue;
		 int sbusq;
		 
		// Debug.DrawLine(new Vector3((x_ori * m_cellWidth)+m_xIni , 1, (y_ori * m_cellHeight)+m_zIni)
		//               , new Vector3((x_des* m_cellWidth)+m_xIni, 1, (y_des * m_cellHeight)+m_zIni)
		//               , Color.black);
		
		if (DEBUG_PATHFINDING)
		{
			Debug.Log("cPathFinding.as::SearchAStar:: ORIGIN(" + x_ori + "," + y_ori + "); DESTINATION(" + x_des + "," + y_des + "); COLUMNS=" + m_cols + ";ROWS=" + m_rows);
			Debug.Log("CONTENT=" + m_cells);			 
		}
		 
		// SAME POSITION
		if ((x_ori == x_des) && (y_ori == y_des))
		{
			return (new Vector2(x_ori, y_ori));
		}
		
		// CHECK VALID ORIGIN AND GOAL
		if ((GetCellContent(x_ori,y_ori)==CELL_COLLISION)||(GetCellContent(x_des,y_des)==CELL_COLLISION))
		{
			return (new Vector2(-1f, -1f));
		}
		
		 // Init search matrix
		 for (i = 0; i < m_totalCells; i++)			 
		 {
			m_matrixAI[i].m_x = -1;  		// x				
			m_matrixAI[i].m_y = -1;  		// y				
			m_matrixAI[i].m_directionInitial = Global.DIRECTION_NONE; 	// initialDirection				
			m_matrixAI[i].m_hasBeenVisited = -1; 	// checked				
			m_matrixAI[i].m_value = 10000;			// value			
			m_matrixAI[i].m_previousCell = -1;		// previous_cell				
		 }
	
		 // Init initial cell
		 sizeMatrix = 0;			 
		 m_matrixAI[sizeMatrix].m_x = x_ori;  // x			 
		 m_matrixAI[sizeMatrix].m_y  = y_ori;  // y			 
		 m_matrixAI[sizeMatrix].m_hasBeenVisited = 1;	   // checked			 
		 m_matrixAI[sizeMatrix].m_directionInitial = Global.DIRECTION_NONE; // initialDirection			 
		 if ((x_des == -1) && (y_des == -1))			 
		 {
			m_matrixAI[sizeMatrix].m_value = 0; 
		 }
		 else
		 {
			m_matrixAI[sizeMatrix].m_value = GetDistance(x_ori, y_ori, x_des, y_des); 		   
		 }
		 m_matrixAI[sizeMatrix].m_previousCell=-1;
		  
		 // ++ Init search ++
		 // Look through all the list looking for the goal and creating new childs
		 i=0;	 
		 do
		 {
			numCellsGenerated=0;

			// ++ Control the maximum lenght of the serach ++
			if (sizeMatrix > m_totalCells - 5)
			{
				if (DEBUG_PATHFINDING) Debug.Log("cPathFinding.as::SearchAStar:: RETURN 1");
				return (new Vector2(-1f, -1f));
			}
	
			// ++ Buscamos el primer nodo minimo a reproducir ++
			minimalValue = 100000000;
			i = -1;
			for (j = 0; j <= sizeMatrix; j++)
			{
			  if (m_matrixAI[j].m_hasBeenVisited == 1) // checked				  
			  {
				if (m_matrixAI[j].m_value < minimalValue)
				{
					i = j;
					minimalValue = m_matrixAI[j].m_value;
				}
			  }
			}

			if (i == -1)
			{
				if (DEBUG_PATHFINDING) Debug.Log("cPathFinding.as::SearchAStar:: RETURN 2");
				return (new Vector2(-1f, -1f));
			}

			// ++ Select a cell ++
			sbusq = i;

			// Debug.Log("COMPARANDO=("+m_matrixAI[i].m_x+","+m_matrixAI[i].m_y+") RESPECTO DESTINO=("+x_des+","+y_des+")");  				
			if ((m_matrixAI[i].m_x == x_des) && (m_matrixAI[i].m_y == y_des))				
			{
				// CREATE THE LIST OF CELLS BETWEEN DESTINATION-ORIGIN
				if (i == -1)
				{
					return (new Vector2(x_des, y_des));
				}
				else
				{					
					int curIndexBack = i;
					Vector2 sGoalNext = new Vector2(-1f, -1f);
					Vector2 sGoalCurrent = new Vector2(0f, 0f);
					do
					{
						
						sGoalCurrent.x = m_matrixAI[curIndexBack].m_x;
						sGoalCurrent.y = m_matrixAI[curIndexBack].m_y;
						
						if ((sGoalNext.x != -1)&&(sGoalNext.y != -1))
						{
							Debug.DrawLine( new Vector3((sGoalNext.x * m_cellWidth)+m_xIni, 1f, (sGoalNext.y * m_cellWidth)+m_zIni)
						               		, new Vector3((sGoalCurrent.x * m_cellWidth)+m_xIni, 1f, (sGoalCurrent.y * m_cellHeight)+m_zIni)
						               		, Color.black);
						}
						
						sGoalNext.x = sGoalCurrent.x;
						sGoalNext.y = sGoalCurrent.y;
						
						curIndexBack = m_matrixAI[curIndexBack].m_previousCell;								
					} while ((curIndexBack != 0)&&(curIndexBack != -1));			
					if (DEBUG_PATHFINDING) Debug.Log("cPathFinding.as::SearchAStar:: RETURN 3:sGoalNext=" + sGoalNext.ToString());					
					return (sGoalNext);
				}
			}
			   
			// Marca de nodo checked
			m_matrixAI[sbusq].m_hasBeenVisited = 0; // checked				
			
			// Generation of Childs 
			//  Child UP
			posx = (int)(m_matrixAI[i].m_x);				
			posy = (int)(m_matrixAI[i].m_y + 1);				
			if (GetCorrectChild(posx, posy, sizeMatrix) == 1)				
			{ 
			   if (m_matrixAI[sbusq].m_directionInitial == Global.DIRECTION_NONE)
			   {
				   directionInitial = Global.DIRECTION_DOWN;
			   }
			   else
			   {
				   directionInitial = m_matrixAI[sbusq].m_directionInitial;
			   }
					   
			   sizeMatrix++;				   
			   m_matrixAI[sizeMatrix].m_x = posx;
			   m_matrixAI[sizeMatrix].m_y = posy;
			   m_matrixAI[sizeMatrix].m_hasBeenVisited = 1;
			   m_matrixAI[sizeMatrix].m_directionInitial = directionInitial;
			   if ((x_des == Global.DIRECTION_NONE) && (y_des == Global.DIRECTION_NONE))
			   {
					m_matrixAI[sizeMatrix].m_value = 0; 
			   }
			   else
			   {
					m_matrixAI[sizeMatrix].m_value = GetDistance(posx, posy, x_des, y_des); 		   
			   }
			   m_matrixAI[sizeMatrix].m_previousCell = i;				   
			   numCellsGenerated++;
			}

			if (DEBUG_PATHFINDING) Debug.Log("cPathFinding.as::SearchAStar:: ANALIZING(" + m_matrixAI[i].m_x + "," + m_matrixAI[i].m_y + ")");				
			
			// Child DOWN	
			posx = (int)(m_matrixAI[i].m_x);
			posy = (int)(m_matrixAI[i].m_y - 1);
			if (GetCorrectChild(posx, posy, sizeMatrix) == 1)				
			{ 
			   if (m_matrixAI[sbusq].m_directionInitial == Global.DIRECTION_NONE)
			   {
				   directionInitial = Global.DIRECTION_UP;
			   }
			   else
			   {
				   directionInitial = m_matrixAI[sbusq].m_directionInitial;
			   }
				   
			   sizeMatrix++;
			   m_matrixAI[sizeMatrix].m_x = posx;				   
			   m_matrixAI[sizeMatrix].m_y = posy;				   
			   m_matrixAI[sizeMatrix].m_hasBeenVisited = 1;				   
			   m_matrixAI[sizeMatrix].m_directionInitial = directionInitial;				   
			   if ((x_des == Global.DIRECTION_NONE) && (y_des == Global.DIRECTION_NONE))
			   {
					m_matrixAI[sizeMatrix].m_value = 0; 			   
			   }
			   else
			   {
					m_matrixAI[sizeMatrix].m_value = GetDistance(posx, posy, x_des, y_des); 
			   }
			   m_matrixAI[sizeMatrix].m_previousCell=i;
			   numCellsGenerated++;
			}
		
			//  Child LEFT
			posx = (int)(m_matrixAI[i].m_x - 1);				
			posy = (int)(m_matrixAI[i].m_y);				
			if (GetCorrectChild(posx, posy, sizeMatrix) == 1)				
			{ 
			   if (m_matrixAI[sbusq].m_directionInitial == Global.DIRECTION_NONE)
			   {
				   directionInitial = Global.DIRECTION_LEFT;
			   }
			   else
			   {
				   directionInitial = m_matrixAI[sbusq].m_directionInitial;
			   }
		
			   sizeMatrix++;
			   m_matrixAI[sizeMatrix].m_x = posx;				   
			   m_matrixAI[sizeMatrix].m_y = posy;				   
			   m_matrixAI[sizeMatrix].m_hasBeenVisited = 1;				   
			   m_matrixAI[sizeMatrix].m_directionInitial = directionInitial;				   
			   if ((x_des == Global.DIRECTION_NONE) && (y_des == Global.DIRECTION_NONE))
			   {
					m_matrixAI[sizeMatrix].m_value = 0; 			   
			   }
			   else
			   {
					m_matrixAI[sizeMatrix].m_value = GetDistance(posx, posy, x_des, y_des); 		   
			   }
			   m_matrixAI[sizeMatrix].m_previousCell = i;				   
			   numCellsGenerated++;
			}
	
			//  Child RIGHT	
			posx = (int)(m_matrixAI[i].m_x + 1);				
			posy = (int)(m_matrixAI[i].m_y);				
			if (GetCorrectChild(posx, posy, sizeMatrix) == 1)				
			{  
				if (m_matrixAI[sbusq].m_directionInitial == Global.DIRECTION_NONE)
				{
					directionInitial = Global.DIRECTION_RIGHT;
				}
				else
				{
					directionInitial = m_matrixAI[sbusq].m_directionInitial;
				}

				sizeMatrix++;
				m_matrixAI[sizeMatrix].m_x = posx;				  
				m_matrixAI[sizeMatrix].m_y = posy;				  
				m_matrixAI[sizeMatrix].m_hasBeenVisited = 1;				  
				m_matrixAI[sizeMatrix].m_directionInitial = directionInitial;				  
				if ((x_des == Global.DIRECTION_NONE) && (y_des == Global.DIRECTION_NONE))
				{
					m_matrixAI[sizeMatrix].m_value = 0; 			   
				}
				else
				{
					m_matrixAI[sizeMatrix].m_value = GetDistance(posx, posy, x_des, y_des); 		   
				}
				m_matrixAI[sizeMatrix].m_previousCell = i;
				numCellsGenerated++;
			}

	  } while (true);
	
	  if (DEBUG_PATHFINDING) Debug.Log("cPathFinding.as::SearchAStar:: RETURN 4");
	  return (new Vector2(-1f, -1f));
	}
Пример #24
0
 public string ToString(string format)
 {
     return(string.Format("Line2(origin: {0}, direction: {1})", origin.ToString(format), direction.ToString(format)));
 }
Пример #25
0
        /// <summary>Apply the tool to the given tile.</summary>
        /// <param name="tile">The tile to modify.</param>
        /// <param name="tileObj">The object on the tile.</param>
        /// <param name="tileFeature">The feature on the tile.</param>
        /// <param name="player">The current player.</param>
        /// <param name="tool">The tool selected by the player (if any).</param>
        /// <param name="item">The item selected by the player (if any).</param>
        /// <param name="location">The current location.</param>
        public override bool Apply(Vector2 tile, SObject tileObj, TerrainFeature tileFeature, Farmer player, Tool tool, Item item, GameLocation location)
        {
            // clear weeds
            if (this.Config.ClearWeeds && this.IsWeed(tileObj))
            {
                return(this.UseToolOnTile(tool, tile, player, location));
            }

            // collect artifact spots
            if (this.Config.DigArtifactSpots && tileObj?.ParentSheetIndex == HoeAttachment.ArtifactSpotItemID)
            {
                return(this.UseToolOnTile(tool, tile, player, location));
            }

            // harvest ginger
            if (this.Config.HarvestGinger && tileFeature is HoeDirt dirt && dirt.crop?.whichForageCrop.Value == Crop.forageCrop_ginger && dirt.crop.hitWithHoe((int)tile.X, (int)tile.Y, location, dirt))
            {
                dirt.destroyCrop(tile, showAnimation: false, location);
                return(true);
            }

            // till plain dirt
            if (this.Config.TillDirt && tileFeature == null && tileObj == null && this.TryStartCooldown(tile.ToString(), this.TillDirtDelay))
            {
                return(this.UseToolOnTile(tool, tile, player, location));
            }

            return(false);
        }
Пример #26
0
 public override string ToString()
 {
     return(string.Format("P{0}T{1}", Position.ToString(2), TexCoord.ToString(2)));
 }
    void AddSetProceduralVariablesBeforeChangeToKeyValue(ProceduralMaterial inputMaterialBeforeChange, ProceduralPropertyDescription[] materialVariablesListBeforeChange, List <string> keysList, List <string> valuesList)
    { // Specify current material variables as the 'beforeChange' material and what to check against after a change happens
        if (keysList.Count > 0)
        {
            keysList.Clear();
        }
        if (valuesList.Count > 0)
        {
            valuesList.Clear();
        }
        for (int i = 0; i < materialVariablesBeforeChange.Length; i++)//loop through properties and make them the default properties for this object
        {
            ProceduralPropertyDescription materialVariable = materialVariablesBeforeChange[i];
            ProceduralPropertyType        propType         = materialVariablesBeforeChange[i].type;
            if (propType == ProceduralPropertyType.Float /*&& (materialVariable.hasRange )*/)
            {
                float propFloat = inputMaterialBeforeChange.GetProceduralFloat(materialVariable.name);
                keysList.Add(materialVariable.name);
                valuesList.Add(propFloat.ToString());
            }
            if (propType == ProceduralPropertyType.Color3 || propType == ProceduralPropertyType.Color4)
            {
                Color propColor = inputMaterialBeforeChange.GetProceduralColor(materialVariable.name);
                keysList.Add(materialVariable.name);
                valuesList.Add("#" + ColorUtility.ToHtmlStringRGBA(propColor));
            }
            if ((propType == ProceduralPropertyType.Vector2 || propType == ProceduralPropertyType.Vector3 || propType == ProceduralPropertyType.Vector4) /* && (objProperty.hasRange || (saveParametersWithoutRange && !objProperty.hasRange))*/)
            {
                if (propType == ProceduralPropertyType.Vector4)
                {
                    Vector4 propVector4 = inputMaterialBeforeChange.GetProceduralVector(materialVariable.name);
                    keysList.Add(materialVariable.name);
                    valuesList.Add(propVector4.ToString());
                }
                else if (propType == ProceduralPropertyType.Vector3)
                {
                    Vector3 propVector3 = inputMaterialBeforeChange.GetProceduralVector(materialVariable.name);
                    keysList.Add(materialVariable.name);
                    valuesList.Add(propVector3.ToString());
                }
                else if (propType == ProceduralPropertyType.Vector2)
                {
                    Vector2 propVector2 = inputMaterialBeforeChange.GetProceduralVector(materialVariable.name);
                    keysList.Add(materialVariable.name);
                    valuesList.Add(propVector2.ToString());
                }
            }
            else if (propType == ProceduralPropertyType.Enum)
            {
                int propEnum = inputMaterialBeforeChange.GetProceduralEnum(materialVariable.name);
                keysList.Add(materialVariable.name);
                valuesList.Add(propEnum.ToString());
            }
            else if (propType == ProceduralPropertyType.Boolean)
            {
                bool propBoolean = inputMaterialBeforeChange.GetProceduralBoolean(materialVariable.name);
                keysList.Add(materialVariable.name);
                valuesList.Add(propBoolean.ToString());
            }
        }
        // materialVariables.animationTime = animationTime;

        // sets a procedural material based on custom dictionary. I do this because copies of Procedural Materials get changed with their originals. This does not happen if i set values based on parsed values.
        for (int i = 0; i < materialVariablesBeforeChange.Length; i++)
        {
            ProceduralPropertyDescription materialVariables = materialVariablesBeforeChange[i];
            ProceduralPropertyType        propType          = materialVariablesBeforeChange[i].type;
            if (propType == ProceduralPropertyType.Float && (materialVariables.hasRange /*|| (saveParametersWithoutRange && !materialVariables.hasRange) || resettingValuesToDefault)*/))
            {
                for (int j = 0; j < keysList.Count; j++)
                {
                    if (keysList[j] == materialVariables.name)
                    {
                        if (keysList[j] == materialVariables.name)
                        {
                            inputMaterialBeforeChange.SetProceduralFloat(materialVariables.name, float.Parse(valuesList[j]));
                        }
                    }
                }
            }
            else if (propType == ProceduralPropertyType.Color3 || propType == ProceduralPropertyType.Color4)
            {
                for (int j = 0; j < keysList.Count; j++)
                {
                    if (keysList[j] == materialVariables.name)
                    {
                        Color curColor;
                        ColorUtility.TryParseHtmlString(valuesList[j], out curColor);
                        inputMaterialBeforeChange.SetProceduralColor(materialVariables.name, curColor);
                    }
                }
            }
            else if ((propType == ProceduralPropertyType.Vector2 || propType == ProceduralPropertyType.Vector3 || propType == ProceduralPropertyType.Vector4) && (materialVariables.hasRange /*|| (saveParametersWithoutRange && !materialVariables.hasRange) || resettingValuesToDefault)*/))
            {
                if (propType == ProceduralPropertyType.Vector4)
                {
                    for (int j = 0; j < keysList.Count; j++)
                    {
                        if (keysList[j] == materialVariables.name)
                        {
                            Vector4 curVector4 = StringToVector(valuesList[j], 4);
                            inputMaterialBeforeChange.SetProceduralVector(materialVariables.name, curVector4);
                        }
                    }
                }
                else if (propType == ProceduralPropertyType.Vector3)
                {
                    for (int j = 0; j < keysList.Count; j++)
                    {
                        if (keysList[j] == materialVariables.name)
                        {
                            Vector3 curVector3 = StringToVector(valuesList[j], 3);
                            inputMaterialBeforeChange.SetProceduralVector(materialVariables.name, curVector3);
                        }
                    }
                }
                else if (propType == ProceduralPropertyType.Vector2)
                {
                    for (int j = 0; j < keysList.Count; j++)
                    {
                        if (keysList[j] == materialVariables.name)
                        {
                            Vector2 curVector2 = StringToVector(valuesList[j], 2);
                            inputMaterialBeforeChange.SetProceduralVector(materialVariables.name, curVector2);
                        }
                    }
                }
            }
            else if (propType == ProceduralPropertyType.Enum)
            {
                for (int j = 0; j < keysList.Count; j++)
                {
                    if (keysList[j] == materialVariables.name)
                    {
                        int curEnum = int.Parse(valuesList[j]);
                        inputMaterialBeforeChange.SetProceduralEnum(materialVariables.name, curEnum);
                    }
                }
            }
            else if (propType == ProceduralPropertyType.Boolean)
            {
                for (int j = 0; j < keysList.Count; j++)
                {
                    if (keysList[j] == materialVariables.name)
                    {
                        bool curBool = bool.Parse(valuesList[j]);
                        inputMaterialBeforeChange.SetProceduralBoolean(materialVariables.name, curBool);
                    }
                }
            }
        }
    }
Пример #28
0
 private void PrintVector(Vector2 v, Vector2 comp, float tolerance)
 {
     float scalar = 45.0f;
     float dot = Vector2.Dot(v, comp);
     float absDot = gxtMath.AbsDot(v, comp);
     gxtLog.WriteLineV(gxtVerbosityLevel.INFORMATIONAL, "V: {0}\nDot: {1}\nAbsDot: {2}", v.ToString(), dot, absDot);
     Color col = Color.White;
     gxtDebugDrawer.Singleton.AddLine(Vector2.Zero, v * scalar, col, 0.0f, TimeSpan.FromSeconds(120.0));
     gxtDebugDrawer.Singleton.AddString("Dot: " + dot.ToString() + "\nAbsDot: " + absDot.ToString(), v * (scalar + 130.0f), Color.Yellow, 0.0f, TimeSpan.FromSeconds(120.0));
 }
Пример #29
0
 public override string ToString()
 {
     return("Direction: " + Direction.ToString() + ", Horizontal: " + Horizontal.ToString() + ", Vertical: " + Vertical.ToString());
 }
Пример #30
0
 /// <summary>
 /// 将Line的信息转换为字符串
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     return(pos.ToString() + " " + direction.ToString());
 }
Пример #31
0
 // Update is called once per frame
 void Update()
 {
     mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
     print(mousePosition.ToString());
 }
Пример #32
0
 /// <summary>
 /// 将信息转换为字符串
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     return(startPoint.ToString() + " " + endPoint.ToString());
 }
        private void DoCurveEditor(Rect screenRect)
        {
            Widgets.DrawMenuSection(screenRect);
            SimpleCurveDrawer.DrawCurve(screenRect, this.curve, null, null, default(Rect));
            Vector2 mousePosition = Event.current.mousePosition;

            if (Mouse.IsOver(screenRect))
            {
                Rect    rect = new Rect(mousePosition.x + 8f, mousePosition.y + 18f, 100f, 100f);
                Vector2 v    = SimpleCurveDrawer.ScreenToCurveCoords(screenRect, this.curve.View.rect, mousePosition);
                Widgets.Label(rect, v.ToStringTwoDigits());
            }
            Rect rect2 = new Rect(0f, 0f, 50f, 24f)
            {
                x = screenRect.x,
                y = screenRect.y + screenRect.height / 2f - 12f
            };
            string s = Widgets.TextField(rect2, this.curve.View.rect.x.ToString());
            float  num;

            if (float.TryParse(s, out num))
            {
                this.curve.View.rect.x = num;
            }
            rect2.x = screenRect.xMax - rect2.width;
            rect2.y = screenRect.y + screenRect.height / 2f - 12f;
            s       = Widgets.TextField(rect2, this.curve.View.rect.xMax.ToString());
            if (float.TryParse(s, out num))
            {
                this.curve.View.rect.xMax = num;
            }
            rect2.x = screenRect.x + screenRect.width / 2f - rect2.width / 2f;
            rect2.y = screenRect.yMax - rect2.height;
            s       = Widgets.TextField(rect2, this.curve.View.rect.y.ToString());
            if (float.TryParse(s, out num))
            {
                this.curve.View.rect.y = num;
            }
            rect2.x = screenRect.x + screenRect.width / 2f - rect2.width / 2f;
            rect2.y = screenRect.y;
            s       = Widgets.TextField(rect2, this.curve.View.rect.yMax.ToString());
            if (float.TryParse(s, out num))
            {
                this.curve.View.rect.yMax = num;
            }
            if (Mouse.IsOver(screenRect))
            {
                if (Event.current.type == EventType.ScrollWheel)
                {
                    float           num2 = -1f * Event.current.delta.y * 0.025f;
                    float           num3 = this.curve.View.rect.center.x - this.curve.View.rect.x;
                    float           num4 = this.curve.View.rect.center.y - this.curve.View.rect.y;
                    SimpleCurveView view = this.curve.View;
                    view.rect.xMin = view.rect.xMin + num3 * num2;
                    SimpleCurveView view2 = this.curve.View;
                    view2.rect.xMax = view2.rect.xMax - num3 * num2;
                    SimpleCurveView view3 = this.curve.View;
                    view3.rect.yMin = view3.rect.yMin + num4 * num2;
                    SimpleCurveView view4 = this.curve.View;
                    view4.rect.yMax = view4.rect.yMax - num4 * num2;
                    Event.current.Use();
                }
                if (Event.current.type == EventType.MouseDown && (Event.current.button == 0 || Event.current.button == 2))
                {
                    List <int> list = this.PointsNearMouse(screenRect).ToList <int>();
                    if (list.Any <int>())
                    {
                        this.draggingPointIndex = list[0];
                    }
                    else
                    {
                        this.draggingPointIndex = -1;
                    }
                    if (this.draggingPointIndex < 0)
                    {
                        this.draggingButton = Event.current.button;
                    }
                    Event.current.Use();
                }
                if (Event.current.type == EventType.MouseDown && Event.current.button == 1)
                {
                    Vector2 mouseCurveCoords     = SimpleCurveDrawer.ScreenToCurveCoords(screenRect, this.curve.View.rect, Event.current.mousePosition);
                    List <FloatMenuOption> list2 = new List <FloatMenuOption>();
                    list2.Add(new FloatMenuOption("Add point at " + mouseCurveCoords.ToString(), delegate()
                    {
                        this.curve.Add(new CurvePoint(mouseCurveCoords), true);
                    }, MenuOptionPriority.Default, null, null, 0f, null, null));
                    foreach (int i in this.PointsNearMouse(screenRect))
                    {
                        CurvePoint point = this.curve[i];
                        list2.Add(new FloatMenuOption("Remove point at " + point.ToString(), delegate()
                        {
                            this.curve.RemovePointNear(point);
                        }, MenuOptionPriority.Default, null, null, 0f, null, null));
                    }
                    Find.WindowStack.Add(new FloatMenu(list2));
                    Event.current.Use();
                }
            }
            if (this.draggingPointIndex >= 0)
            {
                this.curve[this.draggingPointIndex] = new CurvePoint(SimpleCurveDrawer.ScreenToCurveCoords(screenRect, this.curve.View.rect, Event.current.mousePosition));
                this.curve.SortPoints();
                if (Event.current.type == EventType.MouseUp && Event.current.button == 0)
                {
                    this.draggingPointIndex = -1;
                    Event.current.Use();
                }
            }
            if (this.DraggingView)
            {
                if (Event.current.type == EventType.MouseDrag)
                {
                    Vector2         delta = Event.current.delta;
                    SimpleCurveView view5 = this.curve.View;
                    view5.rect.x = view5.rect.x - delta.x * this.curve.View.rect.width * 0.002f;
                    SimpleCurveView view6 = this.curve.View;
                    view6.rect.y = view6.rect.y + delta.y * this.curve.View.rect.height * 0.002f;
                    Event.current.Use();
                }
                if (Event.current.type == EventType.MouseUp && Event.current.button == this.draggingButton)
                {
                    this.draggingButton = -1;
                }
            }
        }
Пример #34
0
    /// <summary>
    /// Update the state of the pointer.
    /// </summary>
    protected virtual void UpdatePointer()
    {
        ///<summary>>
        /// Checking for controller States
        /// </summary>
        if (GvrController.AppButtonDown)
        {
            DebugMessage("App Button Down");
            AppButtonDown();
        }
        if (GvrController.AppButtonUp)
        {
            DebugMessage("App Button Up");
            AppButtonUp();
        }
        if (GvrController.ClickButtonUp)
        {
            DebugMessage("Button Up");
            OnButtonUp();
        }
        if (GvrController.IsTouching)
        {
        }
        if (GvrController.ClickButtonDown)
        {
            Vector2 tempTouchPos = touchPosition;
            float   touchDistace = Vector2.Distance(Vector2.one * 0.5f, tempTouchPos);

            DebugMessage("Button Down:" + tempTouchPos.ToString() + "  Distance:" + touchDistace);
            if (touchDistace < 0.4f)
            {
                OnButtonDown();
            }
            else
            {
                if (tempTouchPos.x > 0.5f)
                {
                    // right side
                    if (tempTouchPos.y < 0.5f)
                    {
                        // top right
                        ButtonOptionRT();
                    }
                    else
                    {
                        ButtonOptionRB();
                    }
                }
                else
                {
                    // left side
                    if (tempTouchPos.y < 0.5f)
                    {
                        // top left
                        ButtonOpetionLT();
                    }
                    else
                    {
                        ButtonOptionLB();
                    }
                }
            }
        }
        if (GvrController.TouchDown)
        {
            DebugMessage("TouchDown");
            if (detectSwipes)
            {
                startSwipePosition = touchPosition;
                isSwiping          = true;
            }
            OnTouchDown();
        }
        if (GvrController.TouchUp)
        {
            DebugMessage("Touch Up");
            if (isSwiping)
            {
                CheckIfSwipped();
            }
            OnTouchUp();
        }
                #if !UNITY_EDITOR
        if (GvrController.State != GvrConnectionState.Connected)
        {
            foreach (Transform child in controllerPivot.transform)
            {
                child.gameObject.SetActive(false);
            }
        }
        else
        {
            foreach (Transform child in controllerPivot.transform)
            {
                child.gameObject.SetActive(true);
            }
            controllerPivot.transform.rotation = GvrController.Orientation;
        }
                #endif
        if (isSwiping)
        {
            endSwipePosition = touchPosition;
        }
    }
Пример #35
0
        public void Start()
        {
            if (done)
            {
                return;
            }
            done = true;

            //Log.Normal("AdvTexture called on " + staticInstance.model.name);

            if (!int.TryParse(BuiltinIndex, out textureIndex))
            {
                Log.UserError("AdvancedTexture: could not parse BuiltinIndex " + BuiltinIndex);
            }

            if (!bool.TryParse(tileTextureWithScale, out doTileing))
            {
                Log.UserError("AdvancedTexture: could not parse TileTexture " + tileTextureWithScale);
            }

            //                Log.UserError("AdvancedTexture: could not parse TileTexture " + tileTextureWithScale);

            if (doTileing)
            {
                try
                {
                    iTileing = ConfigNode.ParseVector2(forceTiling);
                    Log.Normal("found tiling: " + iTileing.ToString());
                }
                catch
                {
                    Log.UserError("Cannot parse: \"forceTiling\" : " + forceTiling);
                    iTileing = Vector2.zero;
                }


                tileing = staticInstance.mesh.AddComponent <TileTextures>();
                tileing.initialTileing        = iTileing;
                tileing.staticInstance        = staticInstance;
                tileing.textureTransformNames = transforms;
                tileing.Start();
                tileing.enabled = true;
            }


            targetTransforms = transforms.Split(seperators, StringSplitOptions.RemoveEmptyEntries).ToList();


            foreach (MeshRenderer renderer in gameObject.GetComponentsInChildren <MeshRenderer>(true))
            {
                if (!transforms.Equals("Any", StringComparison.CurrentCultureIgnoreCase) && !targetTransforms.Contains(renderer.transform.name))
                {
                    continue;
                }

                // Log.Normal("Processing Transform: " + renderer.transform.name);

                if (newMaterial != "")
                {
                    ReplaceMaterial(renderer, newMaterial);
                    continue;
                }

                if (!string.IsNullOrEmpty(newShader))
                {
                    ReplaceShader(renderer, newShader);
                }

                SetTexture(renderer, _MainTex, "_MainTex");
                SetTexture(renderer, _ParallaxMap, "_ParallaxMap");
                SetTexture(renderer, _Emissive, "_Emissive");
                SetTexture(renderer, _EmissionMap, "_EmissionMap");
                SetTexture(renderer, _MetallicGlossMap, "_MetallicGlossMap");
                SetTexture(renderer, _OcclusionMap, "_OcclusionMap");
                SetTexture(renderer, _SpecGlossMap, "_SpecGlossMap");
                SetTexture(renderer, _BumpMap, "_BumpMap", true);

                //     KKGraphics.ReplaceShader(renderer);
                CheckForExistingMaterial(renderer);
            }
        }
Пример #36
0
    private void PinchZoomObject(Touch touch1, Touch touch2)
    {
        //current distance between finger touches
                curDist = touch1.position - touch2.position;
                Debug.Log ("touch1 = " + touch1.position);
                Debug.Log ("touch2 = " + touch2.position);
                Debug.Log ("curDist = " + curDist.ToString ());

                //difference in previous locations using delta positions
                prevDist = ((touch1.position - touch1.deltaPosition) - (touch2.position - touch2.deltaPosition));

                touchDelta = curDist.magnitude - prevDist.magnitude;

        //				if ((Input.GetTouch (0).position.x - Input.GetTouch (1).position.x) > (Input.GetTouch (0).position.y - Input.GetTouch (1).position.y)) {
        //						vertOrHorzOrientation = -1;
        //				}
        //				if ((Input.GetTouch (0).position.x - Input.GetTouch (1).position.x) < (Input.GetTouch (0).position.y - Input.GetTouch (1).position.y)) {
        //						vertOrHorzOrientation = 1;
        //				}

                if (touchDelta < 0) {
                        float oldScale = _vegasObject.transform.localScale.x;
                        float newScale = oldScale / 1.1f;
                        _vegasObject.transform.localScale = new Vector3 (newScale, newScale, newScale);
                } else {
                        float oldScale = _vegasObject.transform.localScale.x;
                        float newScale = oldScale * 1.1f;
                        _vegasObject.transform.localScale = new Vector3 (newScale, newScale, newScale);
                }
    }
Пример #37
0
        public static void removeEverythingFromTile(Farm location, Vector2 tileLocation)
        {
            if (location.terrainFeatures.ContainsKey(tileLocation))
            {
                Logger.Log("Removing " + location.terrainFeatures[tileLocation].GetType().ToString() + " at " + tileLocation.ToString());
                location.terrainFeatures.Remove(tileLocation);
            }
            if (location.objects.ContainsKey(tileLocation))
            {
                Logger.Log("Removing " + location.objects[tileLocation].GetType().ToString() + " at " + tileLocation.ToString());
                location.objects.Remove(tileLocation);
            }
            List <StardewValley.TerrainFeatures.ResourceClump> clumpsToRemove = new List <StardewValley.TerrainFeatures.ResourceClump>();

            foreach (StardewValley.TerrainFeatures.ResourceClump clump in location.resourceClumps)
            {
                if (clump.occupiesTile((int)tileLocation.X, (int)tileLocation.Y))
                {
                    clumpsToRemove.Add(clump);
                }
            }
            foreach (StardewValley.TerrainFeatures.ResourceClump clump in clumpsToRemove)
            {
                location.resourceClumps.Remove(clump);
            }
        }
Пример #38
0
 public override string ToString()
 {
     return($"{pos.ToString()}");
 }
Пример #39
0
 public string ToString(string format)
 {
     return(string.Format("({0}, {1})", centre.ToString(format), extents.ToString(format)));
 }
        public void Transform()
        {
            UnityEventListenerMock transformedListenerMock = new UnityEventListenerMock();

            subject.Transformed.AddListener(transformedListenerMock.Listen);

            Assert.AreEqual(Vector2.zero, subject.Result);
            Assert.IsFalse(transformedListenerMock.Received);

            Vector2 result         = subject.Transform(5f);
            Vector2 expectedResult = new Vector2(1f, 0.1f);

            Assert.AreEqual(expectedResult.ToString(), result.ToString());
            Assert.AreEqual(expectedResult.ToString(), subject.Result.ToString());
            Assert.IsTrue(transformedListenerMock.Received);

            transformedListenerMock.Reset();

            result         = subject.Transform(5f);
            expectedResult = new Vector2(1f, 0.2f);

            Assert.AreEqual(expectedResult.ToString(), result.ToString());
            Assert.AreEqual(expectedResult.ToString(), subject.Result.ToString());
            Assert.IsTrue(transformedListenerMock.Received);

            transformedListenerMock.Reset();

            result         = subject.Transform(10f);
            expectedResult = new Vector2(1f, 0.4f);

            Assert.AreEqual(expectedResult.ToString(), result.ToString());
            Assert.AreEqual(expectedResult.ToString(), subject.Result.ToString());
            Assert.IsTrue(transformedListenerMock.Received);

            transformedListenerMock.Reset();

            result         = subject.Transform(-10f);
            expectedResult = new Vector2(1f, 0.2f);

            Assert.AreEqual(expectedResult.ToString(), result.ToString());
            Assert.AreEqual(expectedResult.ToString(), subject.Result.ToString());
            Assert.IsTrue(transformedListenerMock.Received);

            transformedListenerMock.Reset();

            result         = subject.Transform(35f);
            expectedResult = new Vector2(1f, 1f);

            Assert.AreEqual(expectedResult.ToString(), result.ToString());
            Assert.AreEqual(expectedResult.ToString(), subject.Result.ToString());
            Assert.IsTrue(transformedListenerMock.Received);

            transformedListenerMock.Reset();

            result         = subject.Transform(-45f);
            expectedResult = new Vector2(1f, 0f);

            Assert.AreEqual(expectedResult.ToString(), result.ToString());
            Assert.AreEqual(expectedResult.ToString(), subject.Result.ToString());
            Assert.IsTrue(transformedListenerMock.Received);
        }
Пример #41
0
 public override void SetCoordinate(Vector2 pos)
 {
     t_label.text = pos.ToString();
 }
Пример #42
0
        public WorldBlock GetBlock(Vector2 _Position)
        {
            if (_Position.x > Size.x || _Position.y > Size.y)
            {
                throw new Exception($"GetBlock координаты вне границ мира Size({Size.ToString()}); Postion({_Position.ToString()})");
            }

            return(Blocks[_Position.x, _Position.y]);
        }
Пример #43
0
 public override string ToString()
 {
     return(Pos.ToString());
 }
Пример #44
0
        /*private Vector3 get_cam_pos(float angleA, float angleB, float zoom, Vector3 target)
         * {
         *  Vector3 camPos = Vector3.UnitY * zoom;
         *
         *  camPos = Vector3.Transform(camPos, Matrix.CreateRotationX(angleB));
         *  camPos = Vector3.Transform(camPos, Matrix.CreateRotationY(angleA));
         *
         *  camPos += target;
         *  return camPos;
         * }*/


        protected override void Draw(GameTime gameTime)
        {
            Texture2D te = new Texture2D(GraphicsDevice,
                                         1, 1);

            te.SetData <Color>(new Color[] { Color.White });

            spriteBatch.Begin();
            Vector2 point = new Vector2(S.ms.X, S.ms.Y);

            Control.FromHandle(Window.Handle).Visible  = true;
            Control.FromHandle(Window.Handle).Location =
                new Point((int)S.Winform.X, (int)S.Winform.Y);

            spriteBatch.Draw(te, new Rectangle(
                                 S.ms.X, S.ms.Y, 30, 30), Color.White);

            Window.Title = point.ToString() +
                           " -- " + S.Xna.ToString() + " -- " + S.Winform.ToString();

            spriteBatch.End();

            dfps        = 1000 / gameTime.ElapsedGameTime.TotalMilliseconds;
            gc.Position = Vector3.Zero;

            GraphicsDevice.Clear(Color.CornflowerBlue);
            S.be.View       = S.View;
            S.be.Projection = S.Proj;
            if (S.kb.IsKeyDown(Keys.C))
            {
                S.be.FogEnabled = true;
                S.be.FogColor   = new Vector3(0.5f, 0.3f, 0.8f);
                S.be.FogStart   = 0;
                S.be.FogEnd     = S.be.FogStart + 140;
            }
            else
            {
                S.be.FogEnabled = false;
            }
            S.be.EnableDefaultLighting();
            S.be.VertexColorEnabled = true;

            RasterizerState rs = new RasterizerState();

            if (S.kb.IsKeyDown(Keys.K))
            {
                rs.CullMode = CullMode.None;
            }
            else
            {
                rs.CullMode = CullMode.CullCounterClockwiseFace;
            }

            if (S.kb.IsKeyDown(Keys.G))
            {
                rs.FillMode = FillMode.WireFrame;
            }
            else
            {
                rs.FillMode = FillMode.Solid;
            }

            IsMouseVisible = true;

            S.gd.RasterizerState = rs;

            spriteBatch.Begin();

            if (Draw2DEvent != null)
            {
                Draw2DEvent();
            }

            spriteBatch.End();

            GraphicsDevice.BlendState        = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            if (Draw3DEvent != null)
            {
                Draw3DEvent();
            }

            BVHAttackAction action =
                S.action as BVHAttackAction;

            if (action != null &&
                action.attackDrcs.ContainsKey(S.player.Frame))
            {
                S.be.World = S.attackDirMatrix;

                S.be.Techniques[0].Passes[0].Apply();

                S.gd.SetVertexBuffer(attackDirCylinder.vBuffer);
                S.gd.Indices = attackDirCylinder.iBuffer;
                S.gd.DrawIndexedPrimitives(PrimitiveType.TriangleList,
                                           0, 0, attackDirCylinder.vCount,
                                           0, attackDirCylinder.iCount / 3);
            }

            if (mouseRay != null)
            {
                S.be.World           = Matrix.Identity;
                S.be.LightingEnabled = false;
                S.be.Techniques[0].Passes[0].Apply();

                S.gd.SetVertexBuffer(null);
                S.gd.Indices = null;
                S.gd.DrawUserPrimitives(PrimitiveType.LineList,
                                        mouseRay, 0, mouseRay.Length / 2);
            }


            S.be.LightingEnabled = false;
            S.be.World           = Matrix.Identity;
            S.be.Techniques[0].Passes[0].Apply();
            // GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList,
            //   c.vertices, 0, c.vertices.Length, c.indices, 0, c.indices.Length / 3);

            //S.terrain.Draw();
            axis.Draw(S.gd, S.View);

            base.Draw(gameTime);
        }
Пример #45
0
 /// <summary>
 /// Returns a <see cref="System.String"/> that represents this instance.
 /// </summary>
 /// <returns>
 /// A <see cref="System.String"/> that represents this instance.
 /// </returns>
 public override string ToString()
 {
     return(string.Format(CultureInfo.CurrentCulture, "Center:{0} Radius:{1}", Center.ToString(), Radius.ToString()));
 }
Пример #46
0
    private void WriteOutInhibition(XmlDocument xml, XmlElement session)
    {
        XmlElement dots = xml.CreateElement("dots");

        XmlElement ldot = xml.CreateElement("Left");

        Vector2 dotPos = new Vector2(Screen.width/4f,Screen.height/2f);

        ldot.SetAttribute("Center", dotPos.ToString());

        dots.AppendChild(ldot);

        XmlElement rdot = xml.CreateElement("Right");

        dotPos = new Vector2(Screen.width*.75f,Screen.height/2f);

        rdot.SetAttribute("Center", dotPos.ToString());

        dots.AppendChild(rdot);
        session.AppendChild(dots);
        XmlElement practice = xml.CreateElement("practice");

        //Loop through all the events and write them out
        foreach(InhibitionEvent eS in gm.Practice){
            if(eS.Completed){
                XmlElement trial = xml.CreateElement("trial");

                    if(eS.DotColor =="yellow")
                        trial.SetAttribute("TargetSide", "same");
                    else
                        trial.SetAttribute("TargetSide", "opposite");

                    trial.SetAttribute("TimedOut", eS.TimedOut.ToString());

                    if(eS.Response!=null){
                        trial.SetAttribute("ResponseTime", eS.Response.ResponseTime.ToString());
                        trial.SetAttribute("TouchPosition", eS.Response.TouchLocation.ToString());
                        trial.SetAttribute("DistanceFromCenter",eS.Response.DistanceFromCenter.ToString());

                        if(eS.Response.DotPressed ==1)
                            trial.SetAttribute("PressedSide","right");
                        else
                            trial.SetAttribute("PressedSide","left");
                    }

                    if(eS.respondedCorrectly())
                        trial.SetAttribute("Correct","1");
                    else
                        trial.SetAttribute("Correct","0");
                practice.AppendChild(trial);
            }
        }

        session.AppendChild(practice);

        //Create the trial cluster
        XmlElement trials = xml.CreateElement("trials");

        //Loop through all the events and write them out
        foreach(InhibitionEvent eS in gm.Events){
            if(eS.Completed){
                XmlElement trial = xml.CreateElement("trial");

                    if(eS.DotColor =="yellow") trial.SetAttribute("TargetSide", "same");
                    else trial.SetAttribute("TargetSide", "opposite");

                    trial.SetAttribute("TimedOut", eS.TimedOut.ToString());

                    if(eS.Response!=null){
                        trial.SetAttribute("ResponseTime", eS.Response.ResponseTime.ToString());
                        trial.SetAttribute("TouchPosition", eS.Response.TouchLocation.ToString());
                        trial.SetAttribute("DistanceFromCenter",eS.Response.DistanceFromCenter.ToString());

                        if(eS.Response.DotPressed ==1) trial.SetAttribute("PressedSide","right");
                        else trial.SetAttribute("PressedSide","left");
                    }

                    if(eS.respondedCorrectly()) trial.SetAttribute("Correct","1");
                    else trial.SetAttribute("Correct","0");

                trials.AppendChild(trial);
            }
        }
        session.AppendChild(trials);
    }
    // Update is called once per frame
    void Update()
    {
        var     posHead = rig.centerEyeAnchor.position;
        Vector3 posR    = OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch);
        Vector3 posL    = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch);
        Vector3 p       = OVRManager.tracker.GetPose().position;

        var        rotHead           = rig.centerEyeAnchor.rotation;
        Quaternion rotR              = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch);
        Quaternion rotL              = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch);
        string     rightpos          = "Position of the RIGHT controller is: ";
        string     leftpos           = "Position of the LEFT controller is: ";
        string     headpos           = "Position of the HEADSET is: ";
        string     rot               = " And rotation is: ";
        string     cl                = "\n";
        string     axisL             = "AXIS LEFT: ";
        string     axisR             = "AXIS RIGHT: ";
        string     accessoryPosition = rightpos + posR.ToString() + rot + rotR.eulerAngles.ToString() + "\n" + leftpos + posL.ToString() + rot + rotL.eulerAngles.ToString() + "\n" + headpos + posHead.ToString() + rot + rotHead.ToString() + "\n";;
        Vector2    inputAxisThumbL   = OVRInput.Get(OVRInput.RawAxis2D.LThumbstick);
        Vector2    inputAxisThumbR   = OVRInput.Get(OVRInput.RawAxis2D.RThumbstick);

        distLabel.text = accessoryPosition + cl + axisL + inputAxisThumbL.ToString() + cl + axisR + inputAxisThumbR.ToString();
    }
Пример #48
0
    public void SwipeMove()
    {
        if (jumping)
        {
            float curtime = GameMaster.instance.LC.levelTime - jumpstart;
            //float x = (GameMaster.instance.LC.levelTime - jumpstart)* GameMaster.instance.LC.level.levelSpeed;
            //float y =-(.5f*x*x)  + jumpHieght;
            //float a = -(jumpHieght * 2) / jumpLength;
            //float d = (.5f * -a * jumpLength) * curtime + .5f * a * curtime * curtime;
            float a = gravity;
            if (endJump)
            {
                a *= 2;
            }
            float d = jumpVel * curtime + .5f * a * curtime * curtime;


            Vector3 temppos = GameMaster.instance.dragon.gameObject.transform.position;
            temppos.y = movePositions[currentPosID].y + d;
            GameMaster.instance.dragon.gameObject.transform.position = temppos;
            if (d <= 0)
            {
                endJump     = false;
                jumping     = false;
                acceptInput = true;
                GameMaster.instance.dragon.gameObject.transform.position = movePositions[currentPosID];
            }
        }

        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            GameMaster.instance.UI.notifactionText.text = Input.touchCount.ToString();

            if (touch.phase == TouchPhase.Began)
            {
                trackedTouch = touch;
                touchStart   = touch.position;
            }
            else
            {
                // continue track
                if (touch.phase == TouchPhase.Ended)
                {
                    Vector2 swipedir = (touch.position - touchStart).normalized;
                    //take start and end get direction
                    GameMaster.instance.UI.notifactionText.text = swipedir.ToString();
                    Swiped(swipedir);
                }
            }
        }
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            //todo add better exit/save/unload//back to menu
            //if level live exit level to menu, else exit application
            if (GameMaster.instance.LC.LevelPlay)
            {
                GameMaster.instance.LC.LevelPlay = false;
                GameMaster.instance.LevelExit();
            }
            else
            {
                Application.Quit();
            }
        }
        if (Input.GetKeyDown("a"))
        {
            if (acceptInput)
            {
                Horizontal(-1);
            }
        }
        if (Input.GetKeyDown("d"))
        {
            if (acceptInput)
            {
                Horizontal(1);
            }
        }
        if (Input.GetKeyDown("space"))
        {
            if (acceptInput)
            {
                Jump();
            }
        }
        if (Input.GetKeyDown("s"))
        {
            if (jumping)
            {
                //forces jump to end
                //endJump = true;
            }
            else
            if (acceptInput)
            {
                Ability();
            }
        }

        //change to que
    }
 /**
  *  This will save the datatype value inside the register, with a string
  *  key to identify and retrieve it. This will override any previous key
  */
 public static void SetVector2 (string key, Vector2 value)
 {
     SetString(key, value.ToString());
 }
Пример #50
0
    public void  Move()
    {
        Vector2 mousepos = new Vector2(Input.mousePosition.x / GameMaster.instance.cam.scaledPixelWidth, Input.mousePosition.y / GameMaster.instance.cam.scaledPixelHeight);

        // Debug.Log(mousepos);
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            print(Input.touchCount);
            //check actions
            //foreach touch
            // if touch is within move bounds move head
            Vector2 temppos = new Vector2(touch.position.x / GameMaster.instance.cam.scaledPixelWidth, touch.position.y / GameMaster.instance.cam.scaledPixelHeight);

            GameMaster.instance.UI.notifactionText.text = temppos.ToString();
            if (inputBounds.Contains(temppos))
            {
                GameMaster.instance.UI.notifactionText.text = "is contained";
                float posy = temppos.y * (1 / topRightInputBound.y);

                //Debug.Log(posy);
                posy = Mathf.Min(posy, 1);
                float newx = (movementBounds.center.x - movementBounds.extents.x) + temppos.x * movementBounds.size.x;
                float newy = (movementBounds.center.y - movementBounds.extents.y) + posy * movementBounds.size.y;
                if (!moveY)
                {
                    newy = targetpos.y;
                }
                Vector2 newpos = new Vector2(newx, newy);
                targetpos = newpos;

                GameMaster.instance.UI.notifactionText.text = targetpos.ToString();
                if (!padStyle)
                {
                    MoveHead(newpos);
                }
                else
                {
                    MoveTowards(newpos);
                }
            }
        }
        //else if (Input.touchCount > 1)
        //{
        //    //for (var i = 0; i < Input.touchCount; ++i)
        //    //{
        //    //    if (Input.GetTouch(i).phase == TouchPhase.Began)
        //    //    {
        //    //        if (Input.GetTouch(i).tapCount == 2)
        //    //        {
        //    //            // double tap :)
        //    //        }
        //    //    }
        //    //}
        //}
        else if (useMouse)
        {
            Vector2 temppos = mousepos;
            //check actions
            //foreach touch
            //if touch is within move bounds move head
            GameMaster.instance.UI.notifactionText.text = temppos.ToString();
            if (inputBounds.Contains(temppos))
            {
                //Debug.Log(temppos);
                //apply max input


                float posy = temppos.y * (1 / topRightInputBound.y);
                //Debug.Log(posy);
                posy = Mathf.Min(posy, 1);
                float newx = (movementBounds.center.x - movementBounds.extents.x) + temppos.x * movementBounds.size.x;
                float newy = (movementBounds.center.y - movementBounds.extents.y) + posy * movementBounds.size.y;
                if (!moveY)
                {
                    newy = targetpos.y;
                }
                Vector2 newpos = new Vector2(newx, newy);

                targetpos = newpos;
                // GameMaster.instance.UI.notifactionText.text = targetpos.ToString();
                if (!padStyle)
                {
                    MoveHead(targetpos);
                }
                else
                {
                    MoveTowards(targetpos);
                }
            }

            //if (DoubleClick())
            //{
            //    Debug.Log("double click");
            //    ability.Use();
            //}
        }
    }
Пример #51
0
	public void MoveSpeed(Vector2 move){
		moveSpeedText.text = move.ToString();
	}
Пример #52
0
        public static void setFarmhouseCollision(Farm farm, Vector2 topLeft, FarmHouse house)
        {
            Map map          = farm.map;
            Map collisionMap = getFarmHouseCollisionMap(house); //FarmHouseStates.loader.Load<Map>("assets/maps/Collision_FarmHouse.tbin", StardewModdingAPI.ContentSource.ModFolder);

            TileSheet sheet = null;

            foreach (TileSheet tSheet in map.TileSheets)
            {
                if (tSheet.ImageSource.Contains("outdoorsTileSheet"))
                {
                    sheet = tSheet;
                    break;
                }
            }
            if (sheet == null)
            {
                sheet = map.TileSheets[0];
                Logger.Log("Could not find outdoor tilesheet!  Defaulting to the first available tilesheet, '" + sheet.Id + "'...");
            }

            string houseWarp = "Warp " + FarmHouseStates.getEntryLocation(house).X + " " + FarmHouseStates.getEntryLocation(house).Y + " FarmHouse";

            Logger.Log("House warp set to '" + houseWarp + "'");



            Logger.Log("Finding the front door on the collision map for the farmhouse...");
            Vector2 frontDoor = new Vector2(-1, -1);

            for (int x = 0; x < collisionMap.GetLayer("Buildings").LayerWidth; x++)
            {
                for (int y = 0; y < collisionMap.GetLayer("Buildings").LayerHeight; y++)
                {
                    if (collisionMap.GetLayer("Buildings").Tiles[x, y] != null && collisionMap.GetLayer("Buildings").Tiles[x, y].Properties.ContainsKey("Action"))
                    {
                        string tileAction = collisionMap.GetLayer("Buildings").Tiles[x, y].Properties["Action"].ToString();
                        if (tileAction.Contains("Warp") && tileAction.Contains("FarmHouse"))
                        {
                            Logger.Log("Found the front door!  Located at (" + x + ", " + y + ")");
                            frontDoor = new Vector2(x, y);
                            break;
                        }
                    }
                }
                if (frontDoor.X != -1)
                {
                    break;
                }
            }

            if (frontDoor.X == -1)
            {
                frontDoor = new Vector2(5, 4);
            }

            topLeft.X -= frontDoor.X;
            topLeft.Y -= frontDoor.Y;

            bool useDefaultPorch = true;

            if (collisionMap.Properties.ContainsKey("Porch"))
            {
                string porchProperty = Utility.cleanup(collisionMap.Properties["Porch"]);

                string[] coords = porchProperty.Split(' ');
                if (coords.Length >= 2)
                {
                    Vector2 coordsFromString = getCoordsFromString(porchProperty);
                    porchStandingLocation = new Point((int)(coordsFromString.X + topLeft.X), (int)(coordsFromString.Y + topLeft.Y));
                    Logger.Log("Found valid porch property; porch is now at " + porchStandingLocation.ToString());
                    useDefaultPorch = false;
                }
            }
            if (useDefaultPorch)
            {
                porchStandingLocation = new Point((int)topLeft.X + 7, (int)topLeft.Y + 5);
            }

            chimneys.Clear();

            for (int x = 0; x < collisionMap.GetLayer("Back").LayerWidth; x++)
            {
                for (int y = 0; y < collisionMap.GetLayer("Back").LayerHeight; y++)
                {
                    Vector2 currentTile = new Vector2(x + topLeft.X, y + topLeft.Y);

                    if (collisionMap.GetLayer("Back").Tiles[x, y] != null)
                    {
                        if (map.GetLayer("Back").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y] == null)
                        {
                            map.GetLayer("Back").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y] = new StaticTile(map.GetLayer("Back"), sheet, BlendMode.Alpha, 16);
                        }
                        foreach (string key in collisionMap.GetLayer("Back").Tiles[x, y].Properties.Keys)
                        {
                            map.GetLayer("Back").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y].Properties[key] = collisionMap.GetLayer("Back").Tiles[x, y].Properties[key];
                        }
                    }
                    if (collisionMap.GetLayer("Buildings").Tiles[x, y] != null)
                    {
                        if (map.GetLayer("Buildings").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y] == null)
                        {
                            map.GetLayer("Buildings").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y] = new StaticTile(map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 16);
                        }
                        if (collisionMap.GetLayer("Buildings").Tiles[x, y].TileSheet == sheet && collisionMap.GetLayer("Buildings").Tiles[x, y].TileIndex == 125)
                        {
                            map.GetLayer("Buildings").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y].Properties["Passable"] = "T";
                        }
                        foreach (string key in collisionMap.GetLayer("Buildings").Tiles[x, y].Properties.Keys)
                        {
                            if (key.Equals("Action"))
                            {
                                string warpValue = collisionMap.GetLayer("Buildings").Tiles[x, y].Properties[key].ToString();
                                if (warpValue.Contains("Warp") && warpValue.Contains("FarmHouse"))
                                {
                                    map.GetLayer("Buildings").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y].Properties[key] = houseWarp;
                                }
                            }
                            else if (key.Equals("Chimney"))
                            {
                                Logger.Log("Found a chimney at tile (" + x + ", " + y + ")");
                                string chimneyValue = collisionMap.GetLayer("Buildings").Tiles[x, y].Properties[key].ToString();
                                if (chimneyValue.Split(' ').Length == 1)
                                {
                                    Vector2 newChimney = new Vector2((topLeft.X + x + 0.5f) * 64f, (topLeft.Y + y + 0.5f) * 64f);
                                    Logger.Log("Chimney did not specify pixel coordinates; using tile center instead: " + newChimney.ToString());
                                    chimneys.Add(newChimney);
                                }
                                else
                                {
                                    Vector2 chimneyPosition = getCoordsFromString(chimneyValue);
                                    Vector2 newChimney      = new Vector2((topLeft.X + x) * 64f + chimneyPosition.X, (topLeft.Y + y) * 64f + chimneyPosition.Y);
                                    Logger.Log("Chimney did specified pixel coordinates; " + chimneyPosition.ToString() + ": " + newChimney.ToString());
                                    chimneys.Add(newChimney);
                                }
                            }
                            else
                            {
                                map.GetLayer("Buildings").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y].Properties[key] = collisionMap.GetLayer("Buildings").Tiles[x, y].Properties[key];
                            }
                        }
                        removeEverythingFromTile(farm, currentTile);
                    }
                    //else if(map.GetLayer("Buildings").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y] != null)
                    //{
                    //    map.GetLayer("Buildings").Tiles[x + (int)topLeft.X, y + (int)topLeft.Y] = null;
                    //}


                    if (castsShadow(collisionMap, x, y) && (y == collisionMap.GetLayer("Buildings").LayerHeight - 1 || !castsShadow(collisionMap, x, y + 1)))
                    {
                        Logger.Log("Tile (" + x + ", " + y + ") casts a shadow...");
                        if (x == 0 || !castsShadow(collisionMap, x - 1, y))
                        {
                            Logger.Log("Shadow is on the LEFT");
                            buildingShadows[new Vector2(x + (int)topLeft.X, y + (int)topLeft.Y)] = SHADOW_LEFT;
                        }
                        else if (x == collisionMap.GetLayer("Back").LayerWidth - 1 || !castsShadow(collisionMap, x + 1, y))
                        {
                            Logger.Log("Shadow is on the RIGHT");
                            buildingShadows[new Vector2(x + (int)topLeft.X, y + (int)topLeft.Y)] = SHADOW_RIGHT;
                        }
                        else
                        {
                            buildingShadows[new Vector2(x + (int)topLeft.X, y + (int)topLeft.Y)] = SHADOW_MID;
                        }
                    }
                }
            }
        }
Пример #53
0
        public void CanShareSnapPointsInMultipleCollections()
        {
            ScrollPresenter scrollPresenter1 = null;
            ScrollPresenter scrollPresenter2 = null;
            ScrollPresenter scrollPresenter3 = null;

            ScrollSnapPoint scrollSnapPoint1 = null;
            ScrollSnapPoint scrollSnapPoint2 = null;
            ScrollSnapPoint scrollSnapPoint3 = null;

            RepeatedScrollSnapPoint repeatedScrollSnapPoint1 = null;
            RepeatedScrollSnapPoint repeatedScrollSnapPoint2 = null;
            RepeatedScrollSnapPoint repeatedScrollSnapPoint3 = null;

            ZoomSnapPoint zoomSnapPoint1 = null;
            ZoomSnapPoint zoomSnapPoint2 = null;
            ZoomSnapPoint zoomSnapPoint3 = null;

            RunOnUIThread.Execute(() =>
            {
                scrollPresenter1 = new ScrollPresenter();
                scrollPresenter2 = new ScrollPresenter();
                scrollPresenter3 = new ScrollPresenter();

                scrollSnapPoint1 = new ScrollSnapPoint(snapPointValue: 10, alignment: ScrollSnapPointsAlignment.Near);
                scrollSnapPoint2 = new ScrollSnapPoint(snapPointValue: 20, alignment: ScrollSnapPointsAlignment.Near);
                scrollSnapPoint3 = new ScrollSnapPoint(snapPointValue: 30, alignment: ScrollSnapPointsAlignment.Near);

                repeatedScrollSnapPoint1 = new RepeatedScrollSnapPoint(offset:  10, interval: 10, start:  10, end: 100, alignment: ScrollSnapPointsAlignment.Near);
                repeatedScrollSnapPoint2 = new RepeatedScrollSnapPoint(offset: 200, interval: 10, start: 110, end: 200, alignment: ScrollSnapPointsAlignment.Near);
                repeatedScrollSnapPoint3 = new RepeatedScrollSnapPoint(offset: 300, interval: 10, start: 210, end: 300, alignment: ScrollSnapPointsAlignment.Near);

                zoomSnapPoint1 = new ZoomSnapPoint(snapPointValue: 1);
                zoomSnapPoint2 = new ZoomSnapPoint(snapPointValue: 2);
                zoomSnapPoint3 = new ZoomSnapPoint(snapPointValue: 3);

                scrollPresenter1.HorizontalSnapPoints.Add(scrollSnapPoint1);
                scrollPresenter1.HorizontalSnapPoints.Add(scrollSnapPoint2);
                scrollPresenter1.VerticalSnapPoints.Add(scrollSnapPoint1);
                scrollPresenter1.VerticalSnapPoints.Add(scrollSnapPoint3);

                scrollPresenter2.HorizontalSnapPoints.Add(repeatedScrollSnapPoint1);
                scrollPresenter2.HorizontalSnapPoints.Add(repeatedScrollSnapPoint2);
                scrollPresenter2.VerticalSnapPoints.Add(repeatedScrollSnapPoint1);
                scrollPresenter2.VerticalSnapPoints.Add(repeatedScrollSnapPoint3);

                scrollPresenter1.ZoomSnapPoints.Add(zoomSnapPoint1);
                scrollPresenter1.ZoomSnapPoints.Add(zoomSnapPoint2);
                scrollPresenter2.ZoomSnapPoints.Add(zoomSnapPoint1);
                scrollPresenter2.ZoomSnapPoints.Add(zoomSnapPoint3);

                scrollPresenter3.HorizontalSnapPoints.Add(scrollSnapPoint1);
                scrollPresenter3.HorizontalSnapPoints.Add(scrollSnapPoint1);
            });

            IdleSynchronizer.Wait();

            RunOnUIThread.Execute(() =>
            {
                Vector2 horizontalScrollSnapPoint11ApplicableZone = ScrollPresenterTestHooks.GetHorizontalSnapPointActualApplicableZone(scrollPresenter1, scrollSnapPoint1);
                Vector2 verticalScrollSnapPoint11ApplicableZone   = ScrollPresenterTestHooks.GetVerticalSnapPointActualApplicableZone(scrollPresenter1, scrollSnapPoint1);
                Log.Comment("horizontalScrollSnapPoint11ApplicableZone=" + horizontalScrollSnapPoint11ApplicableZone.ToString());
                Log.Comment("verticalScrollSnapPoint11ApplicableZone=" + verticalScrollSnapPoint11ApplicableZone.ToString());

                Vector2 horizontalScrollSnapPoint21ApplicableZone = ScrollPresenterTestHooks.GetHorizontalSnapPointActualApplicableZone(scrollPresenter2, repeatedScrollSnapPoint1);
                Vector2 verticalScrollSnapPoint21ApplicableZone   = ScrollPresenterTestHooks.GetVerticalSnapPointActualApplicableZone(scrollPresenter2, repeatedScrollSnapPoint1);
                Log.Comment("horizontalScrollSnapPoint21ApplicableZone=" + horizontalScrollSnapPoint21ApplicableZone.ToString());
                Log.Comment("verticalScrollSnapPoint21ApplicableZone=" + verticalScrollSnapPoint21ApplicableZone.ToString());

                Vector2 zoomSnapPoint11ApplicableZone = ScrollPresenterTestHooks.GetZoomSnapPointActualApplicableZone(scrollPresenter1, zoomSnapPoint1);
                Vector2 zoomSnapPoint21ApplicableZone = ScrollPresenterTestHooks.GetZoomSnapPointActualApplicableZone(scrollPresenter2, zoomSnapPoint1);
                Log.Comment("zoomSnapPoint11ApplicableZone=" + zoomSnapPoint11ApplicableZone.ToString());
                Log.Comment("zoomSnapPoint21ApplicableZone=" + zoomSnapPoint21ApplicableZone.ToString());

                int combinationCount11 = ScrollPresenterTestHooks.GetHorizontalSnapPointCombinationCount(scrollPresenter1, scrollSnapPoint1);
                int combinationCount31 = ScrollPresenterTestHooks.GetHorizontalSnapPointCombinationCount(scrollPresenter3, scrollSnapPoint1);
                Log.Comment("combinationCount11=" + combinationCount11);
                Log.Comment("combinationCount31=" + combinationCount31);

                Log.Comment("Expecting different applicable zones for ScrollSnapPoint in horizontal and vertical collections");
                Verify.AreEqual <float>(15.0f, horizontalScrollSnapPoint11ApplicableZone.Y);
                Verify.AreEqual <float>(20.0f, verticalScrollSnapPoint11ApplicableZone.Y);

                Log.Comment("Expecting identical applicable zones for RepeatedScrollSnapPoint in horizontal and vertical collections");
                Verify.AreEqual <float>(10.0f, horizontalScrollSnapPoint21ApplicableZone.X);
                Verify.AreEqual <float>(10.0f, verticalScrollSnapPoint21ApplicableZone.X);
                Verify.AreEqual <float>(100.0f, horizontalScrollSnapPoint21ApplicableZone.Y);
                Verify.AreEqual <float>(100.0f, verticalScrollSnapPoint21ApplicableZone.Y);

                Log.Comment("Expecting different applicable zones for ZoomSnapPoint in two zoom collections");
                Verify.AreEqual <float>(1.5f, zoomSnapPoint11ApplicableZone.Y);
                Verify.AreEqual <float>(2.0f, zoomSnapPoint21ApplicableZone.Y);

                Log.Comment("Expecting different combination counts for ScrollSnapPoint in two horizontal collections");
                Verify.AreEqual <int>(0, combinationCount11);
                Verify.AreEqual <int>(1, combinationCount31);
            });
        }
        //private Squad currentSelSquad;

        public void MouseSelection(GroundCombatState groundCombatState)
        {
            if (IsDeploying())
            {
                for (int currentSquad = 0; currentSquad < groundCombatState.playerSquads.Count; currentSquad++)
                {
                    Squad squad = groundCombatState.playerSquads[currentSquad];
                    if (squad.Faction == ChapterMaster.Sector.CurrentFaction)
                    {
                        for (int currentTroop = 0; currentTroop < squad.Troops.Count; currentTroop++)
                        {
                            Troop troop = squad.Troops[currentTroop];
                            if (Keyboard.GetState().IsKeyDown(Keys.LeftShift))
                            {
                                if (draggingSquad)
                                {
                                    draggingSquad = false;
                                }

                                if (Mouse.GetState().RightButton == ButtonState.Pressed) // start drag
                                {
                                    if (!assigningOrder && currentlySelectedTroop == null &&
                                        currentlySelectedSquad == null && troop.MouseOver(this, squad))
                                    {
                                        mouseOffset            = Mouse.GetState().Position.ToVector2() - troop.Position;
                                        troop.Grabbed          = true;
                                        currentlySelectedTroop = troop;
                                        currentlySelectedSquad = squad;
                                        startDragPositionTroop = currentlySelectedTroop.Position;
                                        Debug.WriteLine("start drag position: " + startDragPositionTroop.ToString());
                                        draggingTroop = true;
                                    }
                                }
                                if (troop.Grabbed && currentlySelectedTroop == troop && currentlySelectedSquad == squad)
                                {
                                    if (draggingTroop)
                                    {
                                        Debug.WriteLine(
                                            $"Currently moving troop i {currentTroop} to ${Mouse.GetState().Position.X}");
                                        // Check for collisions
                                        //Vector2 prevPosition = currentlySelectedTroop.Position;
                                        currentlySelectedTroop.Position =
                                            Mouse.GetState().Position.ToVector2() -
                                            mouseOffset;                                          // maybe check for collision here and find last valid position?
                                        if (Mouse.GetState().RightButton == ButtonState.Released) // release drag
                                        {
                                            foreach (Squad other in
                                                     groundCombatState.playerSquads) // TODO: implement for rest of squads
                                            {
                                                Debug.WriteLine("over squad" + other.Troops.Count);
                                                if (currentlySelectedSquad != null && currentlySelectedTroop != null)
                                                {
                                                    if (currentlySelectedTroop.IsCollidingWithAny(this,
                                                                                                  currentlySelectedSquad,
                                                                                                  other))
                                                    {
                                                        Debug.WriteLine("collision squad: " + squad.Troops.Count +
                                                                        "with other squad: " + other.Troops.Count);
                                                        currentlySelectedTroop.Position = startDragPositionTroop;
                                                    }
                                                    else
                                                    {
                                                        Debug.WriteLine("no collision");
                                                    }
                                                }
                                                else
                                                {
                                                    Debug.WriteLine("this should not happen");
                                                }
                                            }

                                            troop.Grabbed = false;
                                            Debug.WriteLine("drag released");
                                            currentlySelectedTroop = null;
                                            currentlySelectedSquad = null;
                                            draggingTroop          = false;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //assigningOrder = false; // todo: what is this again?
                                if (draggingTroop)
                                {
                                    if (Mouse.GetState().RightButton ==
                                        ButtonState.Released) // does this actually work as intended?
                                    {
                                        foreach (Squad other in
                                                 groundCombatState.playerSquads) // TODO: implement for rest of squads
                                        {
                                            Debug.WriteLine("over squad" + other.Troops.Count);
                                            if (currentlySelectedSquad != null && currentlySelectedTroop != null)
                                            {
                                                if (currentlySelectedTroop.IsCollidingWithAny(this,
                                                                                              currentlySelectedSquad,
                                                                                              other))
                                                {
                                                    Debug.WriteLine("collision squad: " + squad.Troops.Count +
                                                                    "with other squad: " + other.Troops.Count);
                                                    currentlySelectedTroop.Position = startDragPositionTroop;
                                                }
                                                else
                                                {
                                                    Debug.WriteLine("no collision");
                                                }
                                            }
                                            else
                                            {
                                                Debug.WriteLine("this should not happen");
                                            }
                                        }
                                        Debug.WriteLine("drag released");
                                        if (!draggingSquad)
                                        {
                                            troop.Grabbed          = false;
                                            currentlySelectedTroop = null;
                                            currentlySelectedSquad = null;
                                        }

                                        draggingTroop = false;
                                    }
                                }
                                if (Mouse.GetState().LeftButton == ButtonState.Pressed)
                                {
                                }

                                if (!draggingSquad && !draggingTroop && !assigningOrder) // TODO: fix this.
                                {
                                    currentlySelectedTroop = null;
                                    currentlySelectedSquad = null;
                                }
                            }
                            // assign order to squad

                            /*if (Mouse.GetState().LeftButton == ButtonState.Pressed) // start order
                             * {
                             *  if (currentlySelectedTroop == null && troop.MouseOver(this, squad))
                             *  {
                             *      mouseOffset = Mouse.GetState().Position.ToVector2() - troop.Position;
                             *      troop.Grabbed = true;
                             *      currentlySelectedTroop = troop;
                             *      currentlySelectedSquad = squad;
                             *      draggingTroop = false;
                             *      orderStart = squad.Position + troop.Position +
                             *                   new Vector2(troop.Size.X, troop.Size.Y / 2);
                             *      assigningOrder = true;
                             *  }
                             * }
                             * if(!draggingTroop)
                             * {
                             *  orderEnd = Mouse.GetState().Position.ToVector2();
                             *  currentlySelectedTroop.Rotation = GetOrderRotation();
                             *  Debug.WriteLine(orderEnd.ToString());
                             *  if (Mouse.GetState().LeftButton == ButtonState.Released) // release order
                             *  {
                             *      troop.Grabbed = false;
                             *      currentlySelectedTroop = null;
                             *      assigningOrder = false;
                             *  }
                             * }*/
                        }
                    }
                }

                // select squads
                if (Mouse.GetState().LeftButton == ButtonState.Pressed)
                {
                    for (int currentSquad = 0; currentSquad < groundCombatState.playerSquads.Count; currentSquad++)
                    {
                        Squad squad = groundCombatState.playerSquads[currentSquad];
                        Troop troop = squad.GetTroopUnderMouse(this);
                        if (troop != null)
                        {
                            //Debug.WriteLine("started left click");
                            if (previousLMBState == ButtonState.Released) // pressed released with mouse over
                            {
                                // select squad
                                if (!selectedSquads.Contains(squad))
                                {
                                    Debug.WriteLine("added squad" + currentSquad);
                                    selectedSquads.Add(squad);
                                    squad.Selected = true;
                                    // initiate dragging squad
                                    if (!draggingSquad)
                                    {
                                        //troopOffset = GetMouse().Position.ToVector2() - selectedSquads[0].Position;
                                        squad.troopOffset       = GetMouse().Position.ToVector2() - squad.Position;
                                        squad.startDragPosition = squad.Position; // todo: implement
                                        draggingSquad           = true;
                                    }
                                }
                                else
                                {
                                    if (!draggingSquad)
                                    {
                                        Debug.WriteLine("removed squad" + currentSquad);
                                        squad.Selected = false;
                                        selectedSquads.Remove(squad);
                                    }
                                }
                            }
                        }
                    }

                    if (!Keyboard.GetState().IsKeyDown(Keys.LeftControl))
                    {
                        if (previousLMBState == ButtonState.Pressed) // pressed pressed
                        {
                            // move squad
                            if (draggingSquad && selectedSquads.Count > 0)
                            {
                                bool wasOverOtherTroop = false;
                                foreach (Squad s in selectedSquads)
                                {
                                    foreach (Squad otherSquad in selectedSquads)
                                    {
                                        if (!selectedSquads.Contains(otherSquad))
                                        {
                                            if (otherSquad.GetTroopUnderMouse(this) != null)
                                            {
                                                wasOverOtherTroop = true;
                                            }
                                        }
                                    }
                                    if (!wasOverOtherTroop && s.GetTroopUnderMouse(this) != null)
                                    {
                                        s.Position = Mouse.GetState().Position.ToVector2() - s.troopOffset;
                                    }
                                }

                                //Debug.WriteLine($"Currently moving squad i {0} to ${Mouse.GetState().Position.X}");
                                //troop.Grabbed = true;
                            }
                        }
                        else if (previousLMBState == ButtonState.Released && !draggingSquad) // pressed released
                        {
                            for (int squadToDeselect = 0;
                                 squadToDeselect < selectedSquads.Count;
                                 squadToDeselect++)
                            {
                                selectedSquads[squadToDeselect].Selected = false;
                                selectedSquads.RemoveAt(squadToDeselect);
                                Debug.WriteLine("deselecting all");
                            }
                        }
                    }
                }
                else if (Mouse.GetState().LeftButton == ButtonState.Released && draggingSquad && selectedSquads.Count > 0 && !Keyboard.GetState().IsKeyDown(Keys.LeftControl))
                {
                    if (previousLMBState == ButtonState.Pressed)
                    {
                        Debug.WriteLine("lifted move");
                        foreach (Squad selectedSquad in selectedSquads)
                        {
                            foreach (Squad other in groundCombatState.playerSquads) // TODO: Implement for rest of squads.
                            {
                                //Debug.WriteLine("over squad" + other.Troops.Count);
                                foreach (Troop t in selectedSquad.Troops)
                                {
                                    if (t.IsCollidingWithAny(this, selectedSquad, other))
                                    {
                                        selectedSquad.Position =
                                            selectedSquad.startDragPosition; //- selectedSquad.troopOffset;
                                    }
                                }
                            }
                        }

                        draggingSquad = false;
                    }
                }
                else if (Mouse.GetState().RightButton == ButtonState.Pressed)
                {
                    if (previousRMBState == ButtonState.Released)
                    {
                        for (int currentSquad = 0; currentSquad < groundCombatState.playerSquads.Count; currentSquad++)
                        {
                            Squad squad = groundCombatState.playerSquads[currentSquad];
                            Troop troop = squad.GetTroopUnderMouse(this);
                            if (troop != null)
                            {
                                orderStart        = squad.Position + troop.Position;
                                squadBeingOrdered = squad;
                                assigningOrder    = true;
                            }
                        }
                    }
                    else if (previousRMBState == ButtonState.Pressed)
                    {
                        orderEnd = GetMouse().Position.ToVector2();
                    }
                }
                else if (Mouse.GetState().RightButton == ButtonState.Released && squadBeingOrdered != null)
                {
                    if (previousRMBState == ButtonState.Pressed)
                    {
                        squadBeingOrdered.OrderChain.AddOrderLast(new MoveOrder(orderStart, orderEnd));
                        Debug.WriteLine("endx: " + ((MoveOrder)squadBeingOrdered.OrderChain.GetCurrentOrder()).End.X);
                        assigningOrder    = false;
                        squadBeingOrdered = null;
                    }
                }
                previousLMBState = GetMouse().LeftButton;
                previousRMBState = GetMouse().RightButton;
            }
        }
Пример #55
0
 //overload. Same name, different arguments
 public void Draw(SpriteBatch sp, SpriteFont sfont)
 {
     Draw(sp);//call the other Draw method above
     sp.DrawString(sfont, Position.ToString(), Position, Color.White);
 }
Пример #56
0
    public void GetInput()
    {
        //TOUCH
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            GameMaster.instance.UI.notifactionText.text = Input.touchCount.ToString();

            if (touch.phase == TouchPhase.Began)
            {
                trackedTouch = touch;
                touchStart   = touch.position;
            }
            else
            {
                // continue track
                if (touch.phase == TouchPhase.Ended)
                {
                    Vector2 swipedir = (touch.position - touchStart).normalized;
                    //take start and end get direction
                    GameMaster.instance.UI.notifactionText.text = swipedir.ToString();
                    Swiped(swipedir);
                }
            }
        }
        //KEYBOARD
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            //todo add better exit/save/unload//back to menu
            //if level live exit level to menu, else exit application
            if (GameMaster.instance.LC.LevelPlay)
            {
                GameMaster.instance.LC.LevelPlay = false;
                GameMaster.instance.LevelExit();
            }
            else
            {
                Application.Quit();
            }
        }
        if (Input.GetKeyDown("a"))
        {
            if (acceptInput)
            {
                QueInput(Inp.Left);
            }
        }
        if (Input.GetKeyDown("d"))
        {
            if (acceptInput)
            {
                QueInput(Inp.Right);
            }
        }
        if (Input.GetKeyDown("space"))
        {
            if (acceptInput)
            {
                QueInput(Inp.Right);
            }
        }
        if (Input.GetKeyDown("s"))
        {
            if (jumping)
            {
                //forces jump to end
                //endJump = true;
            }
            else
            if (acceptInput)
            {
                QueInput(Inp.Right);
            }
        }
    }
Пример #57
0
		void DrawPath(Vector2 a, Vector2 b, BlockMap pathMap, int depth){
			
			List<PathNode> path = PathFinding.GetPath((int)a.x,(int)a.y,(int)b.x,(int)b.y,pathMap,depth,pathAllowDiagonals,pathRandomisation,1000,true);
			
			if(path != null){
				
				BlockMap bm = pathMap;
								
				Block ba = bm.GetBlockAt((int)a.x,(int)a.y,depth);
				Block bb = bm.GetBlockAt((int)b.x,(int)b.y,depth);
				
				if(ba == null){
					Debug.LogWarning("Null path block at: " + a.x + "," + a.y + " - aborting.");
					return;
				}
				
				if(bb == null){
					Debug.LogWarning("Null path block at: " + b.x + "," + b.y + " - aborting.");
					return;
				}
				
				//set the start and end nodes, as they don't come back with the path
				//PaintBlock(ba, false);
				//PaintBlock(bb, false);
				
				
				int upper_val, lower_val;
				
				upper_val = (int)(pathWidth / 2.0f);
				lower_val = upper_val;
				
				if(pathWidth % 2 != 0){
					upper_val += 1;
				}
				
				
				for(int x = ba.x-lower_val; x < ba.x+upper_val; x++){
						
					for(int y = ba.y-lower_val; y < ba.y+upper_val; y++){
				
						Block pB = bm.GetBlockAt(x,y,depth);
						
						if(pB != null){
							PaintBlock(pB,false);
						}
						
					}	
					
				}
				
				for(int x = bb.x-lower_val; x < bb.x+upper_val; x++){
						
					for(int y = bb.y-lower_val; y < bb.y+upper_val; y++){
				
						Block pB = bm.GetBlockAt(x,y,depth);
						
						if(pB != null){
							PaintBlock(pB,false);
						}
						
					}	
					
				}
				
				for(int i = 0; i < path.Count; i++){
															
					for(int x = path[i].x-lower_val; x < path[i].x+upper_val; x++){
						
						for(int y = path[i].y-lower_val; y < path[i].y+upper_val; y++){
					
							Block pB = bm.GetBlockAt(x,y,depth);
							
							if(pB != null){
								PaintBlock(pB,false);
							}
							
						}	
						
					}
				}
				
			}
			else{
				Debug.LogWarning("No path could be found between " + a.ToString() + " and " + b.ToString());
			}
			
		}
Пример #58
0
 public override string ToString()
 {
     return("(" + center.ToString() + "),r:" + r.ToString());
 }
    void test()
    {
        float startTime = Time.realtimeSinceStartup;
        var w = 100;
        var h = 100;
        var p1 = new BezierPoint(new Vector2(10, 0), new Vector2(5, 20), new Vector2(20, 0));
        var p2 = new BezierPoint(new Vector2(50, 10), new Vector2(40, 20), new Vector2(60, -10));
        var c = new BezierCurve(p1.main, p1.control2, p2.control1, p2.main);
        p1.curve2 = c;
        p2.curve1 = c;
        Vector2 elapsedTime = new Vector2((Time.realtimeSinceStartup - startTime) * 10, 0);
        float startTime2 = Time.realtimeSinceStartup;
        for (var i = 0; i < w * h; i++)
        {
            Mathfx.IsNearBezier(new Vector2(Random.value * 80, Random.value * 30), p1, p2, 10);
        }

        Vector2 elapsedTime2 = new Vector2((Time.realtimeSinceStartup - startTime2) * 10, 0);
        Debug.Log("Drawing took " + elapsedTime.ToString() + "  " + elapsedTime2.ToString());
    }
Пример #60
0
    private void Bake()
    {
        Color         cameraColor = camera.backgroundColor;
        RenderTexture prev        = camera.targetTexture;

        float ratio = (float)currentFrame / (float)(frames);

        EditorUtility.DisplayProgressBar("Progress...", ((target is Animator) && clips.Count > 0? clips [clipIndex].name:target.name) + "  " + currentFrame + "/" + frames, ratio);
        //Simulate ();

        RenderTexture rt = new RenderTexture((int)resolution.x, (int)resolution.y, 24, RenderTextureFormat.ARGB32);

        camera.backgroundColor = Color.black;
        camera.targetTexture   = rt;
        camera.Render();
        RenderTexture.active = rt;

        Texture2D black = new Texture2D((int)resolution.x, (int)resolution.y, TextureFormat.ARGB32, false);

        black.ReadPixels(new Rect(0, 0, (int)resolution.x, (int)resolution.y), 0, 0);
        black.Apply();

        camera.backgroundColor = Color.white;
        camera.Render();
        Texture2D white = new Texture2D((int)resolution.x, (int)resolution.y, TextureFormat.ARGB32, false);

        white.ReadPixels(new Rect(0, 0, (int)resolution.x, (int)resolution.y), 0, 0);
        white.Apply();

        camera.targetTexture = null;
        RenderTexture.active = null;

        Texture2D tex  = ExtractTexture(black, white, (int)resolution.x, (int)resolution.y);
        Vector2   view = views.Count > 0? views [viewIndex]:Vector2.zero;

        tex.name = System.String.Format(((target is Animator)?(clips.Count > clipIndex ? clips [clipIndex].name : "sprite"):target.name) + " " + view.ToString() + " {0:D04}", currentFrame);
        tex.alphaIsTransparency = true;
        textures.Add(tex);

        camera.targetTexture   = prev;
        camera.backgroundColor = cameraColor;
        currentFrame++;

        if (currentFrame > frames - 1)
        {
            if (clips.Count - 1 > clipIndex)
            {
                clipIndex++;
                bakeAction = StartBake;
            }
            else
            {
                bakeAction = EndBake;
            }
        }
    }