c# - 移动游戏对象的最佳方式是什么,而不是传送它?

标签 c# unity3d

我试图将游戏对象 pokemon 从屏幕中心平滑地移动到屏幕左侧(仅沿水平轴)。但是,它会立即传送。

代码的作用 = 在无限循环中从一个 sprite 变为另一个 sprite。当它变成另一个 Sprite 时,它也会改变它的比例。

我想要代码做什么 = 在更改为不同的 Sprite 之前,在水平轴上向左移动。

我尝试过线性插值 (lerp) 和 transform.translate。

public class Transitions : MonoBehaviour
{

    public Sprite Pokemon_0; // VARIABLES FOR SPRITES (Pokemons/ game objects) 
    public Sprite Pokemon_1;

    float timer = 1f; // CHANGING SPRITES VALUES (delays)
    float delay = 5f;

    Vector2 temp;     //CHANGING POSITION VARIABLES
    Vector2 tempPos;
    Vector2 finalPosition;


    void Start()
    {
        this.gameObject.GetComponent<SpriteRenderer>().sprite = Pokemon_0;
    }

    void Update()
    {
        timer -= Time.deltaTime;
    if (timer <= 0)
    {
        if (this.gameObject.GetComponent<SpriteRenderer>().sprite == Pokemon_0) // TO CHANGE FROM POKEMON 1 TO POKEMON 2 
        {
            this.gameObject.GetComponent<SpriteRenderer>().sprite = Pokemon_1;

            temp = transform.localScale;  // TO SET THE SCALE WHEN EACH POKEMON CHANGES (works)
            temp.x = -380;
            temp.y = 350;
            transform.localScale = temp;
            timer = delay;

            finalPosition = new Vector2(167, -107);
            transform.position = Vector3.Lerp(transform.position, finalPosition, 1f * Time.deltaTime);

            //tempPos = transform.position; // Tried and tested method. Doesn't work. 
            //tempPos.x = 1f;
            //transform.position = tempPos;



            return;

        }
        if (this.gameObject.GetComponent<SpriteRenderer>().sprite == Pokemon_1) // TO CHANGE BACK FROM POKEMON 2 TO POKEMON 1
        {
            this.gameObject.GetComponent<SpriteRenderer>().sprite = Pokemon_0;
            timer = delay;
            return;

        }

    }

在执行时,这段代码确实改变了 pokemon 并改变了规模。但是,立场保持不变。

我是新人,所以我一直在尝试我们的不同建议,谢谢。

最佳答案

最好使用补间引擎,例如http://dotween.demigiant.com/ .

如果你安装了 Dotween 那么你可以简单地使用

transform.DOMove(new vector3(1 ,0 , 1) , duration);

您还可以为补间设置缓动。或使用 Oncomplete 函数;

transform.DOMove(new vector3(1 ,0 , 1) , duration)
    .SetEase(Ease.OutCubic)
    .OnCompelete(() => { shouldClose = true; }); 

您还可以为您的补间设置循环 .SetLoops(-1)

关于c# - 移动游戏对象的最佳方式是什么,而不是传送它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56836806/

相关文章:

c# - Linq参数错误

android - Google Play 商店中不支持的 API 警告

c# - 为什么 TextMeshPro 在设置文本后不更新 textBounds?

unity3d - 如何将统一预制件移动到鼠标点击位置?

c# - 添加参数的问题

c# - 将 C# lambda 表达式移植到 PHP

c# - Unity 最小化电池使用

C# 字符串不支持西里尔字符

c# - 从两个大整数中获取精确的百分比

c# - 为什么标准 C# 事件调用模式是线程安全的,没有内存屏障或缓存失效?类似的代码呢?