在移动平台上移动敌人

时间:2018-07-09 09:10:13

标签: c# unity3d

我有一个设置,其中包含一个移动平台(绿色)和一个在其上方巡逻的敌人,如下所示:

enter image description here

平台周期性地左右移动,巡逻的敌人也同时使用rigidbody.velocity。分别在运动中时,两者都看起来不错。但是,当敌人位于平台的顶部,并且敌人是平台的子对象时,即使我已经校正了平台的速度,敌人也会显得静止(只是在其中播放移动动画)。下面是我的巡逻代码片段:

void Start()
    {
        myRigidBody = GetComponent<Rigidbody2D>();
        parent = transform.parent;
        parentVelocity = new Vector2(0f, 0f);
    }

    // Update is called once per frame
    void Update()
    {
        if (parent != null && parent.GetComponent<Rigidbody2D>() != null) 
            parentVelocity = parent.GetComponent<Rigidbody2D>().velocity;

        Debug.Log("parentVelocity=== " + parentVelocity);
        if (IsFacingRightOrUp())
        {
            if (moveVertical)
                myVelocity = new Vector2(0f, moveSpeed);
            else
                myVelocity = new Vector2(moveSpeed, 0f);
        }
        else
        {
            if (moveVertical)
                myVelocity = new Vector2(0f, -moveSpeed);
            else
                myVelocity = new Vector2(-moveSpeed, 0f);            
        }
        Debug.Log("myRigidBody.velocity === " + myVelocity);
        myRigidBody.velocity = myVelocity + parentVelocity;
        Debug.Log("myRigidBody.velocity === " + myRigidBody.velocity);
    }

它将生成调试日志,如下所示,parentVelocity默认为(0,0):

enter image description here

我该怎么做才能使敌人的运动与平台上的观察者相同,就像敌人站在静止的地面上时会出现的运动一样?

使用myRigidBody.velocity = myVelocity + parentVelocity;进行的校正似乎根本不重要。无论如何改正,敌人都显得静止不动。而且,如果我将移动平台的速度更改为零,那么它将按预期工作。为什么相对速度校正不起作用?

即使我将速度固定为100,但即使刚体组件正确地将速度显示为100,敌人也似乎是静态的。

1 个答案:

答案 0 :(得分:0)

在没有相对速度校正的情况下添加transform.Translate(myVelocity * Time.deltaTime);可以解决此问题,尽管我不完全理解为什么。

void Update()
{        
    if (IsFacingRightOrUp())
    {
        if (moveVertical)
            myVelocity = new Vector2(0f, moveSpeed);
        else
            myVelocity = new Vector2(moveSpeed, 0f);
    }
    else
    {
        if (moveVertical)
            myVelocity = new Vector2(0f, -moveSpeed);
        else
            myVelocity = new Vector2(-moveSpeed, 0f);            
    }                
    myRigidBody.velocity = myVelocity;
    transform.Translate(myVelocity * Time.deltaTime);
}

enter image description here