unity3d 无法巡逻敌人

np8igboo  于 2022-12-27  发布在  其他
关注(0)|答案(2)|浏览(174)

我就是想不出如何随机点巡逻,我看了100本手册,但我做不到。
无需编写NavMeshAgent。未使用。

using System.Collections;
using UnityEngine;
public sealed class Manikin : MonoBehaviour {

    private Vector3 StartManikin = Vector3.zero,
                    NewPosition = Vector3.zero;
    private readonly float Speed = 2.0f;

    void Start() {
        StartManikin = transform.position;
    }
    
    void Update() {
        if (Vector3.zero == NewPosition) {
            NewPosition = StartManikin + Random.onUnitSphere * 2;
        }
        if (Vector3.Distance(transform.position, NewPosition) < 0.1f) {
            StartManikin = transform.position;
            NewPosition = Vector3.zero;
        } else {
            transform.LookAt(new Vector3(NewPosition.x, StartManikin.y, NewPosition.z));
            transform.position = Vector3.MoveTowards(transform.position, NewPosition, Speed * Time.deltaTime);
        }
    }
}

问题是,可能会有障碍物的形式,栅栏,树,房子,汽车等。
我需要敌人出现时,在他的半径范围内随机生成点,这样他就不会再离开。
帮帮我,我不知道该怎么做才能让一切正常运转...

nwlls2ji

nwlls2ji1#

原来我只是没有看到模型的Pivot不清楚在哪里,它在另一个维度飞行,问题解决了,需要重置所有的变换和模型坐标的世界点。
我没有马上看到,所有的选择结果都起作用了...

lyr7nygr

lyr7nygr2#

using UnityEngine;

public class Patrol : MonoBehaviour

{
public Transform[] waypoints;
private int _currentWaypointIndex = 0;
private float _speed = 2f;

private float _waitTime = 1f; // in seconds
private float _waitCounter = 0f;
private bool _waiting = false;

private void Update()
{
    if (_waiting)
    {
        _waitCounter += Time.deltaTime;
        if (_waitCounter < _waitTime)
            return;
        _waiting = false;
    }

    Transform wp = waypoints[_currentWaypointIndex];
    if (Vector3.Distance(transform.position, wp.position) < 0.01f)
    {
        transform.position = wp.position;
        _waitCounter = 0f;
        _waiting = true;

        _currentWaypointIndex = (_currentWaypointIndex + 1) % waypoints.Length;
    }
    else
    {
        transform.position = Vector3.MoveTowards(transform.position, wp.position, _speed * Time.deltaTime);
        transform.LookAt(wp.position);
    }
}

}
使用这个巡逻脚本,你只需要每次使用Random.range()来选择一个随机的通道装载位置

相关问题