移动父变换时,子变换不会移动

时间:2017-08-26 20:10:36

标签: c# unity3d

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

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

Platform TopDown View

玩家还有一个Rigidbody,平台也是。这是我使用的平台检查员的图像

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
        }
    }
}

现在出现问题:

在平台上跳跃时,玩家将成为平台的孩子。但是当平台开始移动时,播放器不受此影响。他并没有被平台所感动。

我希望有人可以帮我解决这个问题&#34;小&#34; (?)bug。

更新

以下是玩家检查员的图片

PlayerInspector

1 个答案:

答案 0 :(得分:0)

好吧,我去尝试了一下,这对我来说是一个有效的解决方案。

我删除了刚体

并采用此代码

Lam

现在,[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; } 中的Translate()移动了平台。 FixedUpdate()只是检查平台是否应该移动。