简体   繁体   中英

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?

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
    }
}

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.

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