Unity2D Enemy Patrol,奇怪的精灵旋转

时间:2017-07-19 11:48:11

标签: c# unity3d

这里需要帮助,我一直在关注Enemy Patrolling这个教程,https://www.youtube.com/watch?v=KKU3ejp0Alg

教程告诉我们设置2个空游戏对象和坐标,以便精灵从一个方向走到另一个方向,步行确实有效,但精灵的旋转变得非常奇怪,“蠕虫”#39 ;精灵假设现在左右移动它变成面朝上 请看这个图片,

从左向右移动时 enter image description here

从右向左移动时

enter image description here

public Transform[] patrolPoints;
public float speed;
Transform currentPatrolPoint;
int currentPatrolIndex;

// Use this for initialization
void Start()
{
    currentPatrolIndex = 0;
    currentPatrolPoint = patrolPoints[currentPatrolIndex];
}

// Update is called once per frame
void Update()
{
    transform.Translate(Vector3.up * Time.deltaTime * speed);

    if (Vector3.Distance(transform.position, currentPatrolPoint.position) < .1f) {
        if (currentPatrolIndex + 1 < patrolPoints.Length)
            currentPatrolIndex++;
        else
            currentPatrolIndex = 0;
        currentPatrolPoint = patrolPoints[currentPatrolIndex];
    }

    Vector3 patrolPointDir = currentPatrolPoint.position - transform.position;
    float angle = Mathf.Atan2(patrolPointDir.y, patrolPointDir.x) * Mathf.Rad2Deg - 90f;

    Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
    transform.rotation = Quaternion.RotateTowards(transform.rotation, q, 180f);

}

这是代码

谢谢

2 个答案:

答案 0 :(得分:2)

您可以将可选参数Space.World传递给翻译,以相对于世界空间而不是对象空间移动对象。这应该可以防止你的物体旋转。

transform.Translate(Vector3.up * Time.deltaTime * speed, Space.World);

您可以在documentation中了解更多相关信息。

答案 1 :(得分:0)

你可能将敌人精灵旋转了90度。尝试将所有脚本放入没有旋转的空游戏对象,而不是将敌人精灵放置为空游戏对象的子项并根据需要旋转。这样你的逻辑就不会与你的图形发生冲突。

相关问题