// Paints the obstacle tiles in green
    public void paintObstacle(IntVector2 index)
    {
        GameObject t = TileGenerator.tiles[index.x,index.y];

        if(t.tag == "Tile")
        {
            if(t.renderer)
            {
                t.renderer.material = green;
            }
            else
            {
                t.GetComponentsInChildren<Renderer>()[1].material = green;
            }

            t.tag = "Obstacle";
        }
        else
        {
            if(t.renderer)
            {
                t.renderer.material = grey;
            }
            else
            {
                t.GetComponentsInChildren<Renderer>()[1].material = grey;
            }

            t.tag = "Tile";
        }
    }
Example #2
0
        public static void Calculate(IntVector2 viewerLocation, int visionRange, Grid2D<bool> visibilityMap, IntSize2 mapSize,
			Func<IntVector2, bool> blockerDelegate)
        {
            visibilityMap.Clear();

            if (blockerDelegate(viewerLocation) == true)
                return;

            for (int y = -visionRange; y <= visionRange; ++y)
            {
                for (int x = -visionRange; x <= visionRange; ++x)
                {
                    var dst = viewerLocation + new IntVector2(x, y);

                    if (mapSize.Contains(dst) == false)
                    {
                        visibilityMap[x, y] = false;
                        continue;
                    }

                    bool vis = FindLos(viewerLocation, dst, blockerDelegate);
                    visibilityMap[x, y] = vis;
                }
            }
        }
    List<DungeonArea> MakeTunnel( IntVector2 pointA, IntVector2 pointB )
    {
        var roomsColor = SUtil.SRandom.SRandom.GetRandomColor();

        foreach (var r in dunArea_)
            r.color_ = roomsColor;

        IntRect[] areas = dunArea_.Select(r => r.area_).ToArray();

        IntVector2[] points = new IntVector2[]
        {
            pointA,
            pointB,
        };

        var diffArea = IntRect.BLTRRect( points[0], points[1] );

        DungeonArea[] halls = new DungeonArea[]
        {
            new DungeonArea( diffArea ),
            //new DungeonArea( points[0]),
            //new DungeonArea( points[1]),
        };

        var hallcolors = new Color[]
        {
            Color.green, Color.red, Color.red
        };

        for (int i = 0; i < halls.Length; ++i)
            halls[i].color_ = hallcolors[i];

        return halls.ToList();
    }
Example #4
0
    public static void applyTextureToAnotherTexture(ref TextureColorArray source, ref TextureColorArray destination, IntVector2 centerInDestination)
    {
        _leftX  = centerInDestination.x - source.width / 2;
        _rightX = _leftX + source.width;
        _downY  = centerInDestination.y - source.height / 2;
        _topY   = _downY + source.height;

        _srcLeftX = _leftX < 0 ? -_leftX : 0;
        _srcDownY = _downY < 0 ? -_downY : 0;

        _leftX  = _leftX  <  0                  ? 0                      : _leftX ;
        _rightX = _rightX >= destination.width  ? destination.width    : _rightX;
        _downY  = _downY  <  0                  ? 0                      : _downY ;
        _topY   = _topY   >= destination.height ? destination.height  : _topY  ;

        _srcY = _srcDownY * source.width;
        _destY = _downY * destination.width;
        for (_y = _downY; _y < _topY; _y++) {
            _srcX = _srcLeftX;
            for (int _x = _leftX; _x < _rightX; _x++) {

                if (source.Colors [_srcY  + _srcX].a > destination.Colors [_destY + _x].a)
                    destination.Colors [_destY + _x] = source.Colors [_srcY  + _srcX];
                _srcX ++;
            }
            _srcY  += source.width;
            _destY += destination.width;
        }
    }
 public Entity ReplacePosition(IntVector2 newValue)
 {
     var component = CreateComponent<PositionComponent>(ComponentIds.Position);
     component.value = newValue;
     ReplaceComponent(ComponentIds.Position, component);
     return this;
 }
 public Entity ReplaceVelocity(IntVector2 newValue)
 {
     var component = CreateComponent<VelocityComponent>(ComponentIds.Velocity);
     component.value = newValue;
     ReplaceComponent(ComponentIds.Velocity, component);
     return this;
 }
	public virtual bool PlaceAtLocation(IntVector2 location)
	{
		Location = location;
		if (location != null)
		{
			hexCell = GridManager.instance.GetHexCell(location);
			if (hexCell != null)
			{
				transform.position = hexCell.transform.position;
				hexCell.placedPlaceable = this;
				return true;
			}
		}
		else
		{
			if (hexCell != null)
			{
				if (hexCell.placedPlaceable == this)
				{
					hexCell.placedPlaceable = null;
				}
				hexCell = null;
			}
		}
		return false;
	}
Example #8
0
    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Rigidbody body = hit.collider.attachedRigidbody;

        MazeCell cell = hit.gameObject.GetComponentInParent<MazeCell>();
        if (cell == null)
            return;

        if(cell != currentCell)
        {
            if(currentCell != null)
                currentCell.OnPlayerExit();

            cell.OnPlayerEnter();
        }

        currentCell = cell;
        Vector3 transformDirection = new Vector3(Mathf.Round(transform.forward.x), 0f, Mathf.Round(transform.forward.z));
        IntVector2 direction = new IntVector2((int) transformDirection.x, (int) transformDirection.z);

        if(direction.x != 0 && direction.z != 0)
        {
            if (Random.Range(0, 1) == 1)
                direction.x = 0;
            else
                direction.z = 0;
        }

        MazeDirection mazeDirection = MazeDirections.FromIntVector2(direction);
        faceDirection = mazeDirection;
    }
	public virtual bool Decode (Encoding encoding)
	{
		IntVector2 newLocation = new IntVector2(encoding.Int(0)-31, encoding.Int (1)-31);
		Mechanism placedMechanism = GridManager.instance.GetHexCell(newLocation).placedMechanism;
		
		bool didReplacedPart = false;
		if (placedMechanism != null) // we are replacing a part
		{
			if (placedMechanism.MechanismType == MechanismType && // we are replacing the same type of part
				placedMechanism.Location.IsEqualTo(newLocation) && // the location of the old part is the same as this new one (important for multicell mechanisms e.g. weldingRig)
				!placedMechanism.isSolutionMechanism) // is a level mechanism (not part of the solution, part of the problem ;p)
			{
				ObjectPoolManager.DestroyObject(placedMechanism);
				PlaceAtLocation(newLocation);
				isSolutionMechanism = false; // we use the already on board's movable (i.e. immovable)
				
			}
			else
			{
				// something went wrong, we are loading a mechanism on top of one that is different, or a solution mechanism
				Debug.LogError("Something went wrong, we are loading a mechanism on top of one that is different, or a solution mechanism");
				return false;
			}
		}
		else // this is a new part
		{
			PlaceAtLocation(newLocation);
			isSolutionMechanism = (int)encoding.Int(2) == 1;
		}
		
		return true;
	}
Example #10
0
		/// <summary>
		/// Instantiate a given square prefab with the given coordinates. Set all the right
		/// properties and add it to the board.
		/// </summary>
		/// <param name="squarePrefab">Square prefab.</param>
		/// <param name="boardPosition">The position on the board to instantiate to.</param>
		private void InstantiateSquare(GameObject squarePrefab, IntVector2 boardPosition) {
			// instantiate the square and size it correctly
			GameObject square = Instantiate<GameObject>(squarePrefab);
			square.transform.SetParent(transform, false);
			RectTransform squareRectTransform = square.transform as RectTransform;
			squareRectTransform.sizeDelta = cellSize;

			// assign collider properties
			BoxCollider2D collider = square.GetComponent<BoxCollider2D>();
			if (collider == null) {
				Debug.LogErrorFormat("Generated square at {0} does not have a box collider 2d component.", boardPosition);
				return;
			}
			collider.size = cellSize;

			// assign tile properties
			Tile tile = square.GetComponent<Tile>();
			if (tile == null) {
				Debug.LogErrorFormat("Generated square at {0} does not have a tile component.", boardPosition);
				return;
			}
			tile.Coordinates = boardPosition;
			tile.SetParentBoard(this);

			// add to the board
			board[boardPosition.x, boardPosition.y] = square;
		}
