Scripting an Enemy

A common idea for a enemy in a shooter: 
In a very abstract form, an Enemy must reach the Player, stop at a certain distance, consider this a shooting range, then avoid Player's shooting by rotating around its. 

I did a sketch on paper before going into the computer to break down the idea:
- the "P" stands for player
- "E" enemy
- and the circle around "P" is the desired range where the "E" should stop and start rotating.

A keyword here is "distance", that's where this function on Unity3d becomes in handy

Below I will share with you the script and how it looks on gameplay.

 in action:
Basically it is switch between 2 functions, ChasePlayer and if the distance desired is correct (3.5 in this example) RotateAroundPlayer.
Mind that I'm not a programmer master so, if you find this script crappy, sorry I'm a learning n00b.

Also I got some help with a part of my script from this guy here
Moving the Player

My script currently looks something like this (javascript):

var Player : Transform;
var ChaseSpeed = 1.0;
var RotateAroundSpeed = 20;
var timeToChange: float = 0;
var minTime: float = 1; // min time to revert direction
var maxTime: float = 5; // max time to revert direction
private var direction: float = 1;

function Update (){
DetectDistance ();

function DetectDistance () {
    var dist = Vector3.Distance(Player.position, transform.position);
    Debug.Log ("Distance to player: " + dist);
    if(dist <= 3.5){
    }    else {
        ChasePlayer ();

function ChasePlayer () {
    transform.position = Vector3.Lerp(transform.position, Player.position, Time.deltaTime / ChaseSpeed);

function RotateAroundPlayer () {
     if (Time.time > timeToChange){
        timeToChange = Time.time + Random.Range(minTime, maxTime);
        direction = -direction;
    var Rotate_Speed = Random.Range(1,RotateAroundSpeed);
    transform.RotateAround (Player.position, Vector3.up, direction * Rotate_Speed  * Time.deltaTime);

Thanks for reading !

No hay comentarios:

Publicar un comentario