我正在尝试创建门户,但我不明白为什么要使用该代码:
playerControl.transform.position = new Vector3(destination.position.x, destination.position.y, destination.position.z);
仅适用于某些位置和角度。
这是代码的设置
public class Teleport : Interactable
{
public Transform destination;
private GameObject playerControl;
private PortalAnimationController portalController;
// Start is called before the first frame update
void Start()
{//get the player information
playerControl = PlayerManager.instance.player;
portalController = PortalAnimationController.instance;
}
public override void interact()
{
//base.interact();
//run the teleport method
StartCoroutine("teleport");
//Debug.Log(playerControl.GetInstanceID());
}
/*
1. trigger the panel
2. stop the time
3. teleport the player
*/
private IEnumerator teleport()
{
Time.timeScale = 0f;//stop the time
portalController.fadeOut();
//wait for seconds realtime can avoid stopping when timescale is 0
yield return new WaitForSecondsRealtime(portalController.duration);//wait for the transition
Debug.Log("wait finish");
//after the the wait
Debug.Log(playerControl.transform.position + "before");
playerControl.transform.position = new Vector3(destination.position.x, destination.position.y, destination.position.z);
if(playerControl.transform.position!= destination.position)
{
Debug.Log(playerControl.transform.position);
}
else
{
Debug.Log(playerControl.transform.position+"pass");
}
portalController.fadeOut();
Time.timeScale = 1f;
}
}
可交互的类仅包含一个“公共虚拟虚空interact()”方法,用于传送以覆盖它。触发方法是通过以下代码:
void Update()
{
RaycastHit hit;
if (Input.GetButtonDown("Interact"))
{
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, interactableRange))
{
Interactable interactable = hit.collider.GetComponent<Interactable>();
//if the player is looking at the interactable
//Debug.Log("Interact with " + hit.transform.name);
if (interactable != null)
{
//highlight the object
interactable.interact();
//if player press the interact key, then pick it up
Debug.Log("Interact with " + hit.transform.name);
}
}
}
}
[按下e键时它发出光线,然后击中对撞机框以检索可交互组件并立即调用interact()。
我已经对其进行了数百次测试,只有3个结果。1.玩家实际上被传送了。(成功)2.播放器以1帧的速度闪烁到目的地,然后又回到原来的位置。(失败)3.播放器完全不移动。(失败)
感谢所有尝试提供帮助的人。我终于找出问题所在。不能传送的原因是我的播放器有一个名为“角色控制器”的组件,该组件将覆盖播放器的更改位置,并将其发送回原处。因此,在播放器回到原始位置之前,我会将其传送到一帧的正确位置。
我解决它的方法很简单:
characterController.enable = false;
playerControl.transform.position = new Vector3(destination.position.x, destination.position.y, destination.position.z);
characterController.enable = true;
这样将不会调用字符控制器,因此传送将正常运行。
同样,感谢所有尝试提供帮助的人。 :D