Example #11
0
        GameAction DoMove(Direction dir)
        {
            IntVector2 ov = new IntVector2(dir);

            if (ov.IsNull)
                return new WaitAction(1);

            var env = this.Worker.Environment;

            for (int i = 0; i < 7; ++i)
            {
                var v = ov.FastRotate(((i + 1) >> 1) * (((i % 2) << 1) - 1));
                var d = EnvironmentHelpers.AdjustMoveDir(env, this.Worker.Location, v.ToDirection());

                if (d != Direction.None)
                    return new MoveAction(d);
            }

            if (EnvironmentHelpers.CanMoveFromTo(this.Worker, Direction.Up))
                return new MoveAction(Direction.Up);

            if (EnvironmentHelpers.CanMoveFromTo(this.Worker, Direction.Down))
                return new MoveAction(Direction.Down);

            return new WaitAction(1);
        }
    void doFloodFill(IntVector2 position)
    {
        if (canvas.persistentLayer[(int)(position.y * canvas.size.x + position.x)]){
            if (WorkspaceEventManager.instance.onWrongAction!=null)
                WorkspaceEventManager.instance.onWrongAction("persistentborder click");
            return;
        }

        Color32[] colors= canvas.fetchColors();
        if (canvas.persistentLayer[(int)(position.y * canvas.size.x + position.x)])
            return;
        bool[,] resultRegion = TextureUtil.floodFillLineGetRegion (position, canvas.actualColors, canvas.persistentLayer, canvasConfig.canvasSize.x, canvasConfig.canvasSize.y);
        Color32 activeColor = props.colorProperties.activeColor;
        int tCounter = 0;
        for (int yy = 0; yy < canvasConfig.canvasSize.y; yy++) {
            for (int xx = 0; xx < canvasConfig.canvasSize.x; xx++) {
                if (resultRegion[xx,yy]){
                    colors[tCounter].r = activeColor.r;
                    colors[tCounter].g = activeColor.g;
                    colors[tCounter].b = activeColor.b;
                    colors[tCounter].a = 255;
                }
                tCounter++;
            }
        }
        canvas.applyColors(colors,true,true,position);
    }
    private void Start() {

        //init communcation channels 
        textCommChannel = CommunicationChannelFactory.Make2WayTextChannel() as TextCommunicationChannel;
        oneWayCommChannel = CommunicationChannelFactory.MakeOneWayTextChannel() as OneWayTextCommunication;
        roomExitCommChannel = CommunicationChannelFactory.MakeRoomExitPathChannel() as RoomExitPathCommChannel;
        oneWayTimedComm = CommunicationChannelFactory.MakeOneWayTimedChannel() as OneWayTimedCommChannel;
        stillnessTimedComm = CommunicationChannelFactory.MakeTimedStillnessChannel() as StillnessTimedCommChannel;

        //init object mover
        objectMover = ObjectMover.CreateObjectMover();

        playerCurrentCoords = player.MazeCellCoords;

        //start out not in communcation
        aiCommState = AICommunicationState.NotInCommuncation;
        aiAlignmentState = AIAlignmentState.Neutral;

        //initialize list of possible actions (for each state)
        InitializeActionLists();

        roomsRequestedIn = new Dictionary<IntVector2, bool>();

        rng = new System.Random();
    }
    public float Distance(IntVector2 v)
    {
        float r1 = x - v.x;
        float r2 = y - v.y;

        return (float)Math.Sqrt(r1 * r1 + r2 * r2);
    }
Example #15
0
    public void applyColors(Color32[] colors, bool sendEvents = true, bool radialAnimate = false, IntVector2 center = null)
    {
        for (int i = 0; i < colors.Length; i++) {
            if (colors[i].a !=0){
                _r = _actualColors[i].r;
                _actualColors[i].r = colors[i].r;
                colors[i].r = _r;

                _g = _actualColors[i].g;
                _actualColors[i].g = colors[i].g;
                colors[i].g = _g;

                _b = _actualColors[i].b;
                _actualColors[i].b = colors[i].b;
                colors[i].b = _b;
            }
        }

        if (radialAnimate){
            IntVector2 point;
            if (center == null){
                 point = new IntVector2( config.canvasSize.x/2, config.canvasSize.y/2);
            } else {
                point = center;
            }
            StartCoroutine(radialLayer.updateColorsAndAnimate(colors,point));
        }

        StartCoroutine( backLayer.updateColors(_actualColors, radialAnimate));
        if (sendEvents && events.onActiveReceiveNewColors != null)
            events.onActiveReceiveNewColors();
    }
Example #16
0
    void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
    {
        BoardLocation newLocation= new BoardLocation(new IntVector2(0,0), new IntVector2(0,0));
        int maxSpeed = 0;
        IntVector2 direction = new IntVector2(0,0);
        BoardLocation lastBoardLocation = new BoardLocation(new IntVector2( 0, 0), new IntVector2(0,0));

        if (stream.isWriting)
        {
            newLocation = this.boardLocation;
            maxSpeed = this.maxSpeed;
            direction = this.direction;
            lastBoardLocation = this.lastBoardLocation;

            newLocation.Serialize( stream );
            stream.Serialize( ref maxSpeed );
            direction.Serialize( stream );
            lastBoardLocation.Serialize( stream );
        }
        else
        {
            newLocation.DeSerialize( stream );
            stream.Serialize( ref maxSpeed );
            direction.DeSerialize( stream );
            lastBoardLocation.DeSerialize( stream );

            this.boardLocation = newLocation;
            this.maxSpeed = maxSpeed;
            this.direction = direction;
            this.lastBoardLocation = lastBoardLocation;
        }
    }
Example #17
0
    void DrawRoom( IntVector2 pos, IntVector2 size )
    {
        //  char count = '0';
        var yMax = size.y - 1;
        var xMax = size.x - 1;
        for( int x = 0; x < size.x; ++x )
        {
            for( int y = 0; y < size.y; ++y )
            {
                RLTile t = baseTiles_.GetRandomFloor();

                if( (x == 0 || x == xMax ) && y != 0 )
                    t = baseTiles_.walls_.doubleVert_;

                if( (y == 0 || y == yMax ) && x != 0 )
                    t = baseTiles_.walls_.doubleHor_;

                if (x == 0 && y == 0)
                    t = baseTiles_.walls_.doubleBLCorner_;

                if ( x == 0 && y == yMax )
                    t = baseTiles_.walls_.doubleTLCorner_;

                if( x == xMax && y == yMax )
                    t = baseTiles_.walls_.doubleTRCorner_;

                if( x == xMax && y == 0 )
                    t = baseTiles_.walls_.doubleBRCorner_;

                SetTile(x + pos.y, y + pos.y, t.ch_, t.color_ );
            }
        }
    }
Example #18
0
    public void MoveByVector(IntVector2 offset)
    {
        IntVector2 newPos = Map.BoundPos(pos+offset);
        if (mode == CATCH) {

            IntVector2 totemNewPos = Map.BoundPos (pos + dir + offset);
            if (offset == dir) { // forward
                if (Map.mainMap [totemNewPos.x, totemNewPos.y].Count != 0) {
                    return;
                }
            } else if (offset == -dir) { // backward
                if (Map.mainMap [newPos.x, newPos.y].Count != 0)
                    return;
            } else { // 平移
                if (Map.mainMap [totemNewPos.x, totemNewPos.y].Count != 0 ||
                    Map.mainMap [newPos.x, newPos.y].Count != 0)
                    return;
            }
            // Update the pos of the caught totem
            IntVector2 totemPre = new IntVector2(caughtTotem.pos.x, caughtTotem.pos.y);
            caughtTotem.pos = totemNewPos;
            Map.UpdatePos (caughtTotem, totemPre);

        } else if (Map.mainMap [newPos.x, newPos.y].Count != 0) {
                return;
        }

        base.MoveByVector (offset);
    }
