N
N
ne_Sci_fi2019-07-02 18:22:21
C++ / C#
ne_Sci_fi, 2019-07-02 18:22:21

What to do to stop shaking gameobject?

Basically, I have an enemy script that makes the enemy chase the player,
as soon as player.transform.position.x is equal to enemy.ransform.position.x , the enemy starts shaking up and down, and when player.transform.position. y is equal to enemy.ransform.position.y , then the enemy is shaking left and right. Here is my script:
public class Enemy : MonoBehaviour
{
GameObject player;
public float maxDis;
public float speedMove;
public bool isFacingRight;
byte h;
public Animator anim;
void Start()
{
player = GameObject.FindWithTag("Player");
}
void FixedUpdate()
{
Follow();
Rotate();
}
void Follow()
{
float direction_x = player.transform.position.x - transform.position.x;
float direction_y = player.transform.position.y - transform.position.y - 0.7f;
if (Mathf.Abs(direction_x) < maxDis && Mathf.Abs(direction_y) < maxDis)
{
Vector3 pos = transform.position;
pos.x += Mathf.Sign(direction_x) * speedMove * Time.deltaTime;
pos.y += Mathf.Sign(direction_y) * speedMove * Time.deltaTime;
transform position = pos;
h = 1;
}
else
{
h = 0;
}
anim.SetFloat("Speed", Mathf.Abs(h));
}
void Rotate()
{
if(player.transform.position.x < transform.position.x && isFacingRight)
{
Flip();
}
else if(player.transform.position.x > transform.position.x && !isFacingRight)
{
Flip();
}
}
void Flip()
{
isFacingRight = !isFacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Gaydak, 2019-07-02
@ne_Sci_fi

you would code as a code.
but on business.
you know what your piece does (and the same for Y )
pos.x += Mathf.Sign(direction_x) * speedMove * Time.deltaTime; ??
Do you fully understand the essence of the check
if (Mathf.Abs(direction_x) < maxDis && Mathf.Abs(direction_y) < maxDis) ??
Well, and most importantly, as soon as the object and its target are "levelled", they will not coincide in coordinates one to one.
you have direction_x and direction_y going from tiny positive to tiny negative.
this is due to the fact that you are moving the object behind the target, regardless of the current distance between them.
always, if not too far apart - begins the pursuit.
and no matter how close it gets to the target, it moves at a speed (conditionally the same
pos.x += Mathf.Sign(direction_x) * speedMove * Time.deltaTime; ))
as a result, it overtakes a bit. starts moving back. lags behind - again begins to overtake.
as a solution, you can enter the minimum distance at which it is considered that you have already "caught up" and stop chasing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question