Reputation: 129
I'm working on a RTS game. I did a normal move script and I increase the agent's stopping distance so they don't look at each other and pump that much. But they still hit each other.
I can't find the way to make agents avoid each other and not push each other. Or someway to ignore the physics while still trying to avoid each other. Here is the code for the click to move
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class moveTest : MonoBehaviour {
NavMeshAgent navAgent;
public bool Moving;
// Use this for initialization
void Start () {
navAgent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update () {
move();
}
void move()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(1))
{
Moving = true;
if (Moving)
{
if (Physics.Raycast(ray, out hit, 1000))
{
navAgent.SetDestination(hit.point);
navAgent.Resume();
}
}
}
}
}
Upvotes: 1
Views: 1934
Reputation: 7605
From the following link (which sadly don´t have images anymore)
Script
using UnityEngine;
using System.Collections;
public class enemyMovement : MonoBehaviour {
public Transform player;
NavMeshAgent agent;
NavMeshObstacle obstacle;
void Start () {
agent = GetComponent< NavMeshAgent >();
obstacle = GetComponent< NavMeshObstacle >();
}
void Update () {
agent.destination = player.position;
// Test if the distance between the agent and the player
// is less than the attack range (or the stoppingDistance parameter)
if ((player.position - transform.position).sqrMagnitude < Mathf.Pow(agent.stoppingDistance, 2)) {
// If the agent is in attack range, become an obstacle and
// disable the NavMeshAgent component
obstacle.enabled = true;
agent.enabled = false;
} else {
// If we are not in range, become an agent again
obstacle.enabled = false;
agent.enabled = true;
}
}
}
Basically the issue that this approach tries to solve is when the player is surrounded by enemies, those which are in range to attack (almost touching the player) stop moving to attack, but the enemies in the second or third row are still trying to reach the player to kill him. Since they continue moving, they push the other enemies and the result is not really cool.
So with this script, when an enemy is in range to attack the character, it becomes an obstacle, so other enemies try to avoid them and instead of keep pushing, go around looking for another path to reach the player.
Hope it can help you some how
Upvotes: 2