Example #19
0
    void onMouseOverWithButtonDone(IntVector2 obj)
    {
        Profiler.BeginSample("onMouseOverWithButtonDone");
        Profiler.BeginSample("init start");
        points.Add(obj);
        InterpolateContext ic = new InterpolateContext (new LinearInterpolationStrategy());
        Profiler.EndSample();

        Profiler.BeginSample("interpolation");
        if (interpolatedPath==null)
            interpolatedPath= new List<IntVector2>();
        else
            interpolatedPath.Clear();
        ic.interpolate(points, interpolatedPath);
        Profiler.EndSample();
        Profiler.BeginSample("fetch colors");
        Color32[] workingColors= canvas.fetchColors();
        Profiler.EndSample();

        Profiler.BeginSample("apply points with cache");
        TextureUtil.generateTexturePath(canvasTool, ColorUtil.getRandomColor(),interpolatedPath,workingColors,canvasConfig.canvasSize.x, canvasConfig.canvasSize.y);
        Profiler.EndSample();

        Profiler.BeginSample("update back layer");
        Debug.Log("change color and use aply method");
        //canvas.applyColors(workingColors, ColorUtil.getRandomColor());
        Profiler.EndSample();
        Profiler.EndSample();
    }
Example #20
0
        static void Diamond(Context ctx, IntVector2 middle, int radius)
        {
            double v1, v2, v3, v4;
            IntVector2 p1, p2, p3, p4;

            p1 = middle.Offset(0, -radius);
            v1 = GetGridValue(ctx, p1);

            p2 = middle.Offset(-radius, 0);
            v2 = GetGridValue(ctx, p2);

            p3 = middle.Offset(0, radius);
            v3 = GetGridValue(ctx, p3);

            p4 = middle.Offset(radius, 0);
            v4 = GetGridValue(ctx, p4);

            var avg = (v1 + v2 + v3 + v4) / 4;
            var val = avg + GetRandom(ctx, ctx.Range);

            ctx.Grid[middle] = val;

            if (val < ctx.Min)
                ctx.Min = val;
            if (val > ctx.Max)
                ctx.Max = val;
        }
Example #21
0
        /// <summary>
        /// Line using linear interpolation
        /// </summary>
        public static IEnumerable<IntVector2> PlotLine(IntVector2 p0, IntVector2 p1)
        {
            const int MUL = 1 << 16;

            IntVector2 v = p1 - p0;

            int N = Math.Max(Math.Abs(v.X), Math.Abs(v.Y));

            int dx, dy;

            if (N == 0)
            {
                dx = dy = 0;
            }
            else
            {
                dx = (v.X * MUL) / N;
                dy = (v.Y * MUL) / N;
            }

            int x = 0;
            int y = 0;

            for (int step = 0; step <= N; step++)
            {
                var p = new IntVector2(p0.X + MyMath.DivRoundNearest(x, MUL), p0.Y + MyMath.DivRoundNearest(y, MUL));

                yield return p;

                x += dx;
                y += dy;
            }
        }
Example #22
0
    public void Rotate(IntVector2 a)
    {
        dir = a;

        int angle;
        angle = a.x==0? (90*a.y):(90 - 90*a.x + 45*a.x*a.y);
        transform.rotation = Quaternion.Euler (0.0f, 0.0f, (float)angle);
    }
 public IEnumerable<IntVector2> SpiralPoints(IntVector2 start)
 {
     var rectangle = new Rectangle(0, 0, sourceData.Width, sourceData.Height);
     var spiralPoints = SpiralFromCached(start);
     var linearlyDistributed = DistributionCache.Select(index => spiralPoints[index]);
     var result = linearlyDistributed.Where(point => rectangle.Contains(point));
     return result.ToLazyList();
 }
Example #24
0
 public void onMouseOver(IntVector2 pixelCursorPosition, Vector3 globalCursorPosition)
 {
     if (drawCursor) {
         Graphics.DrawMesh (mesh, globalCursorPosition, rotation, material, 8, canvasCam);
         Graphics.DrawMesh (maskMesh, globalCursorPosition, rotation,
                            PropertiesSingleton.instance.cursors.cursorMaskMaterial, 8, canvasCam);
     }
 }
Example #25
0
 /// <summary>
 /// Allows the game to perform any initialization it needs to before starting to run.
 /// This is where it can query for any required services and load any non-graphic
 /// related content.  Calling base.Initialize will enumerate through any components
 /// and initialize them as well.
 /// </summary>
 protected override void Initialize()
 {
     // TODO: Add your initialization logic here
     IntVector2 obj = new IntVector2(5,10);
     OverWorld.Block block = new OverWorld.Block();
     XmlLoader.Save(block, "block.xml");
     base.Initialize();
 }
Example #26
0
    public static void UpdatePos(Character c, IntVector2 pre)
    {
        if (c.pos == pre)
            return;

        mainMap [pre.x, pre.y].Remove (c);
        mainMap [c.pos.x, c.pos.y].Add(c);
    }
Example #27
0
 public Vector3 getWorldCoordsFromMazeCoords(IntVector2 pos)
 {
     float worldX = ((float)pos.x - 19.5f)*4f;
     float worldZ = ((float)pos.z - 19.5f)*4f;
     float worldY = Terrain.activeTerrain.SampleHeight (new Vector3 (worldX, 0, worldZ))+2.0f;
     Debug.Log ("WORLDY:" + worldY.ToString ());
     return new Vector3 (worldX, worldY, worldZ);
 }
	private MazeCell CreateCell (IntVector2 coordinates) {
		MazeCell newCell = Maze.Instantiate(maze.cellPrefab) as MazeCell;
		maze.cells[coordinates.x, coordinates.z] = newCell;
		newCell.coordinates = coordinates;
		newCell.name = "Maze Cell " + coordinates.x + ", " + coordinates.z;
		newCell.transform.parent = maze.transform;
		newCell.transform.localPosition = new Vector3(coordinates.x - maze.size.x * 0.5f + 0.5f, 0f, coordinates.z - maze.size.z * 0.5f + 0.5f);
		return newCell;
	}
Example #29
0
 public CanvasRadialLayer(IntVector2 size, float zPosition, Shader shader, Texture radialTexture, CanvasCamera canvasCamera)
     : base(size,zPosition, shader, canvasCamera)
 {
     this.radialTexture = radialTexture;
     material.SetTexture("_FillTex", radialTexture);
     enabled = false;
     this.texture = new Texture2D(size.x,size.y, textureFormat,false);
     material.mainTexture = texture;
 }
 private Hint CreateAHint(IntVector2 coordinates, IntVector2 size)
 {
     Hint hint = Instantiate(hintFrefab) as Hint;        
     hint.coordinates = coordinates;
     hint.name = "Hint" + coordinates.x + ", " + coordinates.z;
     hint.transform.parent = transform;
     hint.transform.localPosition = new Vector3(coordinates.x - size.x * 0.5f + 0.5f, 0f, -coordinates.z - size.z * 0.5f + 0.5f);
     return hint;
 }
Example #31
0
 public override void OnMouseOverTile(IntVector2 point)
 {
 }
Example #32
0
 public void DrawLine(IntVector2 point, IntVector2 direction)
 {
     // UNITTEST
     DrawRay(point, direction);
     DrawRay(point, -direction);
 }
