Ronin: I Didn’t See That Restraining Order

My daily blog posts are actually get pretty lax, but progress is slow at the moment whilst I’m figuring out the little things in Unity3D. Seriously, last night I spent ages trying to work out how to get a NPC to follow my player using trigonometry because I didn’t know there was a ‘translate’ function. Now that I do, the code has gone from several down to 2. But now, my player can be stalked by a little friend:

Attaching a head seems to be a good way of getting a sense of direction

Achieving this uses a very simple piece of code:

if (!CheckDist(1f, character[1], Target))
character[1].transform.Translate(0, 0, 10 * Time.deltaTime);


I’m also using my ‘CheckDist’ function here:

bool CheckDist(float dist, CharacterController con1, GameObject con2)
var pos1 = con1.transform.position;
var pos2 = con2.transform.position;

var posx = pos1.x – pos2.x;
var posy = pos1.y – pos2.y;
var posz = pos1.z – pos2.z;

if (posx < dist && posx > -dist && posy < dist && posy > -dist && posz < dist && posz > -dist)
return true;
return false;

This just checks if the ‘target’ object is within a certain distance. In my code, if he’s outside of the distance he’ll move towards you, if he isn’t, then he’ll just look at you. Easy as pie!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s