如何让敌人转身并在附近移动? Unity3D

时间:2015-06-14 08:54:57

标签: c# unity3d

当玩家进入某个附近区域时,我试图让我的敌人物体转向并开始向我的玩家物体移动。

对于转弯,我一直在测试transform.LookAt()函数,虽然它没有返回所需的结果,因为当玩家离敌人物体太近时,敌人开始向后倾斜而我只想要我的敌人能够在y轴上旋转,提前谢谢。

using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {
    public Transform visionPoint;
    private PlayerController player;

    public Transform Player;

    public float visionAngle = 30f;
    public float visionDistance = 10f;
    public float moveSpeed = 2f;
    public float chaseDistance = 3f;

    private Vector3? lastKnownPlayerPosition;
    // Use this for initialization
    void Start () {
        player = GameObject.FindObjectOfType<PlayerController> ();
    }

    // Update is called once per frame
    void Update () {
        // Not giving the desired results
        transform.LookAt(Player);
    }

    void FixedUpdate () {

    }

    void Look () {
        Vector3 deltaToPlayer = player.transform.position - visionPoint.position;
        Vector3 directionToPlayer = deltaToPlayer.normalized;

        float dot = Vector3.Dot (transform.forward, directionToPlayer);

        if (dot < 0) {
            return;
        }

        float distanceToPlayer = directionToPlayer.magnitude;

        if (distanceToPlayer > visionDistance)
        {
            return;
        }

        float angle = Vector3.Angle (transform.forward, directionToPlayer);

        if(angle > visionAngle)
        {
            return;
        }

        RaycastHit hit;
        if(Physics.Raycast(transform.position, directionToPlayer, out hit, visionDistance))
        {
            if (hit.collider.gameObject == player.gameObject)
            {
                lastKnownPlayerPosition = player.transform.position;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

改变目标的外观:

void Update () {
    Vector3 lookAt = Player.position;
    lookAt.y = transform.position.y;
    transform.LookAt(lookAt);
}

这样看目标的高度与对象的高度相同。

答案 1 :(得分:0)

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyMovement : MonoBehaviour
{

    public Transform Player;
    public float MoveSpeed = 4;
    int MaxDist = 10;
    int MinDist = 5;




    void Update()
    {
        transform.LookAt(Player);

    if (Vector3.Distance(transform.position, Player.position) >= MinDist)
    {

        transform.position += transform.forward * MoveSpeed * Time.deltaTime;


        if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
        {
           // Put what do you want to happen here
        }

    }
}

}