Unity 一段简单的AI



这是一段控制僵尸向玩家移动的脚本,AI很sb但很有效。我将对Unity3d引擎和UDK引擎的AI脚本编写做一个简单的编程介绍。
先是一段UDK引擎下的脚本示例
class TestZombieBot extends GameAIController;
var Pawn thePlayer; //variable to hold the target pawn
var name SeenPlayerAnim;
simulated event PostBeginPlay()
{
    super.PostBeginPlay();
}
event SeePlayer(Pawn SeenPlayer)   //bot sees player
{
    if (thePlayer ==none)   //if we didnt already see a player
    {
        thePlayer = SeenPlayer; //make the pawn the target
        TestZombiePawn(Instigator).FullBodyAnimSlot.PlayCustomAnim(SeenPlayerAnim);
        GoToState('Follow'); // trigger the movement code
    }
}
state Follow
{
Begin:
    if (thePlayer != None)   // If we seen a player
    {
        MoveTo(thePlayer.Location); // Move directly to the players location
        GoToState('Looking'); //when we get there
    }
}
state Looking
{
Begin:
    if (thePlayer != None)   // If we seen a player
    {
        MoveTo(thePlayer.Location); // Move directly to the players location
        GoToState('Follow');  // when we get there
    }
}
default(此处打断是防止自动论坛表情替换代码字符)properties
{
    Begin Object class=AnimNodeSequence Name=SeenPlayerAnim
        bCauseActorAnimEnd=true
        End Object
        AnimSets(0)=AnimSet'MyModContents.AnimSet.Zombie'
        Animations=SeenPlayerAnim
        SeenPlayerAnim=Fury
}
  TestZombieBot.uc (1.25 KB, 下载次数: 258) 
以上这段脚本就是怪物攻击玩家的最简单形式,傻傻地跑向玩家,然后攻击玩家。很多游戏都是使用这样的AI,如果你希望你的AI不变成sb,可以参考另一篇文章 http://bbs.game798.com/showtopic-141617-1.html

    接着介绍Unity3d引擎下的脚本编写。其实程序是相通的,还是按上面那串代码来说,需要改几个变量,首先是玩家坐标(thePlayer.Location),在Unity3D里面没有这个现成的变量,但是你也可以做一步转化获得玩家坐标thePlayer.Location=GameObject.FindWithTag("Player").transform.position
MoveTo函数的具体形式在Unity3D引擎中可以这样写
function MoveTo(position : Vector3)
{
var direction = position - transform.position;
direction.y = 0;
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
transform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);
var forward = transform.TransformDirection(Vector3.forward);
var speedModifier = Vector3.Dot(forward, direction.normalized);
speedModifier = Mathf.Clamp01(speedModifier);
direction = forward * speed * speedModifier;
GetComponent (CharacterController).SimpleMove(direction);
}
如果你要跑动有声音,那么把这段插到MoveTo函数里面就可以
if (Time.time > SoundReloadTime +lastSound) {
     if (Sound)
            AudioSource.PlayClipAtPoint(Sound, transform.position);
      lastSound = Time.time;
}
这样就有脚步声了。
Unity3D下更复杂的AI脚本请看另外两个实例
http://bbs.game798.com/showtopic-133226-1.html
http://bbs.game798.com/showtopic-132155-1.html

你可能感兴趣的:(Unity3D)