Example #33
0
    void CreateBoard()
    {
        ClearBoard();
        Vector2 boardVector = new Vector2(125 * Board.boardSize.x, 125 * Board.boardSize.y);

        transform.GetComponent <RectTransform>().sizeDelta = boardVector;
        transform.localPosition = boardVector * new Vector2(-0.5f, -0.5f);
        int rndGemsToGen = 0;

        //Сетап всего не рандомного
        for (int i = 0; i < Board.boardSize.x; i++)
        {
            for (int j = 0; j < Board.boardSize.y; j++)
            {
                IntVector2 posInArray = new IntVector2(i, j);
                if (level.matrixSpawnArray[i, j] == 1)
                {
                    AutoInstantiate(spawnPref, posInArray, spawnParent);
                    Board.spawnPoints.Add(new IntVector2(i, j));
                }
                switch (level.matrixTypeTileArray[i, j])
                {
                case TileType.OBSTACLE:     //0 Empty 1 Box
                    switch (level.matrixTypeArray[i, j])
                    {
                    case TileTypeTag.EMPTY:
                        CreateTile(obstaclePrefs[TileTypeTag.EMPTY], posInArray, TileType.OBSTACLE);
                        break;

                    case TileTypeTag.BOX_OBST:
                        CreateTile(bgTilePrefab, posInArray, TileType.BACKGROUND);
                        CreateTile(obstaclePrefs[TileTypeTag.BOX_OBST], posInArray, TileType.OBSTACLE);
                        break;

                    default:
                        break;
                    }
                    break;

                case TileType.DEFAULT:
                    CreateTile(bgTilePrefab, posInArray, TileType.BACKGROUND);
                    switch (level.matrixTypeArray[i, j])
                    {
                    case TileTypeTag.RND:
                        rndTilesMap[i, j] = true;
                        rndGemsToGen++;
                        break;

                    //break;
                    case TileTypeTag.RED:
                        CreateTile(gemPrefs[TileTypeTag.RED], posInArray, TileType.DEFAULT);
                        break;

                    case TileTypeTag.GREEN:
                        CreateTile(gemPrefs[TileTypeTag.GREEN], posInArray, TileType.DEFAULT);
                        break;

                    case TileTypeTag.BLUE:
                        CreateTile(gemPrefs[TileTypeTag.BLUE], posInArray, TileType.DEFAULT);
                        break;

                    case TileTypeTag.YELLOW:
                        CreateTile(gemPrefs[TileTypeTag.YELLOW], posInArray, TileType.DEFAULT);
                        break;

                    case TileTypeTag.PURPLE:
                        CreateTile(gemPrefs[TileTypeTag.PURPLE], posInArray, TileType.DEFAULT);
                        break;

                    default:
                        Debug.Log(i + " " + j);
                        break;
                    }
                    break;

                case TileType.BOOSTER:
                    CreateTile(bgTilePrefab, posInArray, TileType.BACKGROUND);
                    switch (level.matrixTypeArray[i, j])
                    {
                    case TileTypeTag.HORIZ_BOOST:
                        CreateTile(boosterPrefs[TileTypeTag.HORIZ_BOOST], posInArray, TileType.BOOSTER);
                        break;

                    case TileTypeTag.VERT_BOOST:
                        CreateTile(boosterPrefs[TileTypeTag.VERT_BOOST], posInArray, TileType.BOOSTER);
                        break;

                    case TileTypeTag.COLOR_BOOST:
                        CreateTile(boosterPrefs[TileTypeTag.COLOR_BOOST], posInArray, TileType.BOOSTER);
                        break;

                    case TileTypeTag.BOMB_BOOST:
                        CreateTile(boosterPrefs[TileTypeTag.BOMB_BOOST], posInArray, TileType.BOOSTER);
                        break;
                    }
                    break;

                default:
                    Debug.Log(level.matrixTypeTileArray[i, j]);
                    break;
                }
                if (level.matrixLockArray[i, j] != TileTypeTag.NONE)
                {
                    switch (level.matrixLockArray[i, j])
                    {
                    case TileTypeTag.IRON:
                        CreateTile(lockPrefs[TileTypeTag.IRON], posInArray, TileType.LOCK);
                        break;

                    case TileTypeTag.ICE:
                        break;
                    }
                }
            }
        }
        CreateRandomTiles(rndGemsToGen);
        CreateBorders();
        GameManager.singleton.UpdateGameState(GameState.Move);
    }
Example #34
0
 public bool IsInMap(IntVector2 position)
 {
     return(position.X >= 0 && position.Y >= 0 && position.X < MapGrid.GetLength(1) && position.Y < MapGrid.GetLength(0));
 }
 public void onMouseDown(IntVector2 position)
 {
 }
 public void onMouseOverWithButton(IntVector2 position, Vector3 globalPosition)
 {
 }
Example #37
0
 //This is a helper function to check if a set of coordinates are valid.  (out of bounds)
 bool AreCoordsValid(IntVector2 coords)
 {
     return(coords.x >= 0 && coords.y >= 0 &&
            coords.x < m_Grid.GetLength(0) && coords.y < m_Grid.GetLength(1));
 }
Example #38
0
 public void AddValue(IntVector2 point, float value)
 {
     SetValue(point, GetValue(point) + value);
 }
Example #39
0
 public IntVector3(IntVector2 v, int y)
 {
     this.x = v.x;
     this.z = v.z;
     this.y = y;
 }
 public void onTouchOver(IntVector2 pixelPosition, Vector3 globalPosition)
 {
     point = pixelPosition;
 }
 public void onMouseOver(IntVector2 pixelCursorPosition, Vector3 globalCursorPosition)
 {
 }
 public int GetTileType(IntVector2 vector)
 {
     return(GetTileType(vector.X, vector.Y));
 }
Example #43
0
        // Token: 0x0600004E RID: 78 RVA: 0x0000414C File Offset: 0x0000234C
        public static SpeculativeRigidbody SetUpSpeculativeRigidbody(this tk2dSprite sprite, IntVector2 offset, IntVector2 dimensions)
        {
            SpeculativeRigidbody orAddComponent = sprite.gameObject.GetOrAddComponent <SpeculativeRigidbody>();
            PixelCollider        pixelCollider  = new PixelCollider();

            pixelCollider.ColliderGenerationMode = PixelCollider.PixelColliderGeneration.Manual;
            pixelCollider.CollisionLayer         = CollisionLayer.EnemyCollider;
            pixelCollider.ManualWidth            = dimensions.x;
            pixelCollider.ManualHeight           = dimensions.y;
            pixelCollider.ManualOffsetX          = offset.x;
            pixelCollider.ManualOffsetY          = offset.y;
            orAddComponent.PixelColliders        = new List <PixelCollider>
            {
                pixelCollider
            };
            return(orAddComponent);
        }
