Ai script donation

got scripts? Need scripts?
Post Reply
User avatar
VZdemon
Posts: 93
Joined: Thu Nov 25, 2010 1:55 pm

Ai script donation

Post by VZdemon »

over the time i had spent learning unity i have come to a conclusion that i want to make a FPS game. so the basics where very easy but then i reached the point where i had to make interactive ai's. so i searched up the net until i found a quick tut' on how to make one in unity. and so i took the code from the tutorial and moded it a bit to make my own. so now i what to give you this code to use in your game or modify it or what ever you what to do with it.

this behavior code make the assigned object move according to a set amount of waypoints and when the play comes near it it follows him and shoots at him util the player has leaved his raduis. this requires an abject with a rigidbody, a gun object as it's child, a bullet prefab&fire effects.

enemy.js

Code: Select all

var way : Transform[];
var speed : float = 10;
var raduis : float = 5;
private var  currentWay : int;
var health : int = 3;
var loop : boolean = true;
var player : Transform;
var Bullet : Transform;
var barrel : Transform;
var gunFire : Transform;
var spread : float = 2;
var minSpread : float = 0.5;
var maxSpread : float = 3;
private var nextFire = 0;
var fireRate : float = 1; 
var gravity : float = 20;

function Update () {
	if(currentWay < way.length)
	{
		var target : Vector3 = way[currentWay].position;
		var moveDirection : Vector3 = target - transform.position;
		var distFromPlayer : Vector3 = player.position - transform.position;
		var velocity = rigidbody.velocity;
		if(moveDirection.magnitude < 1)
		{
			currentWay++;
		}
		else if(distFromPlayer.magnitude < raduis)
		{
			velocity = Vector3.zero;
			target = player.position;
			velocity = (player.position - transform.position).normalized * speed;
			fire();
		}
		else if(distFromPlayer.magnitude > raduis)
		{
			target = way[currentWay].position;
			velocity = moveDirection.normalized * speed;
		}
		else
		{
			velocity = moveDirection.normalized * speed;
		}
	}
	else
	{
		if(loop)
		{
			currentWay = 0;
		}
		else
		{
			velocity = Vector3.zero;
		}
	}
	if(health<0)
	{
		Destroy(gameObject);
		print("Kill");
	}
	moveDirection.y -= gravity * Time.deltaTime;
	rigidbody.velocity = velocity;
	transform.LookAt(target);
}

function OnCollisionEnter(collide : Collision)
{	
	if(collide.gameObject.tag=="bullet")
	{
		health = health - 1;
		print(health);
	}
}

function fire()
{
	if (Time.time > nextFire) 
	{
		nextFire = Time.time + fireRate;
		Instantiate(Bullet, barrel.position, transform.rotation);
		Instantiate(gunFire, barrel.position, transform.rotation);
		Bullet.LookAt(player.position);
	}
}


your welcome.
it's VZdaemon on xbox live
User avatar
SpiritWebb
Posts: 3107
Joined: Sun Jul 12, 2009 11:25 pm

Re: Ai script donation

Post by SpiritWebb »

Very nice...thanks for this!!
Image

Image
Post Reply

Return to “Scripting/Coding”