简体   繁体   English

将角色移动到触摸的位置2D(无RigidBody和动画动作)UNITY

[英]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. 您可以使用Vector2.Lerp()在两点之间平滑移动。

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 : 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. 这将方向添加到当前位置。使用增量时间缩放运动,您可以通过将所有速度乘以某个标量值(即任何float值)来提高或降低速度。 note that it's best to normalize once rather than every frame but this is the general idea. 请注意,最好是normalize一次,而不是每帧normalize ,但这是一般的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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