进入碰撞后将游戏对象移动到另一个对象。统一 C#

Move a gameObject to another object after entering collision. Unity C#

我是 C# 和 Unity3D 的初学者,所以我的问题可能很奇怪,但请不要评判我。我很难弄清楚哪里出了问题以及为什么它不起作用。

我游戏里有个鬼,我一靠近它,它就得躲开我。我在幽灵周围创建了碰撞并向其添加了这个脚本:

   using UnityEngine;
   using System.Collections;

public class MaidTriggeris : MonoBehaviour {
    public GameObject light;
    public GameObject sing;
    public GameObject ghost;
    public float speed;
    public GameObject target;


    // Use this for initialization
    void Start () {
        light.SetActive(true);
    }

    // Update is called once per frame
    void OnTriggerEnter(){
        light.SetActive (false);
        DestroyObject (sing);
        float step = speed * Time.deltaTime;
        ghost.transform.position = Vector3.MoveTowards(ghost.transform.position, target.transform.position, step);
    }
}

无论如何,当我在碰撞盒中移动时,一切正常(它会破坏游戏对象 "sing" 并将光照设置为 "false"),但是它永远不会将游戏对象的 "ghost" 位置移动到另一个对象 "target"。我的速度设置为5,所有对象都分配好了。

嗯,您只执行了一次 Vector3.MoveTowards,所以您的 ghost 只移动了一步。您需要在 Update 中借助 Coroutine 中某些 condition.Like、

中的任何标志执行此操作
using UnityEngine;
using System.Collections;

public class MaidTriggeris : MonoBehaviour {
    public GameObject light;
    public GameObject sing;
    public GameObject ghost;
    public float speed;
    public GameObject target;


    // Use this for initialization
    void Start () {
        light.SetActive(true);
    }

    // Update is called once per frame
    void OnTriggerEnter(){
        light.SetActive (false);
        DestroyObject (sing);
        StartCoroutine("MoveGhost");            
    }

    IEnumerator MoveGhost(){
        while(Vector3.Distance(ghost.transform.position, target.transform.position) > 1.0f) // Change this value accordingly 
            {
                float step = speed * Time.deltaTime;
                ghost.transform.position = Vector3.MoveTowards(ghost.transform.position, target.transform.position, step);
                yield return new WaitForEndOfFrame();
            }
    }
}

以上代码片段尚未经过测试。因此,如果需要,请进行一些调整。