简体   繁体   中英

Unity3d maintaining a minimum distance between multiple GameObjects c#

I have multiple enemies that move toward the player. I am trying to stop them from merging into each other, ie maintain some type of minimum distance between each other. What I'm trying is this (from unity3d forums):

enemy1.transform.position = (enemy1.transform.position - 
enemy2.transform.position).normalized  * distance + enemy2.transform.position;

However, when I have >= 3 enemies they still seem to bunch up even when I apply this to every enemy combination.

I need a better method as this one does not work and does not scale.

What you do around your enemy prefab is place a quad box which in effect is a trigger element, then on you script for the enemy you set that if another enemy (using tag types, I imagine) comes within touching of the quad box then to run appropriate code to stop the enemy getting closer in and to prevent the enemy actually overlapping with this trigger box.

Your code you example in your question looks like it is referencing the enemy units specifically rather than as instance entitites which is very probably a bad way of coding, as you're finding, it's very inflexible dealing with not-specifically-named reference entities.

    using UnityEngine;
    using System.Collections;

    public class ExampleClass : MonoBehaviour
{

    private Transform otherEntity;
    public float distance = 50.0f;
    private Transform thisEntity;

    void OnTriggerEnter(Collider other)
    {
        otherEntity = other.GetComponent<Transform>();
        thisEntity = GetComponent<Transform>();
        thisEntity.position = (thisEntity.position - otherEntity.position).normalized * distance + otherEntity.position;
    }
}

I have not tested the above code but using the code you reference the values for the transform are loaded from the Game Component for the referenced entities, as this has changed ALOT in Unity since release of version 5.1 and your source for your code was an answer given in 2012!!

thisEntity is the object that the script is attached to, typically one of the enemy. The otherEntity is the object that comes within the quad trigger (please remember the quad needs to be referenced as a trigger element.

The values of the Entity variables need to be set once the trigger is entered, so that it always effects the correct other element.

(I may be totally wrong with my methodology but I hope this helps.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM