程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了将对象 A 移动到其他 X 对象的随机位置大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决将对象 A 移动到其他 X 对象的随机位置?

开发过程中遇到将对象 A 移动到其他 X 对象的随机位置的问题如何解决?下面主要结合日常开发的经验,给出你关于将对象 A 移动到其他 X 对象的随机位置的解决方法建议,希望对你解决将对象 A 移动到其他 X 对象的随机位置有所启发或帮助;

这就是我想要做的,这应该像提示按钮一样工作。当单击放大镜对象 A 时,它应该移动到 X 个隐藏对象之一的随机位置,然后在 3 秒后返回。这是我尝试过的:

public class Lupica1 : MonoBehavIoUr
{
    //List of positions
    public transform[] positions;
    //Just holds the index of picked random position
    privatE int br;
    private transform target;
    private float speed = 1f;
    private Vector3 OrgPos;
    private float timer = 3f;


    // Start is called before the first frame update
    voID Start()
    {
        //Stores the original of position of ObjectA(loupE)
        OrgPos = gameObject.transform.position;
        //Index of random position is picked here
        br = Random.Range(0,positions.Length);
        //And stored into target
        target = positions[br];
    }

    // update is called once per frame
    voID update()
    {
        //Timer 
        timer -= Time.deltaTime;
    }
    
    //This is the method to assign to onClick function in Inspector 
    public voID Lupica()
    {   
        
        transform.position = Vector2.MovetoWARDs(gameObject.transform.position,target.transform.position,speed * Time.deltaTimE);
        //When timer reaches 0,return object A(loupE) to original position
        if (timer < 0)
        {
            gameObject.transform.position = OrgPos;
        }

    }
}

解决方法

我会在 Lupica 中启动一个协程并在那里处理所有的移动和计时器逻辑:

//List of positions
public Transform[] positions;
//Just holds the index of picked random position
privatE int br;
private Transform target;
private float speed = 1f;
private Vector3 OrgPos;
private float timer = 3f;
private CoroutIne lupicaCoroutIne = null;


// Start is called before the first frame update
void Start()
{
    //Stores the original of position of ObjectA(loupE)
    OrgPos = transform.position;
    //Index of random position is picked here
    br = Random.Range(0,positions.Length);
    //And stored into target
    target = positions[br];
}

public void Lupica()
{   
    if (lupicaCoroutIne != null) return;

    lupicaCoroutIne = StartCoroutIne(HandleLoupe());
}

private IEnumerator HandleLoupe()
{
    while (transform.position != target.position)
    {
        transform.position = Vector2.MoveToWARDs(transform.position,target.position,speed * Time.deltaTimE);
        yield return null;
    }

    yield return new WaitForSeconds(timer);

    transform.position = OrgPos;
    lupicaCoroutIne = null;
}

大佬总结

以上是大佬教程为你收集整理的将对象 A 移动到其他 X 对象的随机位置全部内容,希望文章能够帮你解决将对象 A 移动到其他 X 对象的随机位置所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: