跳至正文

NPC运动篇

好,经过前三篇的废话基础后,我们终于来到正题了,那么开始吧

平移运动

这个很简单,只需要在ai里写

NPC.velocity = new Vector2(11,45);

就可以让npc以既定速度运动了

当然,还不够,我们还需要让npc追着玩家跑

public override void AI(){
    NPC.TargetClosest(true);
    Player p = Main.player[NPC.target];
    NPC.velocity = 12*(p.Center - NPC.Center).SafeNormalize(Vector2.Zero);
}

12是速度,大概是略快于玩家掉落速度

旋转运动

使用 NPC.rotation 来旋转向量,注意这个用的是弧度制,从-1pi到pi,下面是示意图

示意图

我们还可以让npc朝向和速度一样

NPC.rotation = NPC.velocity.ToRotation();

ToRotation函数可以将向量转成角度,这个只能在你的贴图正朝向右边时才对,如果你的npc朝向不对,自己加上对应的数

还有,我们可以通过ToRotation函数来实现克眼类旋转,使npc的朝向慢慢转向玩家

if(Math.Abs((NPC.position - p.position).ToRotation()-NPC.rotation)<=0.05f)
{
    NPC.rotation = (NPC.position - p.position).ToRotation();
}
else if((NPC.position - p.position).ToRotation() > NPC.rotation)
{
    NPC.rotation += 0.03f; 
}
else if ((NPC.position - p.position).ToRotation() < NPC.rotation)
{
    NPC.rotation -= 0.01f;
}

除了这些用法,我们还可以使用RotatedBy函数来使向量偏转

NPC.velocity = NPC.velocity.RotatedBy(0.1f);

插值运动

这里就要引入一个新的方法了,Lerp插值:

Vector2 a = Vector2.Lerp(b,c,x);

Lerp插值本质是将第一个空(以一定的幅度)转变到第二个空。幅度就是第三空

这里的a,Lerp后的结果是(b + (c – b) * x)

不过这个x不要超过0.05

接下来就是应用了

new Vector2 vec = 12*(p.Center - NPC.Center).SafeNormalize(Vector2.Zero);//定义一个速度
NPC.velocity = Vector2.Lerp(NPC.velocity,vec,0.05f);//让npc的速度每帧都向这个速度变化0.05倍

冲刺运动

这个肥肠的简单,就是给npc一个向玩家的高倍向量,然后慢慢减速

if(NPC.ai[0]<=10)
{
    NPC.velocity = 30*(p.Center - NPC.Center).SafeNormalize(Vector2.Zero);
}
if(NPC.ai[0]>10)
{
    NPC.velocity = Vector2.Lerp(NPC.velocity,Vector2.Zero,0.05f);
}
if(NPC.ai[0]==60)
{
    NPC.velocity = Vector2.Zero;
    NPC.ai[0] = 0;
}

我们再润色一下

NPC.rotation = NPC.velocity.ToRotation();
if(NPC.ai[0]<=10)
{
    NPC.velocity = 30*(p.Center - NPC.Center).SafeNormalize(Vector2.Zero);
    SoundEngine.PlaySound(SoundID.Roar, NPC.Center);
}
if(NPC.ai[0]>10)
{
    NPC.velocity = Vector2.Lerp(NPC.velocity,Vector2.Zero,0.05f);
}
if(NPC.ai[0]==60)
{
    NPC.velocity = Vector2.Zero;
    NPC.ai[0] = 0;
}

效果也是肥肠好

小作业

试着大致复刻原版克苏鲁之眼的ai吧

标签:

《NPC运动篇》有1个想法

发表回复