Enemy AI

Hi all,
I was wondering if anyone could help me edit a script to make an enemy when in X range run towards me, at Y range start to shoot, and not come any closer to me than Z range. I would also like it to patrol a certain area but I already have that more or less set up.
So if anyone could help me edit the script (shown below) so that the enemy will do what I mentioned above that would be very great.
This is what I have that works:

var waypoint : Transform[];
var speed : float = 20;
private var currentWaypoint : int;
var loop : boolean = true;

var player : Transform;

function Awake(){
waypoint[0] = transform;
}

function Update () {
if(currentWaypoint < waypoint.length){
var target : Vector3 = waypoint[currentWaypoint].position;
var moveDirection : Vector3 = target - transform.position;
var distFromPlayer : Vector3 = player.position - transform.position;

var velocity = rigidbody.velocity;
if(moveDirection.magnitude < 3){
currentWaypoint++;
}
else if(distFromPlayer. magnitude < 20){
velocity = Vector3.zero;
target = player.position;
velocity = (player.position - transform.position).normalized * speed;
if((player.position - waypoint[currentWaypoint].position).magnitude > 21){
target = waypoint[currentWaypoint].position;
velocity = moveDirection.normalized * speed;
}
}
else{
velocity = moveDirection.normalized * speed;
}
}
else{
if(loop){
currentWaypoint=0;
}
else{
velocity = Vector3.zero;
}
}

rigidbody.velocity = velocity;
transform.LookAt(target);

}

Thanks Ahead of Time,
-Jnani

My code would look similar to this:

bool isApproaching = false;
bool isAttacking = false;

const int maxApproachRange = 30; // X
const int shootingRange = 20; // Y
const int minApproachRange = 10; // Z

int playerDistance = distance(player);
if ( (minApproachRange < playerDistance )  ( playerDistance <= maxApproachRange) ) {
   isApproaching = true;
} else {
   isApproaching = false;
}

if ( playerDistance <= shootingRange ) {
   isAttacking = true;
} else {
   isAttacking = false;
}

That helps a little but how would I implement that into the code along with a shoot function.
Sorry for my lack of knowledge of Java I am 14 and have only worked with objective c. Java is a lot harder.

Im assuming that you would make it like this:

bool isApproaching = false;
bool isAttacking = false;

const int maxApproachRange = 30; // X
const int shootingRange = 20; // Y
const int minApproachRange = 10; // Z

int playerDistance = distance(player);
if ( (minApproachRange < playerDistance )  ( playerDistance <= maxApproachRange) ) {
   isApproaching = true;
} else {
   isApproaching = false;
}

if ( playerDistance <= shootingRange ) {
   isAttacking = true;

transform.LookAt(target);
function Shoot() {
//my shooting function would go into here
}

} else {
   isAttacking = false;
transform.LookAt(target);
function Shoot() {
//erase my shooting function, also I would like the enemy to "look away" but you don't have bother
}
}

If you could help me out that would be great “'ll try some more in the morning”.
Thanks A lot,
Jnani

There are many logical ways to combine decision-making and action-taking. A couple reasonable plans:

Option #1: Separate out the decision-making and action-taking code.

aiDecideActions();

if (isShooting) {
  Shoot();
}
if (isApproaching) {
  Approach();
}

Option #2: Combine the decision-making and action-taking code.

if ( (minApproachRange < playerDistance )  ( playerDistance <= maxApproachRange) ) {
   Approach();
}
if ( playerDistance <= shootingRange ) {
   Shoot();
}

In any event, try to wrap lines of code into descriptive function names and avoid duplicating code in both the if and else branches. If you want to LookAt(target) in any case, take it out of the branches. :slight_smile:

By the way, you’re programming in UnityScript which is similar to Javascript. You’re not programming in Java… that’s a completely different language which is more similar to C# than Javascript.

Sorry My bad. I thought that Java stood for Javascript, I stand corrected. So could anyone tell me what could be improved in this code:

const int maxApproachRange = 30; // X
const int shootingRange = 20; // Y
const int minApproachRange = 10; // Z
var player : Transform;

int playerDistance = distance(player);
if ( (minApproachRange < playerDistance )  ( playerDistance <= maxApproachRange) ) {
 transform.LookAt(target); 
 Approach();
}
if ( playerDistance <= shootingRange ) {
transform.LookAt(target);
Shoot();
}
}

I have tried to use the code provided by the FPS shooter project however it does not seem to attack or even move. Im wondering if that has anything to do with the character that I am using (its just a capsule with the AI script attached). While the FPS shooter code doesn’t work, the code I have at the top will follow waypoints and when I come in range it will run right up to me. What I am now trying to do is just make it so the enemy will shoot at me but not come to close to me.
Thanks for any help,
Jnani

I have edited the code to look like this:

private var isApproaching = false;
private var isAttacking = false;

var projectile : Rigidbody;
var initialSpeed = 20.0;

var maxApproach.Range = 30; // X
var shooting.Range = 20; // Y
var minApproach.Range = 10; // Z
var player : Transform[];

function Fire () {
	// Did the time exceed the reload time?
	if (Time.time > reloadTime + lastShot) {
		// create a new projectile, use the same position and rotation as the Launcher.
		var instantiatedProjectile : Rigidbody = Instantiate (projectile, transform.position, transform.rotation);
			
		// Give it an initial forward velocity. The direction is along the z-axis of the missile launcher's transform.
		instantiatedProjectile.velocity = transform.TransformDirection(Vector3 (0, 0, initialSpeed));

		// Ignore collisions between the missile and the character controller
		Physics.IgnoreCollision(instantiatedProjectile.collider, transform.root.collider);
		
		lastShot = Time.time;
	}
}
int player.Distance = distance(player);
if ( (minApproach.Range < player.Distance )  ( player.Distance <= maxApproach.Range) ) {
   isApproaching = true;
} else {
   isApproaching = false;
}

if ( player.Distance <= shooting.Range ) {
   isAttacking = true;

transform.LookAt(target);
function Fire () 

} else {
   isAttacking = false;
transform.LookAt(target);
}
}

However I receive errors and I am not exactly sure how to fix them. (?I added a dot in between the distance and range? not sure if thats right?)

You need to tell us what errors you’re getting if you want help.

No, variables can’t have periods in their names.

First, your code lost a bit in translation…

I declared maxApproachRange as a constant integer. There are a few benefits to this. First, anybody reading this code knows that maxApproachRange can’t change and anywhere they see it they know it means 30. Second, if you accidently try to set it, the compiler will complain you’ve done something wrong. Readability is the main point, but third, such code will usually also run faster.

Besides losing the above advantages, as Vicenti says, maxApproach.Range is invalid due to the dot.

Second, have another look at the integration options I spelled out for combining decision-making and actions. In option #1 I use the boolean isAttacking/isApproaching, but that’s when the decision-making and actions are separated. In option #2 I don’t use the booleans at all. Your code falls between the two, but not in a logical way. The booleans are there, but you don’t make use of them.

Third, you still have lines of code in common between your if and else branches, and that’s generally something to avoid. Factor that code out. Simplify the logic and code.

Fourth, I see code like your function call, “function Fire ()”, and “var player : Transform[ ];” followed by “int player.Distance = distance(player);”. All around this makes me believe you don’t yet get how to program. Which is okay, we’ve all been there… but to get your game working well you’ll need to learn how (since at 14 hiring a programmer is probably out). Investing a couple days into tutorials or a couple weeks into a good book is well worth it. All of this stuff will cease to seem so mysterious then.

Cheers and good luck on your project. :slight_smile:

well, is this your complete code? no update/fixedupdate function or something like that? well, i´m not the best coder but let me give you an advice;)

private var isApproaching = false;
private var isAttacking = false;

var maxApproach.Range = 30; // X
//...and so on

// this is where you declare some variables

function Fire () 
       {
          // bla - one of your own functions
       }

the things which i miss in your code:
all your stuff that need to be checked, i should better say UPDATED, needs a function which is called
function Update()
things like:

///...
function Update()
{
if ( (minApproach.Range < player.Distance )  ( player.Distance <= maxApproach.Range) ) {
   isApproaching = true;
} else {
   isApproaching = false;
}

if ( player.Distance <= shooting.Range ) {
   isAttacking = true;
...
}
}

check out tornadoTwins “how to make a video game” at youtube…

that helped me getting started and to learn some basics. really heplful for beginners!

Solution!!
I just had to take all three of the scripts from the FPS shooter and attach them to my object!!!