How to make the player move on "slide" in Unity?

Asked

Viewed 160 times

4

I’m new to Unity and I’m doing the tutorial Roguelike 2D. By default the player will move, theoretically, using one of those coordinates per shift y+1, x+1, y-1, x-1, or just one block at a time. And I want to know how I can get the player to move freely until he crashes into a wall or any other Champion from the scene.

Like the game 2048, where the squares advance in a straight line and only stop when they collide on the wall or other pieces.

Below is the part of the code that declares the movement. What changes must I make to leave the movement as I quoted above?

//Co-routine for moving units from one space to next, takes a parameter end to specify where to move to.
protected IEnumerator SmoothMovement (Vector3 end)
{
    //Calculate the remaining distance to move based on the square magnitude of the difference between currente position and end parameter.
    //Square magnitude is used instead of magnitude because it's computationally cheaper.
    float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
}

//While that distance is greater than a very small amount (Epsilon, almost zero):
while(sqrRemainingDistance > float.Epsilon)
{
    //Find a new position proportionally closer to the end, based on the moveTime
    Vector3 newPosition = Vector3.MoveTowards(rb2d.position, end, inverseMoveTime * Time.deltaTime);

    //Call MovePosition on attached Rigidbody2D and move it to the calculated position.
    rb2d.MovePosition (newPosition);

    //Recalculate the remaining distance after moving.
    sqrRemainingDistance = (transform.position - end).sqrMagnitude;

    //Return and loop until sqrRemainingDistance is close enough to zero to end the function
    yield return null;
}
  • If easy to understand the question, this code has been provided by Unity and can be downloaded here.

  • If it is not possible or impossible to change the code provided, also accepted in a code isolated from the game, since my goal is to understand this mechanics.

  • You can use the Oncollisionenter function to check for collisions. With do while you make the object move until the collision is detected. Take a look here: https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.