I want an AI for an enemy to move through the X and Y axis in random directions. I want a certain location on the X and Y axis which they cannot go so they don’t move there. Do you know how to do this?
1 Answer
1I put together a little simple example for you. I assumed boundaries but if you tell me more what exactly the condition is where your AI shouldn’t move anymore I could help your further. Hope it helps ![]()
//wall Boundaries
float wall_left = 5.0f;
float wall_right = Screen.width - 5.0f;
float wall_top = Screen.height - 5.0f;
float wall_bottom = 5.0f;
//AI properties
Vector2 AI_Position;
float Speed = 0.3f;
//Get two Random values within a Range (Screen dimensions)
float randomX = Random.Range(0,Screen.width);
float randomY = Random.Range(0,Screen.height);
//Create a Vector2 out of the Random values
Vector2 randomXY = new Vector2(randomX,randomY);
//Get the Direction from AI to the RandomXY generated
Vector2 Direction = randomXY - AI_Position;
//Normalize the Direction to apply appropriatly
Direction = Direction.normalized;
//Check that your AI is within your boundaries
if( AI_Position.x > wall_left && AI_Position.x < wall_right
&& AI_Position.y > wall_bottom && AI_Position.y < wall_top )
{
//Make AI move in the Direction (adjust speed to your needs)
AI_Position += Direction * Speed;
}
else
{
//make your AI do something when its not within the boundaries
//maybe generate a new direction?
}
10x "error CS0116: A namespace can only contain types and namespace declarations" 1x "Assets/Enemy AI.cs(24,15): error CS8025: Parsing error" I'm not used to C#. What are the errors?
– CB-TVWhere are you putting the code? Try Declaring the variables inside the class and set the variables inside a function of that class.
– TpkQ91Yeah, I did that. But I don't really know C#. Could you possible show me what to do because I've put everything in a class but I don't know what else to do?
– CB-TVWere you ever shown what to do? I would like to get the script posted above to work too....If anyone can help, please post. Thank you.
– Jayrastaman
Have you tried something already? Random numbers can be generated by Random.Range(). Why don't you post what you think should work?
– softrareI have a script like this: but I don't know how to make it go in other directions, then stop at a certain location. void Update () { print (walkingDirection); walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime; if (walkingDirection > 0.0f && transform.position.x >= wallRight) walkingDirection = -1.0f; else if (walkingDirection < 0.0f && transform.position.x <= wallLeft) walkingDirection = 1.0f; transform.Translate(walkAmount); } }
– CB-TVThere you go :http://unitygems.com/basic-ai-character/ Your guy will go left, right, ahead, after you and others.
– fafase