How to fix stuttering for movetowards script
Hi, I'm pretty new to these stuff. i've tried to make enemy follow the player by using movetowards function, but I saw that the enemy stutters I tried to fix this by adding isPlaying bools but I can't figure out how to do it. Also, my game is 2d top down.
heres the enemy script
public float speed; private Transform target; public Animator animator; public Transform homePos; public int maxHealth = 50; public int currentHealth; public HealthBar healthbar; Vector2 movement; public bool isDead; public bool isPlaying = false; public GameObject Coin; private Transform target2; public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
currentHealth = maxHealth;
healthbar.SetMaxHealth(maxHealth);
isDead = false;
}
// Update is called once per frame
void Update()
{
if(Vector2.Distance(transform.position, target.position) < 300 && isPlaying == false)
{
transform.position = transform.position = Vector2.MoveTowards(rb.position, target.position, speed * Time.deltaTime);
}
else if (isDead == false)
{
GoHome();
}
if(Vector2.Distance(transform.position, target.position) < 50)
{
animator.SetBool("isAttacking", true);
isPlaying = true;
}
else if (Vector2.Distance(transform.position, target.position) > 50)
{
animator.SetBool("isAttacking", false);
isPlaying = false;
}
if(Vector2.Distance(transform.position, homePos.position) < 40f && isPlaying == false)
{
animator.SetBool("HomePosition", true);
}
else if (isDead == false)
{
animator.SetBool("HomePosition", false);
}
movement.x = target.position.x - transform.position.x;
animator.SetFloat("Horizontal", movement.x);
animator.SetFloat("Speed", movement.sqrMagnitude);
if(currentHealth <= 0)
{
Instantiate(Coin, transform.position, transform.rotation);
isDead = true;
Destroy(gameObject);
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.CompareTag("Proro") && isDead == false)
{
TakeDamage(17);
Destroy(col.gameObject);
}
}
public void GoHome()
{
transform.position = Vector2.MoveTowards(transform.position, homePos.position, speed * Time.deltaTime);
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
healthbar.SetHealth(currentHealth);
}
Your answer
Follow this Question
Related Questions
Vector3.MoveTowards Problems 0 Answers
Particle System not working on multiple enemies 0 Answers
Buttons Not Working? PLEASE HELP!!!!!!!!!!!! 0 Answers
To use touch & raycasting to *drag and drop* a game object... 1 Answer
script causes unity to crash 0 Answers