Hey, I’m very new to Unity and C# and I’ve been watching youtube videos with the goal to create a Zelda type videogame. I wanted to get enemy animations down today but I feel the need to ask guidance.
This is the C# script for my enemy AI:
Rigidbody2D rbody;
Animator anim;
public Transform Player;
public float ChaseSpeed = 5f;
public float Range = 5f;
float CurrentSpeed;
void Start()
{ rbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void Update()
{
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (movement_vector != Vector2.zero)
{
anim.SetBool("is_walking", true);
anim.SetFloat("velocity_x", movement_vector.x);
anim.SetFloat("velocity_y", movement_vector.y);
}
else {
anim.SetBool("is_walking", false);
}
if (Vector3.Distance(transform.position, Player.position) <= Range)
{
CurrentSpeed = ChaseSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, Player.position, CurrentSpeed);
}
}
I’m assigning animations via a blend tree with multiple animations in them, identical to this video: 2D RPG My Hero - Unity3D - YouTube. I want the enemy to follow the player and change animations depending on which direction it’s going towards (north,west,south,east), i used velocity_x and velocity_y as my animation parameters. I know a large error in my animator-code is that I refer to “input” here:
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
This basically makes the AI follow the player but also react to my inputs, which is not supposed to happen.
So my question is, what do I replace “input” with? Is this at all going to work or do I need to change my approach completely?
I’m just trying to understand what types of options I have utilizing my code and how I can find the correct code-keywords to do what I want.
I want to learn C# through unity, are there any noticable 2D Top down tutorial/books people would recommend me?
Any help is really appreciated!