#π€βai-navigation
1 messages Β· Page 8 of 1
Hmm.
Im using this btw https://github.com/Blueteak/Unity-Neural-Network/
Weird. It kinda works against unity logic. The moment you destroy a GameObject, its components are also destroyed and should return null reference if you try to access them...
hmm yea im not sure what i did there either actually
Yeah, but unity should still throw an error if he tries to access a component marked for destruction. Or so I thought...
@late thunder what's the purpose of that Destroy there anyway?
otherwise i spawn useless cars
i only want their brains
so I can just return a list of brains
ill do that actually
MonoBehaviours can't live without a GO. So it's probably destroyed at the end of the frame.
By the way it seems you give them a random brain "when spawned", to then give them the one from one of the parents ? Isn't it useless ?
its for the first generation
oh okay
they dont have a brain yet
fair :p
And GetBrain function probably returns something, right?
yeah it returns this.brain, or if it is null then it makes a random brain
so im thinking the problem is lying there but i just cant find it
yeah try to clone instead of passing reference
So CloneCC is something that you don't need(want to dispose of) along with Clone object?
Then I don't get the whole point of instantiating a new object...π
it was temporary
but if it works it works
im changing it now though
List<NeuralNet> CloneSelection(CarController[] selection, int size, GameObject prefab)
{
List<NeuralNet> clonedList = new List<NeuralNet>();
for (int i = 0; i < size; i++)
{
NeuralNet nn = new NeuralNet(6, 8, 2);
nn.SetBrain(selection[0].GetBrain());
clonedList.Add(nn);
}
return clonedList;
}
i changed it to this
it still doesnt work tho
What's Brain? Is it a Monobehaviour?
its a NeuralNet
im using this small custom library
Okay, it's not. So this part should be fine in my opinion.
Here you said that they all contain the same number. Is that unwanted behavior?
Okay. Then what's the problem now?
this
somehow, it clones incorrectly or something once, and then it clones correctly the rest of the time (forever)
i can make a quick video
@tardy junco @real sonnet (sry for @ )
https://streamable.com/t4hjax
this has been ruining my life for the past week
this is consistent behaviour btw: the first time it clones, its always mutated, or random. the generations after that are perfect clones of the one I clicked on
Yeah they all get c1 brain on L:143
yup
and then you want to activate back mutation and have all except one behave differently
yea
aaaand I dont remember what goes wrong
so the good one doesnt get mutated and ruins the generation
it doesnt keep one un-mutated. not applying mutation at all doesnt solve the problem either: the first clones are random (i think), and the clones after that are perfect clones of the random clones
How do you pick the good one?
i click on it
Where's that code?
I don't see any clicking related code...
this is in carcontroller
Try debugging the gameobject and making sure it's the one you actually clicked.
everything is Car(clone)
Might be just an opinion ? Or try to increase mutationRate ?
wait I'm confused xD
add gameobject as the second parameter. That will allow you to click the debug to highlight the object.
but it should not matter, because if I do mutate the population, then it still wont keep the best from the prev gen
oh ok thx cool
i disabled it on purpose
to show that it clones the wrong one
or a random one
nooo youre already a big help you dont have to use your time to help me
that's fun though
its not fun after 10 hours of debugging π¦
So if I get it now, you expect the clones having the same brain as the fittest one from prev gen ?
(without mutation)
Normally, yes. But now I am manually clicking on them to test if they are cloning the right one
yeaaa
line 174:
newCarController.GetBrain("Spawn");
What's the purpose of this? Did you forget to assign it to something?
its actually the oposite of what i was thinking. I was looking for a reference vs value problem, but instead your clones dont get the fittest brain
its to get a brain (in the constructor of CarController i dont get a brain)
GetBrain also makes this.brain = new brain if it doesnt have a brain already
public NeuralNet GetBrain(string i = "")
{
if(this.brain != null)
{
return this.brain;
}
else
{
Debug.Log("Nieuwe Brain: " + i);
this.brain = new NeuralNet(6, hiddenLayerNodes, 2);
return this.brain;
}
}```
the string is just for debugging purposes
Okay... Not the best descriptive code, but that explains it...
yea im kinda new to coding
yup
yea im using that specific weight as an ID
the thing at the bottom
I am going to see if the selected brain and the cloned brains have the same ID (already did this, but checking again)
And they are, no?
I am going to check now again if they have the same ID
yeah same
i was looking again and noticed that haha, I'm so confused right now
did you debug as I suggested?
im circling my mouse around the spot it should go
yea 1sec
it appears to have exactly the same ID, meaning the brains of the selected car and the clones are the same. It drives differently tho somehow
Huh, weird. its returning a different instance id
I log the instance ID when I click it, and then log the instance ID in th e foreach loop
and its different
GeneticAlg
CarController
Perhaps you have several of the chosen ones?
How did you check?
Hmmm
does it change the instance id or something when you put it in a list
nah that would be weird
im going to output every instance id
wut, the instance id shown when clicking a car isnt even in the list of sortedCars
what in the world
the brains are the same tho
I give up
:/
How does unity make that graphic in the navigation editor window?
The graphic that shows the character's height and stuff
Hey i wanna archive some enemy avoidance with steering behaviour. But somehow it works not as i want - i walk towards the highest dot product value but thats kinda wrong i guess
cod >>> https://hatebin.com/fdrodqmncf
reference >>> https://www.red3d.com/cwr/steer/gdc99/
can someone pls help
This paper presents solutions for one requirement of autonomous
characters in animation and games: the ability to navigate around
their world in a life-like and improvisational manner.
hey guys, i have an ai with nav mesh but the terrain asset is fucked so i cant use only nav mesh, how can i make im create random points within a certain range, this one that i have, creates a walking point in the range of the on that came before i want a general range
sry if it is a bit confusing
Hey! I canΒ΄t get my cooldown working, any ideas? The code snippets using it: https://hatebin.com/evmfvqsriq
all the refs are wrong. google the keyword
also, use a coroutine for a timer
plenty of examples on google
would wave spawning count as ai becuase im trying to use brackeys wave spawner and they do spawn but they spawn infinitely
ive been looking at his video and cant find what i did wrong can anyone help me?"
i just need help how to stop them from spawning infinite amount of spawns
Hello π Can any one recommend a good AI / Behaviour Tree framework? There are a few options out there,but is there like one that sticks out / battle-proven? I tried setting up my own framework but quickly hit the limits of my skills.
@gritty cloak I used Opsive Behavior Trees from the asset store, I like it, allowed me to visually troubleshoot my state, just like blueprints
The only part that was always confusing to me, is that every action and every decision needs to be it's own script. So unlike having a state machine that is part of your Character class, the scripts have to find a reference to the Character they are responsible for each time they execute. But in the end it didn't end up being any major overhead to use a guid and a singleton that would return the correct character
@full sierra You mentioned blueprints... do you mean Unreal Engine? I really liked their AI system. Is it comparable?
oh wow the trailer for that asset is an official unity video. i guess i found my solution then. seems as advanced as i'd need it to be
Yea Unreal Engine, well Unreal Engine allows you to blueprint everything. I have not used Unreal, but the idea is the same. If you can see you code snippets running, it is easier to debug for most of us. AI is tricky to debug with a log, you need a visual reference (IE: Blueprint like system)
yea, just bought the asset cause yolo but looks very familiar. just have to get used to how it works in unity. thanks for the recommendation!
good day people. Im hoping someone can assist with navmeshagent's. Im setting up an enemy npc with navmeshagent to follow the character target, but no matter what I set the NMA speed to it's still keeping pace with the player, even setting speed to 0. Can anyone point out what I've obviously missed?
How are you moving it?
@dilch I fixed that issue π I had forgotten to add a capsule collider lol. Just struggling with an issue on the anim right now
meh. I always type your name wrong too π
@tardy junco any chance you're familiar with importing animations from blender to unity (same model in both)?
A little bit. They should work out of the box if they use the same rig.
It's better to ask in #πβanimation
should lol. and yeah I have put the post in there, its a dead zone currently though π
whats working flawlessly in blender is dropping the character transform on the Y axis as soon as the animation starts playing in unity
there it is π
got no idea why when the rig/model is the same and works on the blender end. Im only guessing but I'm assuming I missed a step at either export or in unity
thing is, as you'll see in the video, the actual GameObject transform isn't shifting when it happens
the entire rig position doesnt match the blender pose on any key either
that happens cuz ur animation and model are not set to humanoid
Hey, what's the purpose of setting an agent during baking a navmesh? I thought there are different types of agents you can setup already?
Hello, Just wanna spread attention for my "Help wanted" thread on Unity Forum in Navigation & AI, Seems like here is waaay more ppls than on forum...
Thread is about problem with navmesh agent local avoidance in RTS, if anyone willing to point me out maybe a good asset which resolve this i will be grateful.
https://forum.unity.com/threads/how-to-approach-this-problem-with-navmesh-agents-local-avoidance-asset-suggestion-maybe.1025272/
Can I pathfind only where there is a specific light level and how would I do this?
You will need data on your light level, so you can include it in the map. Some ambiguity in the term light level though, light level could be something your performing on each tile, or maybe you mean "Can I determine the light level of a unity light shining on a specific tile at a specific location" in which case you got to ask the guys in the lighting channel.
hey guys
how do i make a A.I like i am a total newb so i don't know what navmest means and stuff
so does anyone know any posts or videos that might guide me through?
check brackeys channel he has a tutorial on that.
Note : you can make more complexed AI logic by using some alogorithms like A* or theta* and more without using navmesh
@prisma prawn
@prisma prawn Hi, I just wanted to add that AI and Pathfinding are not the same thing. When you ask about NavMesh you are asking about finding a path between two points, which is related to pathfinding. AI is more about ways to have entities/game managers which can "intelligently" make decisions on their own depending on the game's world state. For example: on a FPS game, how should a Bot react when they see a grenade being launched towards it? Should the Bot run? Should it take cover? Maybe, if it has enough time, should it pick the grenade and throw it back to the enemies?
Well, pathfinding IS useful for AI because, on games, we usually needs our entities to navigate through the scenario, so AI and Pathfinding are two terms which usually are together, but they are not completely coupled to each other
So, I'm not sure if you just want to know about pathfinding, but if you're interested in understanding AI to create your own Bots, and you say that you're just beginning with the matter, I suggest you three AI models:
.
Finite State Machine (FSM): in games, commonly used for AI and animation. You create a graph of states and create transitions, actions and decisions in order to define how the behaviour of the FSM agent will be
A introduction to the concept by Robert Nystrom: https://gameprogrammingpatterns.com/state.html
Behaviour Tree (BHT): also very commonly used on AI. You define the behaviour of the entity by creating a tree (in terms of data structure). This model was used in Halo and Bioshock
Nice Gamasutra article explaining the concept: https://www.gamasutra.com/blogs/ChrisSimpson/20140717/221339/Behavior_trees_for_AI_How_they_work.php
Goal Oriented Action Planning (GOAP): used to create planners which can come up with plans to resolve problems in a very dynamic way. It's the AI model used in F.E.A.R
Very useful source on GOAP: http://alumni.media.mit.edu/~jorkin/goap.html
So, if you're looking into knowing more how AI works, I suggest you to read these posts.
As for implementing your first AI, I would try FSM first as I think it it a good start for beginners, and as it has a nice evolution: **Hierarchical **Finite State Machine (HFSM). Hit youtube with the search "Unity3d FSM" and see what better fits your current level
@sonic rain thank you so much this article helped
but i want to create a AI enemy in a horror game like the one you see in granny or in metal
which one should i use if i want to create a AI similar to that
@prisma prawn
For that, both FSM and BHT seems like a nice fit. But I would use FSM in this case. Your collection of states would represent the possible states in which the Granny could be. Is she chasing you? Is she just wandering randomly in the house? Is she attacking you? Etc
Simplifying and summarising a lot, just to illustrate:
Every FSM has its starting point, so in that case, Granny would start by choosing a random place in the house to go
And the it would go from/to states depending on what happens
Like if you make some noise, she would go to where the noise happened and see if she finds you...if not, then she goes back to patroling again
You type fast
Movement can be aimed by NavMesh system or not, that's your choice
No worries, just really consider diving deeply into this, because AI is an important subject on game development and if you make your own FSM system (or BHT, GOAP), you can try to make it re-usable between other projects
So you can have the same basis FSM for other types of enemies
Investing time on reading and making it correctly is a good thing for you as a gamedev
Thx for the heads up
If I earn from my game I'll you give u a buck no joke there lmao
Hi all,
I've the following issue with navmesh
did posted it on reddit with screens as well : https://www.reddit.com/r/Unity3D/comments/kiqy1t/navmeshissue_on_multiple_floors/
Any idea what i'm doing wrong?
Is there an updated guide on how to bake navmesh at runtime? Everything i've seen online seems very outdated.
I'm randomly generating a world and I want to bake it after it's completely generated.
There is no such thing as a "NavMeshSurface" in the latest unity version, and literally every single guide uses it.
@thorn hemlock AFAIK NavMeshSurface is the indeed the way to go for baking on runtime, but it doesn't come by default on Unity, you have to add it as an external package which can currently be downloaded on Github: https://github.com/Unity-Technologies/NavMeshComponents
There seems to be a major problem on generating localized navmesh in realtime using unity terrains. With localized I mean generating navmesh only around objects that need it. Every time I request navmesh from the terrain it rebuilds it completely from terrainData.ExtractNavMesh, which is incredibly slow. I couldn't find any way to cache that either, since the function above and everything related to that is hidden in the engine.
@sleek oak it sounds like you should file a bug report, in theory there is nothing inherently slow about ExtractNavMesh so it is probably miswritten on Unityβs side
@slim garnet I'm guessing it's baking the navmesh from the heightmap though? So it creates a mesh from heightmap every call. At least that's what I figured since it's so incredibly slow
well it should clearly be cached
terrains are already subdivided so it should be able to cache most of the terrain when e.g. obstacles are placed on top of a specific spot
Yeah, I'll just create a minimal project and submit a bug report
This makes me so happy! I definitely did not spend 10 days on it!
@hazy oar Cool! Did you create your own algorithm for this? Or did you use some pre-built program like the ML program from VS to train your model?
I did it myself.
You said that at almost 2 in the morning?
The lazers check if they should spawn every fixedUpdate. A float increases based on the velocity is used to shoot lazers, as passing a threshold resets it and calculates where to place it.
Based on the activation delay and the time it stays active it determines the closest point it estimates they are going to be at in the middle of it (shown with a trail) to start the lazer. It then sends a raycast in a random direction with a random length from 0 to a float variable, plus .001, then minus the direction by .001 as to prevent it from going inside what it hits, because then doing the other ray casts hits the same point. It then does 2 more raycasts in opposite random directions, and creates a lazer object from the points.
Took 100,000 times longer to code than describe.
It is almost impossible to avoid it if it places it at the end of you jump, especially placed flat because you can't change the jump height, so you kinda have to fall into it.
Mabey I will change that.
why arent my ai going to other meshes, that are apart of my nav mesh surface? do i need to use navmesh links?
@strong karma yes.
alright thanks
You need to connect discontinuities one way or another
alright
is there a way to create a simple ai that picks between rock, paper, and scissors using enum?
not ai
oh okay my bad
but random function can be used
random.range?
Don't say that. I was accused by Fogsight of trolling JUST for saying that.

I am NOT kidding.
then me ded 
Okay, back to topic.
yes
in java you can use math.random between 1 and 3 and then write an if else function to pic rock for 1 sizzors for 2 and paper for 3
UnityEngine.Random.Range(0, 4) @severe crescent
I believe with range the last number is never picked so you'd make it 4 instead of 3.. Could be wrong
If int = 3 enum state = scissors, so on
Ahh okay thank you
"SetDestination" can only be called on an active agent that has been placed on a NavMesh
Im getting this error. Does anyone know how i can fix it
nevermind i fixed the problem
my ai guy when it hits me it has a siezure and flys across the world help
this is setting
this is code
I GOT IT I REMOVED RIGID BODY
Hey all! I'm working on a stealth game with melee combat. I'm trying to figure out how the AI should act. Perhaps similar to the Assassin Creed games but much simpler.
So, as a player, should you have the option to sneak past a guard, or takedown from behind. Should the enemies hear you if you attack their comrades? Should AI attack you in a group or 1 on 1?
Here's a small clip with rough gameplay:
https://www.youtube.com/watch?v=xf7a1d711xg&ab_channel=PhantomProgramming
This is a stealth game I'm working on. Very barebones atm, just thought I'd show some of the gameplay off.
@little nymph Impressive thus far. I would go the route of saying the AI should be able to detect you if within X radius of you taking down another but only if the take-down wasn't completely stealthy. (If possible?)
If you are detected, all AI in X radius should come for you. perhaps there are places you can hide to remove the 'wanted level' ?
Hello all question for everyone. I have an AI NashMesh set up on my Terrain. How can I 'slice' the mesh up a bit so that I can mark areas that should be avoided and so on?
it just makes one big navmesh over everything when baked
Any ideas on how to make a simple fps game ai for enemies
You should check out Coroutines
@unkempt ocean Create a component which takes some sort of movement input, like target position or direction. Control those inputs based on where the AI desires to be.
Unity ships with few of these type of components, like Character Controller and Navmesh Agent.
Can someone help me with how to make a Navmesh not just follow you around but follow you around until a certain range, then start shooting you
cuz rn he just follows u and gets up in your face
ping me pls
thx
Anyone know the best way to have an AI move along a straight path?
I want one of my AI to charge in a straight line until it hits something
So for example, the cyan dot would be a player. Red is the enemy that's just spotted them. The player would run along the cyan line out of the way of the enemy. The enemy would continue along the green path until they hit the wall.
Currently thinking about crawling along in 0.5m increments and sampling downwards, then caching it and repeating until I have the furthest point
I would probably just crawl from previous position to next position
I imagine the AI moves over time
Moving in a straight path is straight (no pun) forward, is the problem with knowing how to detect hitting something. This depends on your model, you might do this with physical colliders, or a populated tile graph
Is there a way to constrain a navmesh agent to move only in two directions?
put an invisible collider on both sides of the 3rd axis
might be a programmatic way to do it but I have never used navmesh, I like A*
I wouldn't even use path finding for 2 dimensions
I mean 1 dimension
how do i increase the slowdown speed of nav mesh agent ?
i don't like the way it (kinda ) drifts to side when i want it to change direction.
i am trying to make a moba like mechanic
@full sierra I ended up doing the crawl. It's for a single enemy done once every so often so the raycasts cost very little overall
What does the raycast do?
@stray swallow Seems to be up for me https://arongranberg.com/astar/
Hello there, I want to work with obstacle avoidance with A*. What could be the solution for this?
Introduce obstacles into your A* algorithm.π€·ββοΈ
Any source for that please.
Should be implemented in your A* api. What are you using?
does anyone know any good tutorials for 3d enemy ai that shoots at the player and wanders, all the ones on youtube ive found are outdated
Does anyone know why I can't bake my nav mesh? The target of the enemy AI is the player prefab. You have to press the play button in the main menu scene to go start the game. I don't know what I'm doing wrong.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class zombieAI : MonoBehaviour
{
NavMeshAgent NMA;
public Transform target;
void Start()
{
NMA = GetComponent<NavMeshAgent>();
}
void Update()
{
NMA.SetDestination(target.position);
}
}
How are they outdated?
Did you actually bake it?
i did. I pressed the button, turned on show path polygons. It didn't work.
Did you set walkable objects as navigation static?
Did you actually read about navmesh in the manual / watch a tutorial explaining how to use it?
a tutorial
Okay, so it worked for them and not for you?
yeah.
Then you probably missed something in that tutorial. Or it's bad. Can you link it?
In this tutorial, you will set up and code a simple Unity3d AI system. I will try to show you the simplest way to do it and give you the framework to build on it in any way you want.
This is part one of two and will cover the absolute basics of baking out your NavMesh and creating a moving enemy that chases a target around your scene.
Assuming you followed the tutorial properly, it should work.
hello, I want to do Enemy AI for my FPS Prototype. I have a lot of requirements and each one of them doesn't sound too hard to hard to make on it's own, but I'm afraid I'll run into some spaghetti code once I join them all together
I really like making reusable components for micro behaviors and use them to compose my stuff and would like to follow that pattern here
any recommended tutorials or reads on how to structure enemy AI?
Finite state machine perhaps?
any good reads on FSM?
Plenty. Here's a good video for example https://youtu.be/V75hgcsCGOM
Build bots for your Unity game with a powerful but simple to manage state machine built completely in c#. Learn how to use the state pattern in unity, building an AI to control harvesting bots that could be used for an RTS, building game, shooter, or anything else. We'll dive into transitions, states, ai, bots, and how to hook it all up in a cle...
idk but the tutorials i tried none of the code worked properly
You sure the problem was with the tutorials? Were there compile errors in the tutorial code?
Instead of discarding the tutorials, you should stick with one and if there are problems during the tutorial, ask fro help in #π»βcode-beginner.
Worked a bit on this one today, the agent's "Brain" is continually provided classified visual info based on what he can see from his perspective. He picks his next action based on very simple motivation/goal definitions (here he wants to "Kick" all the "Physics objects" for "Fun") and can refer back to earlier visual input (Memory) if he doesn't have anything to do or can't see anything new to do. Will be fun to see how it turns out when interacting with other agents.
I wasn't expecting that at the end he decided to run up to my first person camera component because apparently he classified it as a "Physics object" since it had a rigidbody and really wanted to kick it π
thanks! you mentioned the brain which I think I will need to centralize the information for the various scripts
you also mentioned the memory which I was thinking about (like last known location)
I'll also check Jason's tutorial, I really like the way he codes
Ai in my game are pretty lame, I am new to video game ai, and I want to expand on my game ai with a behavior tree system. As a solo developer and full-time student, is it worthwhile to make my own implementation (I am not using navmesh agents) as opposed to an asset store asset?
Unless it's for educational purposes, probably no. There are some decent free implementations on the asset store. If you want some challenge you could find a generic open source implementation for c# and port it into your project.
Ok, thanks!
Indeed! I read a few books on neuroscience and psychology past few years and I'm trying to model and conceptualize my understanding of it in the implementation. Incidentally, the executive central decision component of the "Brain" is called "PrefrontalCortex", while the visual interpretation happens in the "VisualCortex" component π
I think a very qualitative entirely heuristic based AI would be kind of uninteresting to explore so I'm incorporating ideas from Steel, P., & KΓΆnig, C. J. (1992). Temporal motivation theory to quantify my agent's behavior. Goal is to be able to train the agent with reinforcement learning to maximize his motivation to stay alive and clear the area of any perceived threats.
You can see there the agent's stream of conciousness, the top log is the current visual input (filtering out the useless things), second is the kind of stream of consciousness and bottom is somewhat the same just a log of the agent's memory. He can do a bit more than just kick boxes but that's the scene I have at the moment π
I'm kind of meh when it comes to those kind of state machines, on top of that I think rolling your own generic state machine framework just for the sake of it is also probably going to get very clunky too.
When it comes to state machine oriented tasks. I've encountered a few at work/hobby and I always see much more value writing a more language oriented interpreter approach which allows for way more flexibility/complicated behavior and eventually cleaner and less code overhead. Technically, that's still going to be a state machine I guess but even then when you conceptualize those using turing machines they're way easier to work with.
It's 2021. Mankind invents AI. It likes to kick things.
The AI realized the secret to life, the universe and the meaning of existence, its resolute decision was that every object needed to be kicked at least once.
is there any reason a navmesh agent wouldnt respond to movement events? for example chaning the transform.rotation to make him rotate in a direction while standing in place
or while using an attack animation being able to turn
or get a little boost of forward velocity to make the strike look more impactful
the same scripts i use for my players animation events are not working for the AI when it comes to anything movement related (turning, pushing, launching) it is just a basic NavMeshAgent
it seems like applying Velocity to a navmeshagent is useless
As long as the agent updates position and rotation, you won't be able to move it properly in other ways.
I think I read somewhere you need to turnoff navmeshagent when you want to do that
yeah i disabled nav mesh but i still cant push him forwards even with the navmesh disabled
@tardy junco
How are you pushing him?
velocity.x = (character.transform.forward * _pow).x;
velocity.z = (character.transform.forward * _pow).z;
nevermind, i knew it was something stupid lol, i wasnt calling the move function on the character controller for the AI only the player
thats why my animation events werent working
Hi, I used polarith AI from the asset store but couldnt make it work. This was a month ago. What do you guys use for AI? Preferably free since im not making anything serious with it just now
There were a couple free AI tools that seemed to be OK. Here are the free ones https://assetstore.unity.com/tools/ai?category=tools%2Fai&free=true&orderBy=8
Hello, first time using navMesh here. I have a simple follow script where the enemy will follow my character. The issue here is that if the character is jumping the enemy won't follow because the destination is not on the navmesh (it's above it)
The solution I see is casting a raycast down from the player to know the ground position of the player
My question is if it's possible to do a raycast that has that only hits navmesh?
I've seen the AI RayCast but it doesn't seem to do what I want
Or if there is a simpler solution π
There's a method that samples the closest navmesh position.
Yes I'm already using it but it's not working as intended because of height differences.
Here's my code
How do I paste code? π
do
{
NavMeshHit hit;
Vector3 interationPoint = player.transform.position + interationVector * currentDistance;
hasDestination = NavMesh.SamplePosition(interationPoint, out hit, maxDestinationDistance, NavMesh.AllAreas);
if (hasDestination)
{
_agent.SetDestination(hit.position);
}
else
{
currentDistance += iterationDistance;
}
}
I'm using this because some parts of the level aren't walkable but I want the enemy to move to the closest position that is walkable
you could use the filter argument to filter out areas.
Why is interationPoint so convoluted?
What is it supposed to be?
oh I forgot the while
but basically what I'm doing is that I start to look to go to the player position. If I can't, I move closer to the enemy and try again
iterationPoint in the beginning of the loop is = to player position, then it starts moving towards the enemy
why not just increase the max distance?
I was afraid it might move the enemy to the other side of walls. I have some thin walls on my level that the player can walk above it (but enemies can't)
then assign them to different areas.
Anyways, put some debug logs and drawrays in that loop to see what's going on.
Dumb question, but how do i use AStar for flying AI?
Hey! I'm making a zombie apocalypse style game and I've just added navmeshagent onto my zombies but now they walk inside of each other. I looked online where it said to add navmesh obstacles onto them but now the zombies move at super-speed and just sort of sorry the player on their heads? Any help with be great. Thanks π
probably going to have to use a 3d grid
I couldn't find an option for a 3d grid though, unless I'm just missing something
@safe fiber You should specify if you are using an existing solution (and which one) since AStar is the name of a general path finding algorithm.
I meant as in, just imported A* into project and atleast on the graph part where you'd usually set up nodes and whatnot, i did not find any "aerial"-like settings
https://en.wikipedia.org/wiki/A*_search_algorithm This is A*
https://assetstore.unity.com/packages/tools/ai/a-pathfinding-project-pro-87744 This is A* Pathfinding Project asset.
A* Pathfinding Project does not support 3D graphs afaik
Ah apologies, i didn't understand your previous question correctly. Yeah, i meant the unity asset, not the algorithm.
If it's as you say, i guess I'll have to try find some other means for aerial pathfinding since no 3D graphs
A* Project's forum is a good resource https://forum.arongranberg.com/t/3d-grid-or-3d-point-graph/2554/2
I'm working on a tower defense game where the path the enemies takes is made longer by placing towers. Using navmesh to path the enemies to the end. Problem is that I can't seem to figure out how to check if placing a new tower would completely block off the destination. Thought I could place the tower down, check if the pathStatus was pending or invalid, and remove the tower if it was. Seems that the new paths(and mesh carving I think) are calculated for the next frame, which won't do here. Am I missing something simple? Hoping that is the case.
I figured it out. I had to use NavMeshBuilder.BuildNavMeshData and NavMesh.AddNavMeshData and some other things to get required arguments.
Just sharing for fun. Been having fun with this goal/motivation based AI. Uses a definition system that makes it very easy to adjust and extend behavior. The soldier's goals are to kill all zombies as primary and to reach a destination as secondary. They use temporal motivation theory to determine the next task to execute.
I think I forgot I was going to make a game at some point and just went overboard...
Hello Guys
Can you plz tell me what should I do when the player will die in my game. Which type of GUI should I create when the player will die . Plz help me
Probably best to be as clear as possible and put the words YOU DIED on the center of the screen
I am looking to create an enemy that adapts to the player's behavior and tries to predict what the player is going to do. What resources and papers can I look to for creating such a machine-learning model?
There is a dedicated channel to machine-learning and this tutorial is great https://www.youtube.com/watch?v=zPFU30tbyKs&t=2349s
π Let's learn how to get started unlocking the POWER of Machine Learning AI in Unity!
π¦ Unity Machine Learning Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53vehwiN_odYJkPBzcqFw110
π Get my Complete Courses! β
https://unitycodemonkey.com/courses
π Learn to make awesome games step-by-step from start to finish.
ML-Agents GitHub https...
Just keep in mind it is nearly impossible to train in real time right now
Machines do not learn like humans do. Humans link learning new processes to related already trained NNs so that we can learn a new thing in just a few attempts. A machine is still just throwing random numbers around and working from scratch on everything, never linking to previous NNs. So it must run many many iterations and be done offline.
how do I modify the width and depth via a script
this is the a star pathfinding system
Pathfinder is a script right? Are you using someone elses script? Will have to see if they made a public function to set the variables
Code Monkey's Dots A* system is far superior, the problem with a function based A* system is you will have to run it on it's own threads and wait for it's return, it is just too slow and if you want to get many paths in one run of Update your going to get stuttering
I already have a state machine setup, but I have questions about the actual design of the AI. I'm making a boss enemy, and I can't figure out when to make it do what. Like, how often should it attack and retreat? If I have multiple ranged attacks, how should it interchange between each other? Should the timing for the attacks be fixed, or based on stuff like the player's position? How should it know which attack to do? Thanks.
@marsh scarab This is all what will make your AI unique. These are called Decisions. You have Decisions and Actions and it can be represented by a tree. You can even move your state machine into a visual decision tree and it makes it so much easier to troubleshoot when you create a bug in the logic. One branch of the tree might be when a player is distant, while one branch is when the player is close, etc
If your not sure what your enemy should do, put yourself in his shoes and ask yourself, what would I do?
Help i dont understand why but sometime this doesnt work when i reset my variable CurrentWp to 1 my agent dont care and go to the if
if (myAgent.remainingDistance <= 0)
{
myAgent.SetDestination(Waypoints[CurrentWP].position);
CurrentWP = CurrentWP + 1;
}
if(CurrentWP >= MaxWp)
{
CurrentWP = 1;
}
Not sure how useful it'll be , but here's a git repo showcasing procedural navigation
its ok i found a solution but my agent is dumb he fail a lot trying reach the Wp
Does anyone know why an agent would not take any actions?
idk
That's given the assumption that you want completely unsupervised training on difficult NN structures. Which would probably be hard to translate into fun game AI.
@flat shard you could theoretically model your AI's future prediction with Bayesian networks, they can have a relatively limited number of parameters to adjust and might be something interesting to take a look at.
Are you comparing the distance between the three dimensional axis or on a two dimensional plane? If you have three then you need to remember that the Y axis can interfere in how close your two agents think they are.
I have a question. How are FPS enemies usually done in terms of AI in AAA titles?
Is it FSM? ML?
If you need an example: Doom Eternal or Hitman (since they have different styles)
I think Behaviour Trees are still something in indie games, but I guess AAA have moved to HTN, and the like
It's sometimes hard to qualify, a big studio will work on its own implementation and mixing BT, HTN, Utility scorers, some FSM, and so on, depending on how high or low level the decision making is
Recycling said AIs for next games and adding little variations, until someone finds a new interesting pattern and share/write about it
Dunno for the 2 specific games you mentioned though. I'd be curious to know for Doom eternal
No AAA studio uses ML yet (unless Blizzard with AlphaStar AFAIK)
It's a long story but it's not suited for studio workflows
The key point being, IMO, that a FPS bot can be VERY dumb, because more often than not it's expected to die a few seconds after you see it
Hope my answer sticks to the topic
Can someone help me with my coroutine, Im trying to make a charging type enemy in a 2d game (the move faster every 5 seconds for 5 seconds)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
can u be specific??
every 5 seconds the enemy charges at the player at a faster speed than their regular movement speed for 5 seconds
@finite rock
float Speed = (1 + Mathf.Round((CurrentTime - StartTime) / 5.0f)) * SpeedMultiplier;
that's all you need
set the StartTime when the charge should star and keep tracking the current time every update/frame or maybe a timer then get the time difference and divide it with 5, you will get how many times the enemy has to move faster, then just multiply it with the speed
nothing fancy needed for this logic just simple math
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
@wispy minnow
Serius question. Where do you pull these terms from like HTN etc? I have never heard of it π€ Want to build my own source of information stream so i can keep up to date. This is somethin new thought no?
thanks!
Years of keeping an eye on the topic. Reading books, watching videos, looking assets on the store, and so on
Hierarchical Tasks Networks are pretty new and still a thing
Must read: http://www.gameaipro.com/
Home of the book Game AI Pro
Must watch & subscribe: the YT channel of Thommy Thompson, "AI and Games" https://www.youtube.com/user/tthompso
What is AI and Games?
It's a show aimed at helping the world better understand how AI makes for better games and games make for better AI.
Who is the Scottish man in the videos?
I'm Dr Tommy Thompson. I work as an AI researcher and developer as a consultant in the video game industry.
When are new videos released?
Wednesdays - at least once a...
it's a $60 book :C
Knowledge is free imho, and the writer of the book also learned it from somewhere i guess, he didn't invent it, or did he?
ALL the talks of Dave Mark, for UtilityAI: http://intrinsicalgorithm.com/ search his GDC Vault videos
It's multiple authors from the industries, and artciles you can find probably online for free
I just find it nice to have it all compiled in a paperback book
@finite rock it's all free on PDF format if you like reading online
(gameaipro)
Then there's multiple papers if you can find them
its a good starting point thank you
i'll dig deeper if something catches my interest here
But just the 4 or 5 references i mentionned are great ressources
yeah, enough to dig for a start
Hey guys, I originally asked this in the tech channel but I think it's more appropriate here:
Anyone ever done pathfinding where you want the pathing units to stop at certain nodes along the way if they are close enough?
Like you want the units to go from a to b, but you'd also like them to stop at c if it is not prohibitively out of the way
I imagine it'd be A* with some tweaks to the heuristic but I'm wondering if there are established approaches before I take a crack at it
The use case is a unit that is kind of like one of the traders in civ games. His goal is to take things from A to B but if he can stop at an outpost along the way he should do so because they act like checkpoints in my game
I think I'm just gonna modify the heuristic to be more costly the more tile the units travels without passing through an outpost
I love navmesh
Why does it need to be implemented in the pathfinding system? It should be part of your particular ai behavior. If you were using a navmesh for example, you could calculate a path first, then see if any of the points along the path are somewhere where you want it to stop, then save the original target and set destination to the intermediate target.
I have my own pathfinding solution. It would be great if I could do this without touching the pathfinding itself cause I don't want to complicate the system too much but I'm not sure how
If it's along the path then that's good but I wanted to program it so that the path can deviate a little to traverse an outpost
So long as the deviation isn't too great
I could do this by making my heuristic a delegate that I can pass as an argument but I'd also need to make some add some way of allowing the path to pass through these outposts (which it usually can't) so I'm open to any ideas that don't require me to reimplement the pathfinding
I'm probably doing a pretty poor job at explaining this so I get it if it's a weird question. That being said, if anyone knows what I'm going on about I'm up for talking about how to architect this solution
I feel like I should just add delegates for the calculating the cost of every move and the heuristic at every tile. Then I could control which tiles are accessible using the former.
Hello, I'm working with "mlagents" with unity at the moment, but I ran into a problem.
Problem: When I call the function "AddReward", the Cumulative Reward does not go higher then the value i put in the "()"
for example:
AddReward(0.1f); //--- I add a reward
Debug.Log(GetCumulativeReward()); //--- Print Cumulative Reward
When i call this function it just jumps to 0.1 and stays there, even if I call it again, and the same if i put "-0.1" in (it jumps to -0.1 and stays there)
What i have treid:
- Made sure I called "AddReward" and not "SetReward"
- Used "SetReward" and just put "GetCumulativeReward() + 1" in the "()"
Both did not work
any fixes?
Im using a navmesh agent on my enemy, but it faces the wrong way when chasing my character, why is this?
I have tried rotating the prefab, but this hasnt seemed to fix the issue
hey so when my agent chases me theyre partly in the wall, does anyone know how to fix this. I made the walls static and the agent doesn't seem to be going through them, only touching them
good day,
is there some way, to get the path between start and destination AND to get all area costs OR all areas that are passed?
because i only found stuff on google that returns true or false, but i need the all the costs or all the areas that are passed.
are there some functions for that?
edit:
i have a small "dungeon" with 3~ rooms which are connected with corridors.
the corridors and rooms have different Navigation Areas.
i want to tell my agents, they are only allowed to move from 1 room to the other room and not more (turn based game)
what is the best way?
maybe i just go in the wrong direction with my first idea
oh and would be great if u mark me, so i get notified when someone answers π
@lapis jetty Trying to figure this out right now. I am trying to convert the pathfinding to a floodfill, but I don't know what to set my initial hCost to when setting up my path node array. Normally the hCost is based on an end position. I just want to keep going until all tiles have been removed from the open set
I got it!
All you have to do is take the A* code and set the initial hCost to int.MaxValue just like you set your initial gCost. Then make sure not to break your open list loop if the current node = the end node. In fact after taking away that reference, there is no need for an end node reference at all
Here is my floodfill code, which was just a modification of the A* code https://hatebin.com/azrzqgmqdb
There is still a problem, when I tested starting at 5,5 it worked, but if I start further out on the grid, it does not fill the entire grid
If you just want to do flood fill, isn't a breadth-first-search sufficient? A* seems overkill. (sorry haven't peeked at your code to see what modification you did)
Well I have this cool A* system already built to check for things like walking through touching corners, etc. So it is more of a pathfill I guess
Also it is the best performing A* routine I have ever used, so using at as a flood fill is nice to keep any frame drops
It is working as it is because I just figure if a tile is outside of the result then it is too far to walk to anyways, but that would not work for everyone.
I need help with a reward function for a car AI using mlagents
It can move forward and backward and it has a brake and it can turn left and right and I have checkpoints around the map but the ai just holds brake the whole time
Rarely moving forward
I punish it for braking and moving backward too much but still itching
And I assume you reward it enough when distance increase ? you might have better luck sharing code in #archived-machine-learning
I started learning GOAP as my first AI system to implement
But it seems dated to 2012
Does anyone have a recommendation of a 2018-2020 AI archicture to learn and build for a first AI system to implement?
Start from state machines or behaviour trees. π
I got state machines down pat
But id rather not have to rewrite a new agent every time I want to make a different type of agent
Im looking for an architecture that is more scalable and reusable
Didn't you say it's your "first AI system to implement"?
Let me tell you a story. around 2 years ago when I was starting with gamedev I had huge ambitions. I though I'll create the best rpg/strategy game of my dreams that will of course implement the most realistic AI. So I went with GOAP. There's an open source implementation called ReGOAP on the asset store. At first it worked great, but at some points I started encountering bugs that I couldn't explain or debug, because I couldn't understand the source code. It was just too advanced for me. I ended up ditching that implementation and tried another architecture: HTN(Hierarchical task network). But it ended up the same way as my GOAP attempts. Since then a lot of stuff has happened and I had to abandon that project, but recently I've been working on a real project that I actually getting paid for. And when implementing the ai I understood one thing: if you can get it working by simpler means - do it.. I ended up using a simple state machine implementation and it works wonders. It's true that I don't have a lot agents types, but if I needed I could make the solution more generic and make it easier to add different agent types.
Point is: don't chase for "super advanced new AI technique" that is out a month ago. It is not solid, you'll have to implement it yourself or pay money to other people, you'll have to learn how it works. Consider if your project really needs a complicated system that you'll have trouble debugging, or can it be implemented with a simpler solution. More importantly, it's not just the tools that you use, but HOW you use them. A good state machine implementation and proper use case could be better than a very advanced GOAP, HTN or any other advanced AI architecture that is not use properly.
P.s: GOAP is considered pretty fresh. It's not like we get new AI architecture every year and it doesn't mean they come to replace older solutions.
Ive been following along with this tutorial
In this project you will learn about the Goal-Orientated Action Planning (GOAP) architecture used to create intelligent agents that can set goals and plan at achieving them. Unlike Finite State Machines, actions and states are uncoupled, making for a very flexible system. You will build a GOAP system from the ground up and implement it in a si...
It boiled down GOAP into really simple mechanics
Its a little frustrating to re-bake a new Planner when divergent levels or use cases come up
But its not exactly hard to understand or anything
P.s. Is a state machine really an AI? Its just been the thing I use to control states for any type of thing im making
P.p.s if you cant do something with an Enter, Update, and Exit, do you really understand what you are doing :P
AI is what makes your agents move in your game and do things. If you just have sequence of if statements in update that does it, it's already ai.
Oh, the concept itself is easy, I completely agree. But when you get down to details or try to use someone else's implementation that uses interfaces/inheritance and multithreading heavily, you can get lost easily. Especially if you've just started coding.
In my case it was probably a racing condition due to the implementation using threads, but it was so long ago, I can't remember now.
Then you make it generic enough, to fit all cases. But I agree, that there are situations, when a state machine might not be enough. GOAP is a good architecture, if you get it to work properly.
Im only really considered writing my own, I like having control over my pet implementation
Keep it simple, only have the essentials I need, use my standards and conventions, make it something I can really wield
GOAT is great so far, but its not scalable up to hundreds of divergant agents
But at least the re-use factor is like 6 out of 10
Compared to a state machine where the re-use factor is more like a 3.5/10
I'd say it all depends on your implementation. If you find that you can't reuse something, it's probably too specific and you can make it more generic.
I remember following that course myself. The reason why I decided to use an asset after all was that this course and many other learning resources didn't cover backwards planning which, if I remember correctly, is way faster.
I think the critical failure here is a GOAT planner, as you have to rework it often, I was hoping to learn something that could add a bit of architecture mix to make that part more reusable
Why would you need to rework the planner? It simply finds a path to the goal, where path nodes are actions.
It's as generic as it can get.
What you'd need to reimplement with GOAP are actions and goals.
Maybe im confusing two aspects of goat into one thing
Im talking about the process of creating graphs conceptually for your use cases that you then turn into actions and goals
Id think a decision tree would be more flexible then this part
Donno. Is seems pretty simple to me. Let's say you have a goal "satisfy hunger" that requires "food eaten". Then you have an action "eat food", that requires "food" and satisfies "food eaten", and actions like "Take food from storage", "Hunt for food", "gather food", "beg for food". All of them would give you "food". You add the desired actions and goals to your agent and it will plan the actions to get to the goal, for example: "gather food" - "eat food".
You can make as many different actions and goals as you want and put them in different configurations on your agents. That's as modular as it can get.
It was like that at the start
But now I have over 300 actions and goals, and tweaking and messaging them to get some realistic simulations is becomming unweildy
Then perhaps your actions or goals are too specific.
I think my game has too many stages
I don't know what actions and goals you have, but for example if you have goals like gatherFoodTypeA and gatherFoodTypeB, the amount of actions will explode very quickly.
Maybe I could use some sort of reinforcement learning to weight the acitons better
Just thinking out loud
Re-jiggering my design documents to figure out weighting better sure is a pain
Machine learning is a completely separate field. Might be more complicated to get into it, than fixing your GOAP implementation.
If I used a decision tree, then weighting actions is no longer such a barrior
But then its not really goap any more
You mean behavior trees? Well, as I said, if a simpler solution works, go for it.
GOAP is really a dynamically created behavior tree.
You know
I just realized when checking all the states
This might be a great spot for a lambda operation
Well
I will just figure out wieghting iteratively for now
Im back in code now lol
is it possible to tell a navmeshagent it can't use an area no matter what, even if it can't get to its destination otherwise?
@tardy junco totally agree with you. I was fortunate to do my first AI with FSM, because even though it is harder to maintain due to spaghetti, it is still something that you have more control, which is of course intentional -- in FSM you specify exactly every possible decision/action that can be done, and in what order, as GOAP creates it in runtime, making it way more obscure to understand/debug it at some times
PS: I'm not complaining about neither FSM or GOAP, they just have their differences and that's it
By the way, I'm not sure if you already tackled this, but I'd suggest you to use HFSM (Hierarchical Finite State Machine), which is super useful on reducing the amount of spaghetti graph, because the whole package of "Fight Sombody" states can be encapsulated inside another state, so it cleans a lot the graph
Also something else that you might be interested in (or already knows about) is Utility Theory, which is a mathematical AI model where decisions are done based in math curves. It is super interesting, I suggest you to look at some GDC talks on the matter, if you didn't yet
Haven't heard about HFSM. I'll have a look at them, thanks! I remember utility theory from political studies back in university, and also remember I read somewhere about it in the context of AI, but I don't remember the contents. Gonna have a look at it too.
@tardy junco For UtilityAI, don't miss the work of Dave Mark (http://www.intrinsicalgorithm.com/) and Kevin Dill (AI engineer for the military at Lockheed Martin)
That's the GDC vault talks @sonic rain is talking about. Dave M is head at organising most of these AI talks
Yeah Mr. Dave is the big reference on Utility AI π
@worldly trench If i read well and I'm not off-topic of your concerns, don't be afraid to mix multiple patterns where it helps you π
I made the mistake of diving right into GOAP
But instead I should have focused on how wieldable the modules of the AI architecture are
A hierarchical task network planner is no good if tuning the weighting takes up more time then implementing a game
Design a game with balance is definitely not easy
And I am starting to realize
It's interesting and rewarding though ?
That when an AI clearly demonstrates a personality in its decision, its more fun then an AI that demonstrates "intelligence"
True that
Yeah, im learning a lot about architecture
and you can expose the settings your AI use to the player so he understand them, helps making your AI more believable in the decisions they make. Some games do that very well
Thats a interesting idea
I should probably replace my planner weights from world and local situations to something more like personality traits
Hmm
Thats very nice
Crusader kings III exposes AI personality very well too
π€ not replace. You still want your AI to *sense the environment
personality adds a layer and mutates the perception
to add even more variation and unpredictable behaviour to your agents
Any AI framework in a nutshell: SENSE > THINK > ACT
Im thinking maybe a Spatial UI that when highlighting over a enemy you see things in the weighting
Could be nice
Very nice
Yep, if it helps the player understand how your AI behaves, so he can learn and understand the systems of your game, yeah go ahead π
It will make it easy to debug also
I could really use some data visualization of my states and decisions
that takes part in the fun of mastering the game, and eventually overcoming it
yeah debugging too, but remember you can also make editor tools for that π
How I can use a class from an embedded package?
I have this class from Digital Human:
and when I try to use it like this:
using System.Collections.Generic;
using UnityEngine;
using Unity.DemoTeam.DigitalHuman;
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
GameObject snappersHead = GameObject.Find("SNAPPERS:Head");
if (snappersHead != null)
{
SkinAttachmentTarget sat = snappersHead.GetComponent(typeof(SkinAttachmentTarget));
Debug.Log(sat);```
It gives the error: The type or namespace name 'SkinAttachmentTarget' could not be found (are you missing a using directive or an assembly reference?)
damn, wrong category..
I have a really basic enemy AI where they just move towards the player. How can I stop the enemies from clumping up? I am a beginner programmer. Can I maybe force them to stay a min distance of 50 pixels apart from each other?
I'm not sure what an embedded package is. Is it the same as a separate assembly? Is it in your project? Did you import it via unity? Does it have an assembly definition file?
Is it 2d? How are you moving them?
I am making a 2d game and setting the positions of each of the sprites using Vector2.MoveToward(current, target, speed).
I noticed that when dodging the enemies, they tend to clump into a single super powerful enemy. I read an answer on Stack Overflow but didn't understand it at all so I came here. Can I make the enemies stay a minimum distance apart?
You'll need some kind of algorithm that will move enemies apart. Like flocking algorithms.
For that you'll need to make sure that your enemies are aware of each other. Are the enemies controlled each from its own script or do you have some ai manager that updates them?
Each are controlled by their own script.
I just followed BlackThornProd's Follow AI tutorial. How would I make all of them controlled by one script?
You could have a reference to all of them in one script and call some functions on all of them in update or something. But you don't have to do that.
If it's separate scripts, you could use a static list of enemies in the script itself, for example. Or you could overlap circle in some radius around the enemy. Or, if they have a collider, you could use collisions(but that wouldn't work create with Vector move towards). Anyways, you need a way for your agents to know what's around them. When that's done just write some simple avoidance algorithm.
anyone good with NavMesh could spare me 15 minutes?
Just ask your question and someone might answer.
I need help with all of navmesh from setting up to bake to setting agents and stuff
so uh....
What's the problem?
i dont know anything. just managed to setup the mesh, need help with cost and stuff
How do I apply Costs and stuff
Costs? Never used them. I think it's when you use additional areas in your navmesh.
I'm sure some tutorials cover that.
thing is i cant find any explaining them well
I can see at least a few with a quick google.
There's also a manual page specifically for that:
https://docs.unity3d.com/Manual/nav-AreasAndCosts.html
Im looking for notes/a review of this sweet AI architecture I have in mind
Would anyone be up? Its just two pages
Hi. Maybe, somebody, knows, what algorithm is used by Unity for NavMesh generation?
Is it something like Mononen model or Multiple-Layered NavMesh?
For generation..?π€
As far as I am aware, its a black box to everyone
is there a way to make the peds walk on an offset of the path they're on?
ok so i've finally come back to ask about a certain nav mesh agent issue that i have, when enemies spot the player and they're on a different platform where they can't jump, they seem to leave their designated area of navigation, as in they float in the air... i have had this issue for a bit now
Curious what types of databases you all use for development?
man unity really needs to use colliders instead of meshes for navmesh baking
it makes absolutely 0 sense
like what if i have weird meshes that causes weird navmeshes? do i have to make all the meshrenders visible every single time i bake a navmesh?
it's a very painful workflow
so i keep getting this error on unity with my navmeshagent that says this:
"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:set_destination(Vector3)
i really cant seem to find a solution here
i've even tried putting the enemy slightly above the navigation area as someone stated but nothin worked
Assuming you've bakes your navmesh and the agent is really positioned on it and has that are in walkable mask, is the agent enabled?
Can you take screenshots of the agent so that it's gizmos are visible relative to the navmesh?
the agent is in fact enabled and you are correct positioning is fine, the navmesh is baked, everything is set
here are the two screenshots
cause either he floats in midair or sinks to the other navigation area that he should NOT be allowed to access otherwise he starts moving weirdly
usually this happens after he spots the player and there are no walls to stop him
so basically if the player leaves his area
anyone that is not on a floating platform do not have this problem
First, I don't see the navmesh properly I'd like to see it from the second screenshots perspective.
Second, you agent height is 0.01??? Why?? I'm sure that could be the source of the issue. It doesn't seem like the model is 0.01 units to me.
I mean in the bake settings.
well i changed the agent height back to 2 already
and yet it still doesnt work
and here
And in your agent it's set to 6?? These values should correapond imho.
so change radius to 0.2 and height to 2 like in the baking area?
Yes.
Then you can level up your debugging by pausing the game right after the error and checking the navmesh agent at runtime.
I think you can use a try catch on that Set destination line and Debug.Break if in the catch.
the catch... explain that part?
Try-catch block allows you to catch errors and respond to them in the code. Look it up. It's a feature you should be using from time to time as a coder.
kk
i will look at that after i try what i just did for the matching up the radius and height to the baked agent
Google c# try-catch.
okie
and also it does kind of look like he isnt going off the platform but lemme disable a certain moving platform animation next to him to make sure he doesnt
ok so i realized that as soon as the enemy goes off the platform when spotting me, this appears:
"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)
EnemyAI:InFront() (at Assets/EnemyAI.cs:106)
EnemyAI:Update() (at Assets/EnemyAI.cs:50)
so clearly he is for some reason still disobeying the navmesh with his code
Does it have a dynamic rb?
i was told to remove the rigidbody from someone else as it would not work well with the navmesh
At the very least set it to kinematic.
i kinda forgot what that does since i have not used it in a while
Basically. disables physics calculations for that rb. You shouldn't let both physics and navigation control your object at the same time.
unless you're doing some custom blending.
Yeah gravity too and any other forces.
kk i shall try that
he still floats off of the platform
doesnt seem like it made a difference
@tardy junco i mean i could show you the EnemyAI script if you wantr
Did you pause at runtime as I suggested?
yeah
Sure upload it to hatebin or something.
ok
and like said, this showed up as soon as they left the platform
Not completely sure, but agent.autoBraking = false; might be a problem? Never had any need to use it.
The fact that your agent goes out of mesh bounds probably means that it's not breaking.
i guess so
This could also be a problem: this.transform.Translate(0, 0, Time.deltaTime * speed2);
If you're using an agent you should be very careful about applying any kind of movement manually.
well actually speed2 is the one that is meant to stop the enemy
speed and speed1 are the moving ones
Doesn't matter. Stopping is also applying some movement. You should avoid any and all kind of manual movement to the agent, unless you're 200% understand how it will work out.
Another thing is to get rid of root motion. It can also apply unwanted movement to your agent via an animation.
make sure to enable gizmos when you debug. We can't see the actual position of the agent like that.
getting rid of speed2 just makes them dart in random directions... ---
So here's the summary:
- don't disable agent's autobraking.
- disable any source of movement aside from the agent itself. This includes:
- setting rb to kinematic.
- making sure your animator doesn't apply root motion.
- getting rid of all the transform.Translate or similar commands.
the rigidbody already is kinematic, the animator does NOT apply root motion, and without speed2 the enemies chase the player weirdly
should i turn off use gravity?
if it's kinematic it shouldn't be affected by gravity anyway.
And I said get rid of all transform.Translate. Not just the ones where you use speed2.
If you disable and reenable the agent, make sure it's on the navmesh at that point. You could sample the closest navmesh position and setting the character pos to that position every time you enable the agent.
the only transform is speed2 at the given time
I see quite a lot with speed and speed1 in your code too. I don't have time to look thoroughly through your code, so I can't be sure whether they get or don't get called at that time. There's also a possibility of a bug where it is actually called when you don't want it. That's why commenting them out and testing is a good thing to try.
speed and speed1 is when they are currently chasing the player or they are going to a waypoint, that's it
the only time they leave the platform is when they have speed1 active... so that could probably mean that speed1 does something to the navmesh
a.k.a. when they see the player
getting rid of speed1 seems to make them not rotate fast at all or even run fast
so i need to think of a way for speed1 to not lead the enemy off the platform, but also have the enemies still have their normal speed
try playing with acceleration it seems to have an effect on the rotation speed too.
okie
alright it is not working at all without speed1
they dont move when they see the player
are you actually setting the destination of the agent?
yeah, it sets to player when they see him but they do not chase after him due to the lack of speed1
Is that destination on the navmesh?
cause for going for waypoints, since speed is in there, they go there successfully
it is in the script
agent.SetDestination yadda yadda yadda
is the destination position on the navmesh or very close to it?
for what
For set destination
so you mean......... uh... im confused
SetDestination takes a vector3 position, right?
no it's just this in the script:
agent.SetDestination(player.position);
I'm asking you if this position is physically on a navmesh?
no it's anywhere
Well, that's the problem.
if they see the player in the raycast and in their line of sight they will try to reach them where they eventually break through the nav area
are they supposed to break from the nav area?
nope
clearly not, if they are floating in midair then hell no they aren't supposed to
Then follow the steps I mentioned a few messages ago, and they will stay confined to the navmesh.
as for not following, you could try sampling a point on the navmesh and setting that as the destination.
but that is where the problem is, if i dont have speed, speed1, or speed2 they dont move period
I already explained you why they don't move. moving them manually adds to the problem, not fixes it.
manually??
Manually. As you did with transform.Translate.
unless you meant this
which i dont know how to do
Instead of setting player.position as the destination, sample the navmesh for the closest point with SamplePosition and then set the resulting point as the new destination. https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html
the issue with me when it comes to the scriptreferences, for certain ones if they are not used directly in my script by someone else who knows how it works already, then i dont know how to properly put it in... better yet i dont know which one to use
like which one do i even use in this reference, where do i put it
There's an example on the page.
Try to understand what the function and each of it's parameters do, and you'll be able to use it without problem.
the closest one i can think of is maxDistance
but i dont even see it being used in the example script that is shown
Of course it is. NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas)
1.0f is the third argument and the only float. I don't understand how can you not notice it. π
so i use that on a line in if(state = "pursuing") ?
you mean in that if block?
yeah
Yes, check if it returns true. If it does, you can use the hit position as the agent's destination. Otherwise it couldn't find any navmesh position in the designated radius.
so how does the if statement look for if true? and does it trigger the player position if so?
trigger? It will look exactly the same except you'll use the sampled position.
if(SamplePosition)
Set your destiantion.
so
agent.SetDestination(player.position); ?
but replace player with SamplePosition?
No, do it outside in an if statement to see if you got a position or not.
so what i just said... but outside of the pursuing if statement
If(sample position)
set position as the hit result
else
throw error or handle in a different way
i notice another issue
randomPoint
the example shows a whole new bool statement with {} and yet i cant do that
nevermind
i got the thingie
wait... i already have a hit section at the HaveLineOfSight statement bool where it checks for if the tag is Player
how the fuck am i supposed to do this
it can be any name you want.
both.
so i can put the thing in the havelineofsight and have the same hit?
even if the hit is a RayCastHit?
No. They are different types. The navmesh one is NavMeshHit.
i renamed the navmeshhit to booper so that is solved
i dont get what the hell im doing but here is where i am at
You don't need random point. you want to sample the position of your player.
so replace randomPoint with player?
And it's not the place we were talking about.
how did it get to HaveLineOfSight method? lol
Why would that be related?
I told you where. Where you set the destination of your agent. agent.SetDestination(player.position);
instead of player.position, you want to set a destination on the navmesh, right?
and i told you that is inside another bool
What is inside another bool? How can something be "in a bool"? π
the fuckin bool InFront() { }
This is a fuckin method or function(that returns a bool), but in no way you can call it a bool and expect other people to understand that.
That's the part about what it returns.
but now it isnt working due to the result thing
Either way, why is it in there? I think I was pretty clear with that message:
set position as the hit result
else
throw error or handle in a different way```
what result?
oh my fuckin satan, the result that came with the example
result in the example is just and out parameter they define in the function. You don't even have to use it like that.
The only part you should really care about is this:
if (NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas))
{
result = hit.position;
return true;
}
you can ignore the return and setting the result variable
well it is causing an error just by existing
all you need it to use is that hit.position for your destination.
Then fix it.
Since you're using result as an out parameter it has to be assigned in the function.
what part of it
WHERE
ANYWHERE before returning from the function.
Because you don't listen to me. You don't even need to use result.
Not saying what an error is is really unhelpful too
well then you haven't assigned result before returning
if it's the same error it's the same problem
i dont know how to assign it
It must be set in every independent scope. IF your code goes through a function, gets to return and sees that out parameter is not assigned, it will give your this error.
cause im a dumbass
so not Vector3.zero??
that would be fine, but you're clearly just not assigning it before a return
it's skipping the assignment logic for a possible execution
all execution paths need to have result assigned
That will work. You could also assign it a default value once before the branching, instead of doing it before every return.
so at the very beginning of the function or...
yes. Before all the if statements begin.
ok
I like to assign it once before each return as it makes it clear when you've missed some logic
I agree, but it this case he doesn't even need it.
alright i did that... anything else?
Why is there a for loop, why is it after setting the agent destination. You should be using the result if the Sampling as the destination. I think I mentioned it like 5 times now...
it's because it was in the example... -_-
Example is there for you to understand how to use the function. Not to copy-paste the example.π€£
They use it for a completely different thing.
how do i type the if statement as the replacement then
if (SamplePosition...) what comes next
I already explained several times:
set agent destination as the hit result
else
throw error or handle in a different way
the if statement doesnt work at all.... it cant just be If(sample position)!!
That's all you need. 1 if statement, 1 sample, 1 set destination. 2 lines of code.
Of course. It's pseudo code. But I think it's pretty self explanatory.
not really
Why? What exactly is not clear?
what i should put in the if statement with it!
sample position is NavMesh.SamplePosition(blablabla).
I mean cmon man, let's not get down do #π»βcode-beginner level. If coding is a problem, I'd suggest doing some c# courses.
i should not do that because if i try to see it through courses that dont relate to my issue, then im probably going to get stressed to the point of wanting to shoot myself AGAIN
and plus outside of AI i can do literally everything else correctly
i haven't come here a single time with something other than AI damn it!
Yet the issues you're having are clearly unrelated to AI. They are related to missing some beginner-intermediate understanding of c# or coding in general.
and yet everything you try to show me in that sense is something i dont fuckin understand cause it doesn't relate at all to my problem
considering that just about all of it doesnt apply to the code
and my issue DOES relate to AI, it involves NavMesh
It doesn't have to relate to your problem. Is generic coding knowledge. You will need it at some point(like now), if you're planning on developing(games) seriously. And it's clearly related to solving your current issue.
That was your initial issue and I already gave you feedback on how to tackle it. Now it's just up to coding it.
how though?!
how do i code it???
cause what you told me for sampleposition is nothing but bullshit it didn't even change anything
THIS
Very simple. 2 lines of code. Both of them are in the example, you just need to change some parameters.
If(sample position)
set agent destination as the hit result
SamplePosition is a method that takes some parameters. Check the docs page again to see what it does and what parameters it takes.
I'm not gonna write the code for you.
Did you read the description of the method?
yes
i read it multiple times!!
but i guess im such a dumbass that it goes right through my thick ass skull!
Did you read what parameters it takes and what they correspond to?
Okay, so it's simple from there. call the function. Pass in the relevant parameters and you're done!
you act like i know how to do that...
i cant even do the fucking if statement how am i supposed to do that?!
Then I'd really suggest going through some beginner coding tutorials. Calling a function is one of the basics.
if statements too.
i can usually do if statements pretty easily, but every time i ask about it, you make it as bland as possible for me to figure it out
I just don't understand what the problem is.
like if(sample position) isnt gonna do it for me
Why not?
i need to at least know what to put in that and then maybe i can do the rest of this shit
cause if (NavMesh.SamplePosition) does not work
neither does if (NavMesh.SamplePosition(player, out booper, 1.0f, NavMesh.AllAreas))
If I tell you what to put in it it's basically the same as writing the code for you. I can copy paste the method from the example, but you'll have to replace the parameters to what you need.
fine do that then
Why?
Why do you need that line 114??? π
cause you told me to replace the for statement?
I asked what was it for. I meant that you don't need it(nor you need to replace it).
2 line of code:
If(sample position)
set agent destination as the hit result
all you need.
well i got rid of it so...
instead of the 10 that you have from 113 to 122
so put the agent.SetDestination inside of if (NavMesh.SamplePosition(player, out booper, 1.0f, NavMesh.AllAreas)) ?
FINALLY stupid auto-delete
It's not auto-delete. It's bot moderating proper sharing of code.
Yes.
ok.
and of course the InFront that gets called in the update function decides to NOT WORK ALL OF A SUDDEN WHAT THE FUCK???
Define "not work".
red squiggle shit
(Vector3 center, float range, out Vector3 result) this is the cause of it
Yeah. I don't know why you changed your function definition...
cause it doesnt seem to work without center
that is part of Vector3 rando = center + Random.insideUnitSphere * range;
You're probably still doing something unnecessary.
this is unnecessary.
It wasn't in your function before, was it?
I mean before that.
no it was not
you only ever needed 2 lines in your original function.
what is not needed in here then?
Originally it was 2 lines instead of 1. So you only needed to add 1 line.
Was the function originally returning something?
it was originally part of the result thing before i scraped it
the first argument of SamplePosition is the position that you want to sample from. The player position.
then you don't need a return.
so like this? if (NavMesh.SamplePosition(player.position, out booper, 1.0f, NavMesh.AllAreas))
Yes. Now it's only the SetDestination that still uses the player position.
yes
Yes. An I said like 10 times already that it's supposed to use the hit result.
so booper
Yes.
so this is the final result?
Set destination still uses the player position.
yeah? and?
And it shouldn't. That's the whole freakin point of what we were doing.π€£
what do i replace it with? booper?
Yes. And I think you already asked that and I already replied to that...
i thought you meant somethin else
I don't see any other SetDestination in that screenshot.
booper.position or.... what is it
Assuming you didn't mess up anything else in the process, yes. Although I'd add an else statement that throws a Log or an error for ease of debugging.
You might need to play with the distance parameter depending on how far the player is from the navmesh.
alright... i will aim for probably 2 to start
...
the enemy automatically goes off the platform when spotting the player now...
that did the exact opposite of what i wanted
"goes off"?
floats! doesnt stay on the platform he is on originally! acts like the lower ground is at its height!
You're still using transform.Translate in your latest screenshot btw.
comment all that shit out.
glitch moves?
he doesnt move, then he moves slightly
Probably because you set new destination every frame. It stops and takes time to recalculate the path again.
InFront() has to be activated in the Update function
It doesn't mean that SetDestionation has to.
Might also be that else statement.
What is that supposed to be checking?
where do you set the direction?
to see how close the enemy is to the player in order to start attacking
so that is needed PERIOD
Put some debugs in the if and the else to see whether they execute where you don't expect them to.
well apparently the useless shit that i put in that was the sampleposition failed to work 189 times
Then your player position is way to far away from the navmesh. That's also why the agent wasn't moving before.
what is
the navmesh is probably being interfered by the lower level navmesh...
WHICH I CANNOT ALTER IN ANY WAY
because the floating platforms are the same navmesh just higher!!!
what now you're gonna tell me that there's multiple bake able navmesh areas?!
it interferes because what isn't altered is the height of the navmesh in the air from the one on the ground
There is, but I'm not sure that's what you need..?
i mean if anything that could work BETTER
When you sample your position, your player is probably directly above the lower navmesh, so yeah it will be sampled.
indeed
I'm not completely sure, but your game seems to be a platformer?
but yeah let's try the idea of multiple navmeshes that is my only hope and yes it is
a 3D platformer
I'm not sure a navmesh is the most suitable solution for navigation in your scenario.
Do you need your npcs to move towards the player, when it's in the air?
or on a different plarform?
What you could do is check if the destination is reachable first before setting it.
of the player?
I don't understand what's the current problem then?
Yes. That might stop the agent from moving if the player is not on the same platform though.
the problem is that the enemy will chase the player but eventually they will glitch into the lower level navmesh but since they dont do gravity, they float
and that is why if the gravity is on then the enemy will fall to the lowest level and start moving weirdly
Do you want them to chase the player to the lower levels?
no
if i wanted that then i would have made their jumping function by now
buuuut i will save that for a different type of enemy
Then they shouldn't by default. The platform area mesh is not connected to the ground is it?
no it isnt
Then it's probably one of your Translate calls.