Home > Software design >  Unable to patrol enemies
Unable to patrol enemies

Time:12-26

I just can’t figure out how to make random points for patrolling, I went through 100 manuals, but I can’t do it.
No need to write about NavMeshAgent. Not used.

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);
        }
    }
}

The problem is that there may be obstacles in the form of a fence, a tree, houses, cars, etc.

I need that when the enemy appears, random points are generated in his radius so that he does not leave further.
Help me out, I can’t figure out what needs to be done to make everything work ...

CodePudding user response:

It turns out that I just did not see that the Pivot of the model is not clear where, it flies in another dimension, the problem is solved, it is necessary to reset all transformations and the world point of the model's coordinates.

I didn’t see it right away, all the options turned out to be working ...

CodePudding user response:

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);
    }
}

}

use this patrolling script you just need to pic a random waypount position each time by using a Random.range()

  • Related