Vladimir Arevshatyan
Vladimir Arevshatyan

Reputation: 673

Move Character to touched Position 2D (Without RigidBody and Animated Movement) UNITY

Good day. I am trying to achieve simple thing but nothing just works....

The desired output:

• Player touches a place in my world

• Character starting to smoothly move with walking animation towards that location

The actual result:

• Player touches a place in my world

• Character just jumps into the final point, no smooth movement nothing

Things tried:

• Vector2 finalPosition = Camera.main.ScreenToWorldPoint(position); 
transform.position = finalPosition;

In this scenario the character just jumps into the final point

• Vector2 finalPosition = Camera.main.ScreenToWorldPoint(position); 
transform.Translate(finalPosition);

In this case character just dissappears from the screen.

Any solution?

Upvotes: 0

Views: 528

Answers (2)

ryeMoss
ryeMoss

Reputation: 4343

You can use Vector2.Lerp() to move smoothly between two points.

Some pseudo code:

bool move;
float t;
Update()
{
    if () // insert condition to begin movement
    {
        move = true;
        t = 0; // reset timer
        startPos = transform.position; // store current position for lerp
        finalPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
    if (move)
        MovePlayer();
}

void MovePlayer()
{
    t += Time.deltaTime / 3f; // 3 is seconds to take to move from start to end
    transform.position = Vector2.Lerp(startPos, finalPosition, t);
    if (t > 3)
    {
        move = false; // exit function
    }
}

Upvotes: 2

mad.meesh
mad.meesh

Reputation: 2766

in update:

transform.position += (final_pos - transform.position).normalized * Time.deltaTime;

this is adding to your current position the direction ... use delta time to scale the movement and you can increase or decrease the speed by multiplying it all by some scalar value, ie any float value. note that it’s best to normalize once rather than every frame but this is the general idea.

Upvotes: 0

Related Questions