gpt4 book ai didi

c# - 移动父变换时子变换不移动

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:47 24 4
gpt4 key购买 nike

我有一个玩家控制的平台。当移动到外边缘时,平台开始移动。外部触发器的宽度由代码计算。

因此玩家可以向任何方向移动,他只需要靠近边缘即可触发移动。

Platform TopDown View

玩家连接了一个刚体,平台也是。这是我使用的平台检查器的图像

Platform Inspector

这是附加的代码

[SerializeField]
private float speed; // the movementSpeed

[SerializeField]
private float movementTriggerWidth; // width of the triggers at the outer edges

private Vector3 movementDirection = Vector3.zero;
private Rigidbody platformRigid;
private GameObject player;
private float triggerDistance; // distance from center to a trigger

private void Start()
{
player = Globals.GetPlayerObject(); // search for the player Object in the scene
platformRigid = GetComponent<Rigidbody>();

triggerDistance = transform.localScale.x / 2 - movementTriggerWidth; // set the trigger distance
}

private void OnTriggerEnter(Collider col)
{
col.transform.parent = transform; // set the player as a child of the platform
}

private void OnTriggerExit(Collider col)
{
col.transform.parent = null; // leave the platform
}

private void OnTriggerStay(Collider col)
{
if (col.gameObject == player) // only the player can move the platform
{
Vector3 playerPosition = player.transform.position;
Vector3 platformPosition = transform.position;

if (Vector3.Distance(playerPosition, platformPosition) > triggerDistance) // player is in outer trigger?
{
movementDirection = playerPosition - platformPosition; // calculate the movement direction
platformRigid.MovePosition(transform.position + movementDirection * speed * Time.deltaTime); // move the platform
}
}
}

现在的问题:

在平台上跳跃时,玩家成为平台的 child 。但是当平台开始移动时,玩家不受此影响。他不会被平台打动。

我希望有人能帮助我解决这个“小”(?)错误。

更新:

这是玩家检查员的照片

PlayerInspector

最佳答案

好吧,我进行了一些尝试,这对我来说是一个可行的解决方案。

我移除了刚体

并获取了这段代码

[SerializeField]
private float speed;

[SerializeField]
private float movementTriggerWidth;

private Vector3 movementDirection;
private bool move = false;
private GameObject player;
private float triggerDistance;

private void Start()
{
player = Globals.GetPlayerObject();
triggerDistance = transform.localScale.x / 2 - movementTriggerWidth;
}

private void OnTriggerEnter(Collider col)
{
col.transform.parent = transform;
}

private void OnTriggerExit(Collider col)
{
col.transform.parent = null;
}

private void OnTriggerStay(Collider col)
{
if (col.gameObject == player)
{
Vector3 playerPosition = player.transform.position;
Vector3 platformPosition = transform.position;

if (Vector3.Distance(playerPosition, platformPosition) > triggerDistance)
{
movementDirection = playerPosition - platformPosition;
move = true;
}
}
}

private void FixedUpdate()
{
if (move)
transform.Translate(movementDirection * speed * Time.deltaTime);

move = false;
}

现在平台由 FixedUpdate() 中的 Translate() 移动。 OnTriggerStay() 只是检查平台是否应该移动。

关于c# - 移动父变换时子变换不移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com