简体   繁体   中英

Grid Based Movement for a Block Sliding Game

https://www.gamesmen.com.au/rush-hour-traffic-jam-logic-board-game

there was this game that i try to recreate it in Unity. i've try to make the sliding blocks script, and it works. let's just say that i make it with a Grid, yes, that Grid where i can put tiles on it. so how can i make the blocks snaps on the Grid? especially if the block is more than 1 tile long?

they way how it works is that i use OnMouseDown at the moment because i've planned to built it on Android but now the problem is that i don't know how to make these blocks snap to grid with OnMouseUp.

so far here's the Code for the Blocks

private void GrabABlock()
    {
        if (Input.GetMouseButton(0)) {
            Debug.Log("blockGrab"); 
            mousePos = Input.mousePosition;
            mousePos = Camera.main.ScreenToWorldPoint(mousePos);
            BlockPosX = mousePos.x - this.transform.position.x;
            BlockPosY = mousePos.y - this.transform.position.y;
            Grabbed = true;
            if (Grabbed == true) {
                mousePos = Input.mousePosition;
                mousePos = Camera.main.ScreenToWorldPoint(mousePos);
                switch (BlockDirection)
                {
                    case BlockShape.Horizontal:
                        HorizontalMovement();
                        break;
                    case BlockShape.Vertical:
                        VerticalMovement();
                        break;
                    case BlockShape.Square:
                        OctaMovement();
                        break;
                }
            }
        }

    }

    private void LateUpdate() // Snap to Grid
    {
        mousePos.x = Mathf.Floor(gameObject.transform.position.x / 1f) * 1f;
        mousePos.y = Mathf.Floor(gameObject.transform.position.y / 1f) * 1f;
        pivot.transform.position = mousePos;
    }

my expectation is that the block's pivot detects the each tiles of the grid, and snaps into it onMouseUp

You can add a trigger collider to the block. Then for every position in the grid add an empty GameObject, let's call it SnapLocation. Then OnMouseButtonUp you can move the blocks position to the SnapLocation's position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM