- Home /
What's causing this in my 2D AI script?
I'm trying to make AI for my beat-em-up, so far just a simple following waypoints and chasing the player. I've gotten stuck at every corner, and I'd like some help from someone so I can see where I'm going wrong.
Here's my Code:
void Update ()
{
if ((chaseTarget.position.x - spriteObject.transform.position.x) > attackRange)
{
Move(chaseTarget);
}
else if ((chaseTarget.position.x - spriteObject.transform.position.x) <= attackRange)
{
Move(chaseTarget);
}
else
{
Idle();
}
}
void Move (Transform target)
{
//If the target is to the left of the sprite
if (target.position.x < spriteObject.transform.position.x)
{
velocity.x = -walkSpeed * Time.deltaTime; //Move to the left
sprite.scale = new Vector3(-1, 1, 1); //Flip sprite to look left
animController.walking = true; //walking animation
}
//Alternatively, if the target is to the right
else if(target.position.x > spriteObject.transform.position.x)
{
velocity.x = walkSpeed * Time.deltaTime; //Move right
sprite.scale = new Vector3(1, 1, 1); //Flip to look to the right
animController.walking = true; //walking animation
}
//If the target is above the sprite
if (target.position.y > spriteObject.transform.position.y)
{
velocity.y = walkSpeed * Time.deltaTime; //Move up
animController.walking = true; //waling animation
}
//Alternatively, if target is below sprite
else if (target.position.y < spriteObject.transform.position.y)
{
velocity.y = -walkSpeed * Time.deltaTime; //Move down
animController.walking = true; //walking animation
}
worldMover.Move(velocity); //Move based on the velocity vector
}
This code causes this:

Any idea why?
First, I would put any AI code in a coroutine, because you have much more control over how code is executed in a coroutine. Second, why are you multiplying velocity by Time.deltaTime? Time.deltaTime is the amount of time (in seconds) since the last frame.
A) Streets of Rage remake??!?!?!??!?!?!?!
B) You are sure that your walkspeed isn't massive? Try setting it to a really low number and see if it affects anything. It looks like in one update he's already passing the player by alot, and in the next he has to turn around the do the same thing over and over.
This won't affect anything, but in your Update loop you're if statements will never reach Idle(). It'll always make it into the first or second if statement.
Ah yeah, the walkspeed was pretty massive. I think I's a problem with my ranges.
Also, not an exact remake, but similar gameplay.
Your answer
Follow this Question
Related Questions
Setting up Unity Steer 0 Answers
Zombies AI 2 Answers
Sit automatically at waypoint 0 Answers
Unity ML Agent doesn't learn well on default examples 1 Answer