我正在尝试在Unity中创建一个2D传送门,不仅可以将玩家传送到另一个传送门游戏对象中,还可以保持玩家通过传送门后的位置、移动方向和速度。
我并不是个艺术家,但举个例子:
玩家是一个在区域内弹跳的球,当他穿过门时,他的速度保持不变,并且他进入了传送门的中心。
例如在这里:
如果玩家进入传送门的下半部分,他将从传送门的下半部分出来。
当这个系统工作时,它非常好用!然而,它只有50%的时间能正常工作,这50%的问题可能会有很多不同的问题,有时球会无法传送。有时球击中第一个传送门,传送到第二个传送门,然后返回到第一个传送门,一直反复进行。而且它似乎也是随机出现这些问题。
这是我的脚本:
我并不是个艺术家,但举个例子:
![enter image description here](https://istack.dev59.com/Dw45O.webp)
例如在这里:
![enter image description here](https://istack.dev59.com/2Znri.webp)
当这个系统工作时,它非常好用!然而,它只有50%的时间能正常工作,这50%的问题可能会有很多不同的问题,有时球会无法传送。有时球击中第一个传送门,传送到第二个传送门,然后返回到第一个传送门,一直反复进行。而且它似乎也是随机出现这些问题。
这是我的脚本:
public GameObject otherPortal;
public PortalController otherPortalScript;
private BallController ballController;
public float waitTime = 0.5f;
[HideInInspector]
public bool teleporting;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Ball")
{
ballController = other.GetComponent<BallController>();
if(!teleporting)
{
var offset = other.transform.position - transform.position;
offset.x = 0;
other.transform.position = otherPortal.transform.position + offset;
otherPortalScript.teleporting = true;
teleporting = true;
StartCoroutine("Teleport");
}
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.tag == "Ball")
{
teleporting = false;
otherPortalScript.teleporting = false;
}
}
IEnumerator Teleport()
{
yield return new WaitForSeconds(waitTime);
teleporting = false;
otherPortalScript.teleporting = false;
ballController.teleporting = false;
}
}
该脚本附加在两个门户上,它们都是同一对象的预制体。我在编辑器中设置了“otherPortal”、“otherPortalScript”和“waitTime”。其中,“waitTime”是我事后添加的,用于解决另一个问题,即有时“传送”永远不会被设置为false。我认为这个问题的原因与那个问题相同,因此“waitTime”只是对更大问题的临时解决方案。此外,每当Portal脚本更改“ballController”中的变量(例如“ballController.teleporting=false;”)时,仅因为球正在向得分系统添加或删除点数,它根本不会影响球的运动。