Thursday, April 28, 2011

Alien Zombies walk Through Walls

A new problem I've been having is trying desperately to come up with an "Object Avoidance" system that is simple and hopefully not expensive. I added this bit of code into my "Alien Zombie's" AI script:







function Update (){



//The direction vector to our target
var dir = (target.position - transform.position).normalized;
var hit : RaycastHit;
// Check for forward raycast
if(Physics.Raycast(transform.position, transform.forward, hit, 20)){
if(hit.transform != transform){
Debug.DrawLine(transform.position, hit.point, Color.red);
dir += hit.normal * 50;
}


}


var leftR = transform.position;
var rightR = transform.position;


leftR
rightR.x += 2;




if(Physics.Raycast(leftR, transform.forward, hit, 20)){
if(hit.transform != transform){
Debug.DrawLine(leftR, hit.point, Color.red);
dir += hit.normal * 50;
}
}
if(Physics.Raycast(rightR, transform.forward, hit, 20)){
if(hit.transform != transform){
Debug.DrawLine(rightR, hit.point, Color.red);
dir += hit.normal * 50;
}
}


var rot = Quaternion.LookRotation(dir);


var sizeOfMonster = 2.5;
var groundOffset = Vector3(0,2.2,0);
var newPosition = transform.position + transform.forward * 1 * Time.deltaTime;
if (!Physics.CheckSphere(newPosition+groundOffset, sizeOfMonster)){
transform.position = newPosition;
}


transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime);
transform.position += transform.forward * 1 * Time.deltaTime;


}


function OnDrawGizmosSelected () {
Gizmos.color = Color.red;
var sizeOfMonster = 2.5;
var groundOffset = Vector3(0,2.2,0);
Gizmos.DrawWireSphere (transform.position+groundOffset, sizeOfMonster);
}
 
With some help from Unity Answers. But they still just pass right through the walls of my buildings and even sometimes through the terrain and then just fall into oblivion, which I'll bet is a real garbage collector and drag on the games performance after a while. These frustrating problems are causing me so much grief and costing me so much valuable time that I could be spending on the games actual creative look and feel. But I just want to get this and other issues worked out so I have some sort of template to base future (If Any) games on as this very frustrating learning curve continues.

No comments: