敌人gameObject没动

时间:2015-09-27 13:39:05

标签: c# unity3d

我遇到了敌人实施的问题。首先,我正在关注this tutorial。我有一个带有盒式对撞机的敌人游戏对象,基本上我只需要它。

这是我的剧本:

using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour {

[SerializeField]
private float rotationSpeed = 180; // In degrees per second

[SerializeField]
private float movementSpeed = 1f; // In units per second

[SerializeField]
private float meshRadius = 1f; // In units

private IEnumerator turnTowardsPlayerCoroutine;
private IEnumerator moveTowardsPlayerCoroutine;

void OnTriggerEnter(Collider collider)
{
    if (collider.gameObject.tag == "Player")
    {
        float playerDistance = Vector3.Distance(collider.transform.position, transform.position);

        // Ignore trigger events from the inner colliders
        if (playerDistance >= 2f * meshRadius)
        {
            turnTowardsPlayerCoroutine = TurnTowardsPlayer(collider.transform);
            moveTowardsPlayerCoroutine = MoveTowardsPlayer(collider.transform);
            StartCoroutine(turnTowardsPlayerCoroutine);
            StartCoroutine(moveTowardsPlayerCoroutine);
        }
    }
}

void OnTriggerExit(Collider collider)
{
    if (collider.tag == "Player")
    {
        float playerDistance = Vector3.Distance(collider.transform.position, transform.position);

        // Ignore trigger events from the inner colliders
        if (playerDistance >= 2f * meshRadius)
        {
            StopCoroutine(turnTowardsPlayerCoroutine);
            StopCoroutine(moveTowardsPlayerCoroutine);
        }
    }
}

private IEnumerator TurnTowardsPlayer(Transform player)
{
    while (true)
    {
        Quaternion targetRotation = Quaternion.LookRotation(player.position - transform.position, Vector3.up);
        targetRotation.x = 0f;
        targetRotation.z = 0f;

        transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        yield return 0;
    }
}

private IEnumerator MoveTowardsPlayer(Transform player)
{
    while (true)
    {
        Vector3 playerDirection = transform.position - player.position;
        playerDirection.y = 0;
        playerDirection = playerDirection.normalized;

        Vector3 deltaMovement = playerDirection * movementSpeed * Time.deltaTime;

        int layermask = LayerMask.GetMask("Environment");
        Vector3 movingTowards = transform.position - playerDirection*meshRadius + (new Vector3(0f, 0.1f, 0f));
        if (Physics.Raycast(movingTowards, Vector3.down, 0.25f, layermask))
        {
            transform.position -= deltaMovement;
        }

        yield return 0;
    }
}
}

结果是,当我进入敌人必须攻击我的区域时,敌人向我旋转,但他没有移动。我忘了什么或做错了吗?

2 个答案:

答案 0 :(得分:1)

我已经完成了几次教程,脚本是正确的。似乎缺少的是图层。确保“环境”图层存在并将其分配给环境对象。

将“环境”图层添加到必要对象的最简单方法是选择层次结构中应该位于“环境”图层中的每个对象,然后在检查器中更改图层。

答案 1 :(得分:0)

如果物理光线投射不成功,那可能仅仅意味着以下事情之一:

-layermask设置错误(它忽略了特定的分层对象,并且它没有击中任何东西)

- 你向错误的方向发送

- 拍摄距离太小,问题是在教程中你正在观察它可能与这个值一起工作,但你可能有不同的缩放你的水平。尝试把它放到更大的东西(100,1000)。