【问题标题】:Unity transform.position not working properlyunity transform.position 无法正常工作
【发布时间】:2018-08-27 00:58:27
【问题描述】:

好的,我发现了我遇到的问题。为门户返回的位置在门户内部,当一个对象在另一个对象内部时它会出现故障,所以我只是在门户中添加了一个空对象,我希望他们退出并让程序指向它。

我正在 Unity 中开发一个小“游戏”,有四个标记为 PortalMain1PortalMain2PortalMain3PortalMain4 的门户,目标是让玩家能够运行进入每个门户上的对撞机并随机传送到其他门户之一。

我在处理触发事件的播放器模型上有这段代码:

private void OnTriggerEnter(Collider other)
{
    int PortalDestination = Random.Range(1, 4);  ///Portals index at 1 because Unity
    string Portal = "PortalMain" + PortalDestination;
    Debug.Log(Portal);
    transform.position = GameObject.Find(Portal).transform.position;
}

游戏中实际发生的情况是,当玩家与传送门上的盒子碰撞器发生碰撞时,游戏会正确地从 1-4 中选择一个传送门(尽管它似乎永远不会选择你触摸的那个整洁的)并传送你在那里。

除了你被传送到传送门附近而不是在传送门顶部之外,如果传送确实有效,它似乎只工作了大约 1/4 的时间。

这是带有基础的场景层次结构图:

这是场景与建筑物的层次结构图:

这是带有门户的场景层次结构图:

编辑 #1:我重新设计了使用 Rigidbody 的方法,但问题仍然存在。

private void OnTriggerEnter(Collider other)
{
    int PortalDestination = Random.Range(1, 4);  ///Portals index at 1 because Unity
    string Portal = "PortalMain" + PortalDestination;
    Debug.Log(Portal);
    GetComponent<Rigidbody>().isKinematic = true;
    GetComponent<Rigidbody>().position = GameObject.Find(Portal).transform.position;
    GetComponent<Rigidbody>().isKinematic = false;
} 

这里是 Github 链接 > https://github.com/LvInSaNevL/Bamboozle

【问题讨论】:

  • 就像现在很多次说的那样,在处理物理时不要使用翻译。使用Rigidbody 使物理引擎功能受益
  • @m.rogalski 我发现的唯一方法是用矢量物理移动刚体。我想要更多的“即时”传送。那可能吗?我根据文档尝试了GetComponent&lt;Rigidbody&gt;().position = GameObject.Find(Portal).transform.position;,但只有大约 25% 的时间有效。
  • 您能否发布您的层次结构的图片,特别是门户对象的图片。此外,场景视图中的门户图片(选中时)也会有所帮助。对于即时传送,我发现使用 transform.position 可以正常工作!
  • 此外,您的最新编辑不会改变任何内容。 ().position 与 .position 完全相同。
  • @Immorality 现在添加了一张图片。

标签: c# unity3d


【解决方案1】:

首先,将 OnTriggerEnter 附加到 TRIGGER,而不是播放器。

其次,将此脚本附加到门户并明确设置 spawnPoint。

之后,您可以将该传送门复制到任何您想要的位置,它会将自己添加到可能的传送门列表中以供玩家退出。

public class Portal : MonoBehaviour {
    public static List<Portal> portals {get; protected set;}
    public Transform spawnPoint; // Set it in the editor
    protected bool ignoreNextTouches = false;

    private void Start () {
        if (portals == null)
            portals = new List<Portal>();
        portals.Add (this);
    }
    private void OnTriggerEnter (Collider other) {
        if (!other.gameObject.tag.Equals ("Player"))
            return;
        if (ignoreNextTouches) {
            ignoreNextTouches = false;
            return;
        }
        Portal random = GetRandomPortal (this);
        random.ignoreNextTouches = true;
        other.transform.position = random.spawnPoint.position;
    }
    private static Portal GetRandomPortal (Portal exceptThis) {
        Portal  p = exceptThis;
        while (p == exceptThis)
            p = portals[Random.Range(0,portals.Length)];
        return p;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    相关资源
    最近更新 更多