John Doe
John Doe

Reputation: 601

Unity2D Move Tile Up and Down with transiton

I want to create a functionality similar to Mario tiles. So basically the Player would jump, hit the tile with the head, collision happens and I want the tile to smoothly move up and the back down to it's initial position.

Player has player tag. Tiles are on the Tile layer. which is being held in the layerMask variable

 private void OnCollisionEnter2D(Collision2D collision)
{
    // print("Colision layer: " + collision.collider.gameObject.layer);

    if(collision.collider.gameObject.layer == Mathf.Log(layerMask.value, 2))
    {
        GameObject Tile = collision.gameObject;
        Vector3 initialPosition = new Vector3(Tile.transform.position.x, Tile.transform.position.y, Tile.transform.position.z);
        print("initial pos: " + initialPosition);

        Tile.transform.Translate(Vector3.up * 15f * Time.deltaTime, Space.World);
        Vector3 newPosition = new Vector3(Tile.transform.position.x, Tile.transform.position.y, Tile.transform.position.z);
        print("new pos: " + newPosition);

        Tile.transform.position = Vector3.Lerp(newPosition, initialPosition, 50f * Time.deltaTime);

        // Tile.transform.Translate(Vector3.down * 15f * Time.deltaTime, Space.World);
    }
}

Basically it moves the tile up but it doesn't move it back down, the last line of code that is commented out does work but there is no transition so it happens instantly, and the Lerp doesn't do anything.

Upvotes: 0

Views: 310

Answers (1)

Leoverload
Leoverload

Reputation: 1238

You should use animation and with the record button change the transform.position of the tile and keeping the collider down (if that is what you need). In this way when the player hits the tile you should try to do something like this

void OnCollisionEnter2D(Collision2D collision)
{  if(collision.gameObject.layer == Tile) // I'm not sure this is the layer
          { animator.setTrigger(MovingTileUpAndDown);
          }
}

In the animator, you should put a transition from idle condition (the tile staying still) and the bonk transition with the MovingTileUpAndDown parameter, then you can put a transition back to the idle or anything you want without the parameter and a HasExitTime set to the duration of the animation of tile moving.

Upvotes: 1

Related Questions