Example #44
0
    //检测垂直碰撞:检测方式与水平同理
    private void CheckVerticalCollision()
    {
        contactPoint.y = 0;
        IntVector2 tilePosition = owner.room.GetTilePosition(lastPos);
        int        collideNum   = 0;

        if (vel.y > 0.0)
        {
            int  y1       = owner.room.GetTilePosition(new Vector2(0.0f, pos.y + TerrainRad)).y;
            int  y2       = owner.room.GetTilePosition(new Vector2(0.0f, lastPos.y + TerrainRad)).y;
            int  x1       = owner.room.GetTilePosition(new Vector2((float)(pos.x - TerrainRad + 1.0), 0.0f)).x;
            int  x2       = owner.room.GetTilePosition(new Vector2((float)(pos.x + TerrainRad - 1.0), 0.0f)).x;
            bool @checked = false;
            for (int y = y2; y <= y1 && !@checked; ++y)
            {
                for (int x = x1; x <= x2 && !@checked; ++x)
                {
                    if (owner.room.GetTile(x, y).Terrain == Room.Tile.TerrainType.Solid && owner.room.GetTile(x, y - 1).Terrain != Room.Tile.TerrainType.Solid && (tilePosition.y < y || owner.room.GetTile(lastPos).Terrain == Room.Tile.TerrainType.Solid))
                    {
                        pos.y = y * 20f - TerrainRad;
                        if (vel.y > (double)PhysicalObject.impactTreshhold)
                        {
                            owner.TerrainImpact(index, new IntVector2(0, 1), Mathf.Abs(vel.y), lastContactPoint.y < 1);
                        }
                        contactPoint.y = 1;
                        vel.y          = -Mathf.Abs(vel.y) * owner.bounce;
                        if (Mathf.Abs(vel.y) < 1.0 + 9.0 * (1.0 - owner.bounce))
                        {
                            vel.y = 0.0f;
                        }
                        vel.x   *= Mathf.Clamp(owner.surfaceFriction * 2f, 0.0f, 1f);
                        @checked = true;
                    }
                    ++collideNum;
                    if (collideNum > BodyChunk.MaxRepeats)
                    {
                        Debug.Log("!!!!! " + owner + " emergency breakout of terrain check!");
                        @checked = true;
                    }
                }
            }
        }
        else
        {
            if (vel.y >= 0.0)
            {
                return;
            }
            int  y1       = owner.room.GetTilePosition(new Vector2(0.0f, pos.y - TerrainRad)).y;
            int  y2       = owner.room.GetTilePosition(new Vector2(0.0f, lastPos.y - TerrainRad)).y;
            int  x1       = owner.room.GetTilePosition(new Vector2((float)(pos.x - TerrainRad + 1.0), 0.0f)).x;
            int  x2       = owner.room.GetTilePosition(new Vector2((float)(pos.x + TerrainRad - 1.0), 0.0f)).x;
            bool @checked = false;
            for (int y = y2; y >= y1 && !@checked; --y)
            {
                for (int x = x1; x <= x2 && !@checked; ++x)
                {
                    if (SolidFloor(x, y) && !SolidFloor(x, y + 1) && (tilePosition.y > y || owner.room.GetTile(lastPos).Terrain == Room.Tile.TerrainType.Solid))
                    {
                        pos.y = (float)((y + 1.0) * 20.0) + TerrainRad;
                        if (vel.y < -PhysicalObject.impactTreshhold)
                        {
                            owner.TerrainImpact(index, new IntVector2(0, -1), Mathf.Abs(vel.y), lastContactPoint.y > -1);
                        }
                        contactPoint.y = -1;
                        vel.y          = Mathf.Abs(vel.y) * owner.bounce;
                        if (vel.y < owner.gravity || vel.y < 1.0 + 9.0 * (1.0 - owner.bounce))
                        {
                            vel.y = 0.0f;
                        }
                        vel.x   *= Mathf.Clamp(owner.surfaceFriction * 2f, 0.0f, 1f);
                        @checked = true;
                    }
                    ++collideNum;
                    if (collideNum > BodyChunk.MaxRepeats)
                    {
                        Debug.Log("!!!!! " + owner + " emergency breakout of terrain check!");
                        @checked = true;
                    }
                }
            }
        }
    }
Example #45
0
 public void DrawRay(IntVector2 start, IntVector2 direction)
 {
     // UNITTEST
     DrawRay(start.x, start.y, direction.x, direction.y);
 }
Example #46
0
    private void CheckAgainstSlopesVertically()
    {
        //获取当前Pos对应的Tile
        IntVector2 tilePos = owner.room.GetTilePosition(pos);
        IntVector2 intVec  = new IntVector2(0, 0);

        //获取当前Pos斜坡类型
        Room.SlopeDirection slopeDir = owner.room.IdentifySlope(pos);
        //如果当前Pos地形不是斜坡
        if (owner.room.GetTile(pos).Terrain != Room.Tile.TerrainType.Slope)
        {
            if (owner.room.IdentifySlope(tilePos.x - 1, tilePos.y) != Room.SlopeDirection.Broken && pos.x - slopeRad <= owner.room.MiddleOfTile(pos).x - 10.0)
            {
                slopeDir = owner.room.IdentifySlope(tilePos.x - 1, tilePos.y);
                intVec.x = -1;
            }
            else if (owner.room.IdentifySlope(tilePos.x + 1, tilePos.y) != Room.SlopeDirection.Broken && pos.x + slopeRad >= owner.room.MiddleOfTile(pos).x + 10.0)
            {
                slopeDir = owner.room.IdentifySlope(tilePos.x + 1, tilePos.y);
                intVec.x = 1;
            }
            else if (pos.y - (double)slopeRad < owner.room.MiddleOfTile(pos).y - 10.0)
            {
                if (owner.room.IdentifySlope(tilePos.x, tilePos.y - 1) != Room.SlopeDirection.Broken)
                {
                    slopeDir = owner.room.IdentifySlope(tilePos.x, tilePos.y - 1);
                    intVec.y = -1;
                }
            }
            else if (pos.y + (double)slopeRad > owner.room.MiddleOfTile(pos).y + 10.0 && owner.room.IdentifySlope(tilePos.x, tilePos.y + 1) != Room.SlopeDirection.Broken)
            {
                slopeDir = owner.room.IdentifySlope(tilePos.x, tilePos.y + 1);
                intVec.y = 1;
            }
        }
        if (slopeDir == Room.SlopeDirection.Broken)
        {
            return;
        }
        Vector2 tempVec = owner.room.MiddleOfTile(owner.room.GetTilePosition(pos) + intVec);
        int     xSign   = 0;
        float   dist;
        int     ySign;

        switch (slopeDir)
        {
        case Room.SlopeDirection.UpLeft:
            xSign = -1;
            dist  = (float)(pos.x - (tempVec.x - 10.0) + (tempVec.y - 10.0));
            ySign = -1;
            break;

        case Room.SlopeDirection.UpRight:
            xSign = 1;
            dist  = (float)(20.0 - (pos.x - (tempVec.x - 10.0)) + (tempVec.y - 10.0));
            ySign = -1;
            break;

        case Room.SlopeDirection.DownLeft:
            dist  = (float)(20.0 - (pos.x - (tempVec.x - 10.0)) + (tempVec.y - 10.0));
            ySign = 1;
            break;

        default:
            dist  = (float)(pos.x - (tempVec.x - 10.0) + (tempVec.y - 10.0));
            ySign = 1;
            break;
        }
        if (ySign == -1 && pos.y <= dist + (double)slopeRad + slopeRad)
        {
            pos.y          = dist + slopeRad + slopeRad;
            contactPoint.y = -1;
            vel.x         *= 1f - owner.surfaceFriction;
            vel.x         += (float)(Mathf.Abs(vel.y) * (double)Mathf.Clamp(0.5f - owner.surfaceFriction, 0.0f, 0.5f) * xSign * 0.2);
            vel.y          = 0.0f;
            onSlope        = xSign;
            slopeRad       = TerrainRad - 1f;
        }
        else
        {
            if (ySign != 1 || pos.y < dist - (double)slopeRad - slopeRad)
            {
                return;
            }
            pos.y          = dist - slopeRad - slopeRad;
            contactPoint.y = 1;
            vel.y          = 0.0f;
            vel.x         *= 1f - owner.surfaceFriction;
            slopeRad       = TerrainRad - 1f;
        }
    }
Example #47
0
 public bool IsLineUniform(IntVector2 point1, IntVector2 point2, bool ofValue)
 {
     // UNITTEST
     return(ofValue == this[point1] && IsLineUniform(point1, point2));
 }
Example #48
0
    /// <summary>
    /// Set up the lerp of the new animal into the board. If
    /// you want to set the animals coord to a fixed y append and extra
    /// int to the end of the parameters. If not let the game figure it out.
    /// </summary>
    private void DropAnimalIntoTable(int x, int y)
    {
        IntVector2 endPos = new IntVector2(x, y);

        animalSpawners[x].AddAnimalToSpawnQueue(endPos);
    }
Example #49
0
 public static bool PickVoxel(MyGame game, IntVector2 screenPos, MapControlPickMode pickMode, out IntVector3 pos, out Direction face)
 {
     return(MousePositionService.PickVoxel(game.Environment, game.Surfaces[0].Views[0], screenPos,
                                           game.ViewGridProvider.ViewGrid, pickMode, out pos, out face));
 }
Example #50
0
 /// <summary>
 /// Add a position to the list that needs to be checked for matches.
 /// </summary>
 /// <param name="pos"></param>
 public void AddPositionToCheck(IntVector2 pos)
 {
     positionsToCheck.Enqueue(pos);
 }
Example #51
0
        public static GameObject BuildPrefab(string name, string guid, string defaultSpritePath, IntVector2 hitboxOffset, IntVector2 hitBoxSize, bool HasAiShooter)
        {
            if (EnemyBuilder.Dictionary.ContainsKey(guid))
            {
                ETGModConsole.Log("EnemyBuilder: Yea something went wrong. Complain to Neighborino about it.");
                return(null);
            }
            var prefab = GameObject.Instantiate(behaviorSpeculatorPrefab);

            prefab.name = name;

            //setup misc components
            var sprite = SpriteBuilder.SpriteFromResource(defaultSpritePath, prefab).GetComponent <tk2dSprite>();

            sprite.SetUpSpeculativeRigidbody(hitboxOffset, hitBoxSize).CollideWithOthers = true;
            prefab.AddComponent <tk2dSpriteAnimator>();
            prefab.AddComponent <AIAnimator>();

            //setup knockback
            var knockback = prefab.AddComponent <KnockbackDoer>();

            knockback.weight = 1;


            //setup health haver
            var healthHaver = prefab.AddComponent <HealthHaver>();

            healthHaver.RegisterBodySprite(sprite);
            healthHaver.PreventAllDamage = false;
            healthHaver.SetHealthMaximum(15000);
            healthHaver.FullHeal();

            //setup AI Actor
            var aiActor = prefab.AddComponent <AIActor>();

            aiActor.State     = AIActor.ActorState.Normal;
            aiActor.EnemyGuid = guid;
            AIBulletBank aibulletBank = prefab.AddComponent <AIBulletBank>();

            //setup behavior speculator
            var bs = prefab.GetComponent <BehaviorSpeculator>();

            bs.MovementBehaviors = new List <MovementBehaviorBase>();
            bs.AttackBehaviors   = new List <AttackBehaviorBase>();
            bs.TargetBehaviors   = new List <TargetBehaviorBase>();
            bs.OverrideBehaviors = new List <OverrideBehaviorBase>();
            bs.OtherBehaviors    = new List <BehaviorBase>();

            if (HasAiShooter)
            {
                var actor = EnemyDatabase.GetOrLoadByGuid("01972dee89fc4404a5c408d50007dad5");
                behaviorSpeculatorPrefab = GameObject.Instantiate(actor.gameObject);
                foreach (Transform child in behaviorSpeculatorPrefab.transform)
                {
                    if (child != behaviorSpeculatorPrefab.transform)
                    {
                        GameObject.DestroyImmediate(child);
                    }
                }

                foreach (var comp in behaviorSpeculatorPrefab.GetComponents <Component>())
                {
                    if (comp.GetType() != typeof(BehaviorSpeculator))
                    {
                        GameObject.DestroyImmediate(comp);
                    }
                }

                GameObject.DontDestroyOnLoad(behaviorSpeculatorPrefab);
                FakePrefab.MarkAsFakePrefab(behaviorSpeculatorPrefab);
                behaviorSpeculatorPrefab.SetActive(false);
            }

            //Add to enemy database
            EnemyDatabaseEntry enemyDatabaseEntry = new EnemyDatabaseEntry()
            {
                myGuid          = guid,
                placeableWidth  = 2,
                placeableHeight = 2,
                isNormalEnemy   = true
            };

            EnemyDatabase.Instance.Entries.Add(enemyDatabaseEntry);
            EnemyBuilder.Dictionary.Add(guid, prefab);


            //finalize
            GameObject.DontDestroyOnLoad(prefab);
            FakePrefab.MarkAsFakePrefab(prefab);
            prefab.SetActive(false);

            return(prefab);
        }
Example #52
0
        // --------------------------------------------------------------------------------------------
        /// <summary>
        /// Finds the best path for a unit to a target coordinate using A*
        /// </summary>
        public bool TryGetBestPathForUnit(Unit unit, IntVector2 startCoord, IntVector2 targetCoord, int movementExhausted, out IntVector2[] bestPath)
        {
            bestPath = new IntVector2[0];
            if (movementExhausted >= unit.MoveRange)
            {
                // return empty array if we've already exahusted the list
                return(false);
            }

            // A* implementation for best path
            HashSet <IntVector2AsAStarNode> open   = new HashSet <IntVector2AsAStarNode>();
            HashSet <IntVector2AsAStarNode> closed = new HashSet <IntVector2AsAStarNode>();

            open.Add(new IntVector2AsAStarNode
            {
                coord    = startCoord,
                previous = null,
                f        = 0,
                g        = 0,
                h        = 0,
            });

            int moveRange = unit.MoveRange - movementExhausted;

            bool succeeded = false;

            while (open.Count > 0)
            {
                List <IntVector2AsAStarNode> openAsList = new List <IntVector2AsAStarNode>(open);
                // sort the open list ascending by f value
                openAsList.Sort((IntVector2AsAStarNode a, IntVector2AsAStarNode b) =>
                {
                    return(a.f.CompareTo(b.f));
                });

                // set the current node to the node with the least f
                IntVector2AsAStarNode currentNode = openAsList[0];

                closed.Add(openAsList[0]);
                open.Remove(currentNode);

                if (currentNode.coord.Equals(targetCoord)) // remember to use .Equals() instead of == becuase these are not the same object
                {
                    bestPath  = currentNode.ToPath();
                    succeeded = true;
                    break;
                }

                List <BoardTile> nextBoardTiles = new List <BoardTile>();
                BoardTile        northTile      = GetTile(currentNode.coord.x, currentNode.coord.y + 1);
                if (northTile != null)
                {
                    nextBoardTiles.Add(northTile);
                }
                BoardTile southTile = GetTile(currentNode.coord.x, currentNode.coord.y - 1);
                if (southTile != null)
                {
                    nextBoardTiles.Add(southTile);
                }
                BoardTile eastTile = GetTile(currentNode.coord.x + 1, currentNode.coord.y);
                if (eastTile != null)
                {
                    nextBoardTiles.Add(eastTile);
                }
                BoardTile westTile = GetTile(currentNode.coord.x - 1, currentNode.coord.y);
                if (westTile != null)
                {
                    nextBoardTiles.Add(westTile);
                }
                foreach (BoardTile boardTile in nextBoardTiles)
                {
                    // check if we've already visited this coord
                    bool isClosed = false;
                    foreach (IntVector2AsAStarNode closedNode in closed)
                    {
                        isClosed |= closedNode.coord.Equals(boardTile.Coord);
                    }
                    if (isClosed)
                    {
                        continue;
                    }

                    // create a new node to add to the open list
                    IntVector2AsAStarNode childNode = new IntVector2AsAStarNode();
                    childNode.coord    = boardTile.Coord;
                    childNode.previous = currentNode;
                    childNode.g        = currentNode.g + boardTile.GetMoveCostForUnit(unit);
                    childNode.h        = (boardTile.Coord - targetCoord).ManhattanDistance;
                    childNode.f        = childNode.g + childNode.h;

                    // we can't look at tiles that are beyond a unit's move range or that are occupied by some other unit
                    if (childNode.g > moveRange || (boardTile.Occupant != null && boardTile.Occupant != unit))
                    {
                        continue;
                    }

                    // check if we've visited this coord but now we have a better path to it
                    bool foundBetterPath = false;
                    bool haveVisited     = false;
                    foreach (IntVector2AsAStarNode openNode in open)
                    {
                        if (!openNode.coord.Equals(childNode.coord))
                        {
                            continue;
                        }

                        haveVisited = true;

                        if (openNode.f < childNode.f)
                        {
                            continue;
                        }

                        // we've found a better node!
                        openNode.g        = childNode.g;
                        openNode.h        = childNode.h;
                        openNode.f        = childNode.f;
                        openNode.previous = childNode.previous;
                        foundBetterPath   = true;
                    }

                    if (!haveVisited || !foundBetterPath)
                    {
                        open.Add(childNode);
                    }
                }
            }

            if (bestPath.Length == 0)
            {
                // if we haven't found a best path, then there's no way the unit could move to the target
                // instead, return the best path to the node closest to the target
                List <IntVector2AsAStarNode> toCullFromClosed = new List <IntVector2AsAStarNode>();
                foreach (IntVector2AsAStarNode closedNode in closed)
                {
                    if (closedNode.g != moveRange)
                    {
                        toCullFromClosed.Remove(closedNode);
                    }
                }
                foreach (IntVector2AsAStarNode toRemove in toCullFromClosed)
                {
                    closed.Remove(toRemove);
                }

                List <IntVector2AsAStarNode> closedAsList = new List <IntVector2AsAStarNode>(closed);
                closedAsList.Sort((IntVector2AsAStarNode a, IntVector2AsAStarNode b) =>
                {
                    return(a.f.CompareTo(b.f));
                });

                bestPath = closedAsList[0].ToPath();
            }

            return(succeeded);
        }
Example #53
0
 public PixelErrorData this[IntVector2 point]
 {
     get { return(pixelErrorDatas[point.X, point.Y]); }
     set { pixelErrorDatas[point.X, point.Y] = value; }
 }
Example #54
0
        // --------------------------------------------------------------------------------------------
        public BoardTile GetBoardTileAtPosition(Vector3 worldPosition)
        {
            IntVector2 coord = new IntVector2(Mathf.RoundToInt(worldPosition.x / BoardTileView.Size), Mathf.RoundToInt(worldPosition.z / BoardTileView.Size));

            return(GetTile(coord));
        }
Example #55
0
 public Bitmap(IntVector2 size, PixelFormat format)
 {
     nativeBitmap = EngineInstance.NativeEngine.CreateBitmap(size, format);
 }
Example #56
0
 public static Vector2 MapToWorldPosition(IntVector2 mapPosition)
 {
     return(new Vector2(mapPosition.X, mapPosition.Y));
 }
        ///maybe add some value proofing here (name != null, collider != IntVector2.Zero)
        public GameObject Build()
        {
            try
            {
                //Get texture and create sprite
                Texture2D tex    = ResourceExtractor.GetTextureFromResource(spritePath);
                var       shrine = ItemAPI.SpriteBuilder.SpriteFromResource(spritePath, null, false);

                //Add (hopefully) unique ID to shrine for tracking
                string ID = $"{modID}:{name}".ToLower().Replace(" ", "_");
                shrine.name = ID;

                //Position sprite
                var sprite = shrine.GetComponent <tk2dSprite>();
                sprite.IsPerpendicular = true;
                sprite.PlaceAtPositionByAnchor(offset, tk2dBaseSprite.Anchor.LowerCenter);

                //Add speech bubble origin
                var talkPoint = new GameObject("talkpoint").transform;
                talkPoint.position = shrine.transform.position + talkPointOffset;
                talkPoint.SetParent(shrine.transform);

                //Set up collider
                if (!usesCustomColliderOffsetAndSize)
                {
                    IntVector2 spriteDimensions = new IntVector2(tex.width, tex.height);
                    colliderOffset = new IntVector2(0, 0);
                    colliderSize   = new IntVector2(spriteDimensions.x, spriteDimensions.y / 2);
                }
                var body = ItemAPI.SpriteBuilder.SetUpSpeculativeRigidbody(sprite, colliderOffset, colliderSize);

                var data = shrine.AddComponent <CustomShrineController>();
                data.ID             = ID;
                data.roomStyles     = roomStyles;
                data.isBreachShrine = true;
                data.offset         = offset;
                data.pixelColliders = body.specRigidbody.PixelColliders;
                data.factory        = this;
                data.OnAccept       = OnAccept;
                data.OnDecline      = OnDecline;
                data.CanUse         = CanUse;

                IPlayerInteractable interactable;
                //Register as interactable
                if (interactableComponent != null)
                {
                    interactable = shrine.AddComponent(interactableComponent) as IPlayerInteractable;
                }
                else
                {
                    var simpInt = shrine.AddComponent <SimpleInteractable>();
                    simpInt.isToggle    = this.isToggle;
                    simpInt.OnAccept    = this.OnAccept;
                    simpInt.OnDecline   = this.OnDecline;
                    simpInt.CanUse      = CanUse;
                    simpInt.text        = this.text;
                    simpInt.acceptText  = this.acceptText;
                    simpInt.declineText = this.declineText;
                    simpInt.talkPoint   = talkPoint;
                    interactable        = simpInt as IPlayerInteractable;
                }


                var prefab = FakePrefab.Clone(shrine);
                prefab.GetComponent <CustomShrineController>().Copy(data);
                prefab.name = ID;
                if (isBreachShrine)
                {
                    if (!RoomHandler.unassignedInteractableObjects.Contains(interactable))
                    {
                        RoomHandler.unassignedInteractableObjects.Add(interactable);
                    }
                }
                else
                {
                    if (!room)
                    {
                        room = RoomFactory.CreateEmptyRoom();
                    }
                    RegisterShrineRoom(prefab, room, ID, offset);
                }


                builtShrines.Add(ID, prefab);
                Tools.Print("Added shrine: " + ID);
                return(shrine);
            }
            catch (Exception e)
            {
                Tools.PrintException(e);
                return(null);
            }
        }
 public void onMouseOverWithButtonDone(IntVector2 position)
 {
     doFloodFill(position);
 }
Example #59
0
        public static GameObject BuildPrefab(string name, string guid, string defaultSpritePath, IntVector2 hitboxOffset, IntVector2 hitBoxSize, bool HasAiShooter, bool UsesAttackGroup = false)
        {
            if (HasAiShooter)
            {
                var actor = EnemyDatabase.GetOrLoadByGuid("3cadf10c489b461f9fb8814abc1a09c1");
                behaviorSpeculatorPrefab = GameObject.Instantiate(actor.gameObject);
                foreach (Transform child in behaviorSpeculatorPrefab.transform)
                {
                    if (child != behaviorSpeculatorPrefab.transform)
                    {
                        GameObject.DestroyImmediate(child);
                    }
                }
                foreach (var comp in behaviorSpeculatorPrefab.GetComponents <Component>())
                {
                    if (comp.GetType() != typeof(BehaviorSpeculator))
                    {
                        GameObject.DestroyImmediate(comp);
                    }
                }
                GameObject.DontDestroyOnLoad(behaviorSpeculatorPrefab);
                FakePrefab.MarkAsFakePrefab(behaviorSpeculatorPrefab);
                behaviorSpeculatorPrefab.SetActive(false);
            }
            if (AdvEnemyBuilder.Dictionary.ContainsKey(guid))
            {
                ETGModConsole.Log("AdvEnemyBuilder: Yea something went wrong. Complain to Neighborino about it.");
                return(null);
            }
            var prefab = GameObject.Instantiate(behaviorSpeculatorPrefab);

            prefab.name = name;

            //setup misc components
            var sprite = SpriteBuilder.SpriteFromResource(defaultSpritePath, prefab).GetComponent <tk2dSprite>();

            sprite.SetUpSpeculativeRigidbody(hitboxOffset, hitBoxSize).CollideWithOthers = true;
            prefab.AddComponent <tk2dSpriteAnimator>();
            prefab.AddComponent <AIAnimator>();

            //setup knockback
            var knockback = prefab.AddComponent <KnockbackDoer>();

            knockback.weight = 1;

            //setup health haver
            var healthHaver = prefab.AddComponent <HealthHaver>();

            healthHaver.RegisterBodySprite(sprite);
            healthHaver.PreventAllDamage = false;
            healthHaver.SetHealthMaximum(15000);
            healthHaver.FullHeal();

            //setup AI Actor
            var aiActor = prefab.AddComponent <AIActor>();

            aiActor.State            = AIActor.ActorState.Normal;
            aiActor.EnemyGuid        = guid;
            aiActor.CanTargetPlayers = true;
            aiActor.HasShadow        = false;
            aiActor.specRigidbody.CollideWithOthers  = true;
            aiActor.specRigidbody.CollideWithTileMap = true;
            aiActor.specRigidbody.PixelColliders.Clear();
            aiActor.specRigidbody.PixelColliders.Add(new PixelCollider

            {
                ColliderGenerationMode = PixelCollider.PixelColliderGeneration.Manual,
                CollisionLayer         = CollisionLayer.EnemyCollider,
                IsTrigger = false,
                BagleUseFirstFrameOnly = false,
                SpecifyBagelFrame      = string.Empty,
                BagelColliderNumber    = 0,
                ManualOffsetX          = 0,
                ManualOffsetY          = 0,
                ManualWidth            = 15,
                ManualHeight           = 17,
                ManualDiameter         = 0,
                ManualLeftX            = 0,
                ManualLeftY            = 0,
                ManualRightX           = 0,
                ManualRightY           = 0
            });
            aiActor.specRigidbody.PixelColliders.Add(new PixelCollider
            {
                ColliderGenerationMode = PixelCollider.PixelColliderGeneration.Manual,
                CollisionLayer         = CollisionLayer.EnemyHitBox,
                IsTrigger = false,
                BagleUseFirstFrameOnly = false,
                SpecifyBagelFrame      = string.Empty,
                BagelColliderNumber    = 0,
                ManualOffsetX          = 0,
                ManualOffsetY          = 0,
                ManualWidth            = 15,
                ManualHeight           = 17,
                ManualDiameter         = 0,
                ManualLeftX            = 0,
                ManualLeftY            = 0,
                ManualRightX           = 0,
                ManualRightY           = 0,
            });
            aiActor.CorpseObject        = EnemyDatabase.GetOrLoadByGuid("01972dee89fc4404a5c408d50007dad5").CorpseObject;
            aiActor.PreventBlackPhantom = false;
            //setup behavior speculator
            var bs = prefab.GetComponent <BehaviorSpeculator>();

            bs.MovementBehaviors = new List <MovementBehaviorBase>();
            bs.TargetBehaviors   = new List <TargetBehaviorBase>();
            bs.OverrideBehaviors = new List <OverrideBehaviorBase>();
            bs.OtherBehaviors    = new List <BehaviorBase>();
            if (UsesAttackGroup)
            {
                bs.AttackBehaviorGroup.AttackBehaviors = new List <AttackBehaviorGroup.AttackGroupItem>();
            }
            else
            {
                bs.AttackBehaviors = new List <AttackBehaviorBase>();
            }
            //allows enemies to be tinted
            prefab.AddComponent <Tint>();
            prefab.AddComponent <EngageLate>();
            prefab.AddComponent <AIBulletBank>();
            //Add to enemy database
            EnemyDatabaseEntry enemyDatabaseEntry = new EnemyDatabaseEntry()
            {
                myGuid          = guid,
                placeableWidth  = 2,
                placeableHeight = 2,
                isNormalEnemy   = true,
            };

            EnemyDatabase.Instance.Entries.Add(enemyDatabaseEntry);
            AdvEnemyBuilder.Dictionary.Add(guid, prefab);
            //finalize
            GameObject.DontDestroyOnLoad(prefab);
            FakePrefab.MarkAsFakePrefab(prefab);
            prefab.SetActive(false);

            return(prefab);
        }
Example #60
0
    //检测水平碰撞:计算速度、位置和ContactPoint
    private void CheckHorizontalCollision()
    {
        contactPoint.x = 0;
        //获取上一帧TilePos
        IntVector2 tileLastPos = owner.room.GetTilePosition(lastPos);
        int        collideNum  = 0;

        //如果水平速度大于0,从左向右移动
        if (vel.x > 0)
        {
            //从左向右,从下到下遍历检测
            int  x1        = owner.room.GetTilePosition(new Vector2((pos.x + TerrainRad), 0.0f)).x;
            int  x2        = owner.room.GetTilePosition(new Vector2(lastPos.x + TerrainRad, 0.0f)).x;
            int  y1        = owner.room.GetTilePosition(new Vector2(0.0f, (float)(pos.y + TerrainRad - 1.0))).y;
            int  y2        = owner.room.GetTilePosition(new Vector2(0.0f, (float)(pos.y - TerrainRad + 1.0))).y;
            bool contacted = false;
            for (int x = x2; x <= x1 && !contacted; ++x)
            {
                for (int y = y2; y <= y1 && !contacted; ++y)
                {
                    //检测是否满足条件
                    if (owner.room.GetTile(x, y).Terrain == Room.Tile.TerrainType.Solid && owner.room.GetTile(x - 1, y).Terrain != Room.Tile.TerrainType.Solid &&
                        (tileLastPos.x < x || owner.room.GetTile(lastPos).Terrain == Room.Tile.TerrainType.Solid))
                    {
                        pos.x = x * 20f - TerrainRad;
                        //产生地形碰撞影响
                        if (vel.x > PhysicalObject.impactTreshhold)
                        {
                            owner.TerrainImpact(index, new IntVector2(1, 0), Mathf.Abs(vel.x), lastContactPoint.x < 1);
                        }
                        contactPoint.x = 1;
                        //水平速度计算反弹,小于阈值则为0
                        vel.x = -Mathf.Abs(vel.x) * owner.bounce;
                        if (Mathf.Abs(vel.x) < 1.0 + 9.0 * (1.0 - owner.bounce))
                        {
                            vel.x = 0.0f;
                        }
                        //垂直速度计算计算表面摩擦力
                        vel.y *= Mathf.Clamp(owner.surfaceFriction * 2f, 0.0f, 1f);
                        //设置碰撞标志位
                        contacted = true;
                    }
                    //碰撞超限计数
                    ++collideNum;
                    if (collideNum > BodyChunk.MaxRepeats)
                    {
                        Debug.Log("!!!!! " + owner + " emergency breakout of terrain check!");
                        contacted = true;
                    }
                }
            }
        }
        //如果水平速度小于0,从右向左移动
        else if (vel.x < 0.0)
        {
            //从右向左,从下到上遍历
            int  x1       = owner.room.GetTilePosition(new Vector2(pos.x - TerrainRad, 0.0f)).x;
            int  x2       = owner.room.GetTilePosition(new Vector2(lastPos.x - TerrainRad, 0.0f)).x;
            int  y1       = owner.room.GetTilePosition(new Vector2(0.0f, (float)(pos.y + TerrainRad - 1.0))).y;
            int  y2       = owner.room.GetTilePosition(new Vector2(0.0f, (float)(pos.y - TerrainRad + 1.0))).y;
            bool @checked = false;
            for (int x = x2; x >= x1 && !@checked; --x)
            {
                for (int y = y2; y <= y1 && !@checked; ++y)
                {
                    if (owner.room.GetTile(x, y).Terrain == Room.Tile.TerrainType.Solid && owner.room.GetTile(x + 1, y).Terrain != Room.Tile.TerrainType.Solid &&
                        (tileLastPos.x > x || owner.room.GetTile(lastPos).Terrain == Room.Tile.TerrainType.Solid))
                    {
                        //产生地形碰撞效果
                        pos.x = (float)((x + 1.0) * 20.0) + TerrainRad;
                        if (vel.x < -(double)PhysicalObject.impactTreshhold)
                        {
                            owner.TerrainImpact(index, new IntVector2(-1, 0), Mathf.Abs(vel.x), lastContactPoint.x > -1);
                        }
                        contactPoint.x = -1;
                        //根据弹力计算水平速度,小于阈值则为0
                        vel.x = Mathf.Abs(vel.x) * owner.bounce;
                        if (Mathf.Abs(vel.x) < 1.0 + 9.0 * (1.0 - owner.bounce))
                        {
                            vel.x = 0.0f;
                        }
                        //根据表面摩擦力修改垂直速度
                        vel.y   *= Mathf.Clamp(owner.surfaceFriction * 2f, 0.0f, 1f);
                        @checked = true;
                    }
                    //碰撞计数检测
                    ++collideNum;
                    if (collideNum > BodyChunk.MaxRepeats)
                    {
                        Debug.Log("!!!!! " + owner + " emergency breakout of terrain check!");
                        @checked = true;
                    }
                }
            }
        }
    }