- Home /
Script for Enemy AI (2D platformer)
I'm curious of how to make an Enemy AI for a 2D platformer. I've tried many of the scripts on the forum but they all seemed to be more geared towards 3D games since when applied to my sprites they rotate in the 3rd dimension. Ideally what I would like is an enemy who patrols until the player is spotted then he follows the player until the player is in range then he attacks. If this is too much to ask then a simple follow script would still be extremely helpful. This video shows kind of how I'd like my enemy to move but I couldn't figure out how to make it work at all. Any kind of guidance would be greatly appreciated, Javascript or C# please. Thanks!
Answer by AmarokStudios · Jul 23, 2014 at 11:59 PM
Hey, I've noticed there was no answer for this question so I thought I'd give it a shot! I'm looking for the same thing... I'm almost done working on a script to do this but I need to figure out how to lock the rotation. So far, if you apply this script to an enemy, and add the "Player" tag to your player, than the enemy will follow the player but when it gets too close, it will rotate showing the other sides of the enemy (a 2D sprite... so it's not pretty lol) but for the most part, this one works.
pragma strict
private var Xpos : float; private var Ypos : float; private var max : boolean;
var Vert : boolean; var maxAmount : int; var step : float;
function Start () { Xpos = transform.position.x; Ypos = transform.position.y; }
function FixedUpdate () {
if (Vert) { if (transform.position.y >= Ypos + maxAmount) { max = true; }
else if (transform.position.y <= Ypos)
{
max = false;
}
}
else
{
if (transform.position.x >= Xpos + maxAmount)
{
max = true;
}
else if (transform.position.x <= Xpos)
{
max = false;
}
}
if (Vert)
{
if (!max)
{
transform.position.y += step;
}
else
{
transform.position.y -= step;
}
}
else
{
if (!max)
{
transform.position.x += step;
}
else
{
transform.position.x -= step;
}
}
}
U can used Rigid body 2d and select Fixed Angle to lock the rotation
Your answer
Follow this Question
Related Questions
2d enemy ai 0 Answers
How do I make an object follow the player? 1 Answer
Mirroring Animation with Object Move 2 Answers
A Quick Question About 2D Enemy AI 0 Answers