Reputation: 61
I have a little companion that follows the player around, but he is also supposed to turn around when the player does. But instead, he constantly keeps turning could someone help me see where I went wrong
public float speed;
public float stoppingDistance;
private Transform target;
Player Player;
void Start()
{
Player = GameObject.Find("Axel").GetComponent<Player>();
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
void Update()
{
if (Vector2.Distance(transform.position, target.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
if (Player.facingRight == false)
{
Turn();
}
else if (Player.facingRight == true)
{
Turn();
}
}
}
void Turn()
{
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
Upvotes: 0
Views: 42
Reputation: 90580
Well you call Turn
"all the time" but you never check if you probably already are looking in the correct direction ...
either change your condition or add a parameter to Turn
and set a fixed direction instead of toggling between two directions without controlling which is the current direction.
You could do it e.g. with an enum Direction
like
public float speed;
public float stoppingDistance;
private Transform target;
Player Player;
private enum Direction
{
right = 1,
left = -1;
}
// for storing the scale on start
private Vector3 originalScale;
private void Start()
{
Player = GameObject.Find("Axel").GetComponent<Player>();
// If you just want the transform of the Player
// than simply use
target = Player.transform;
// instead of
//target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
originalScale = transform.localScale;
}
// Btw: for reacting to any user input (as the player movement)
// it is always better to do these things
// in LateUpdate instead of Update
// LateUpdate is executed after all Update calls in the Scene finished
private void LateUpdate()
{
if (Vector2.Distance(transform.position, target.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
if (Player.facingRight == false)
{
Turn(Direction .left);
}
else if (Player.facingRight == true)
{
Turn(Direction .right);
}
}
}
private void Turn(Direction direction)
{
transform.localScale = Vector3.Scale(originalScale, Vector3.right * (int)direction);
}
As alternative if you want to keep your original Turn
you could as well simply add more conditions before you even call Turn
. Something like
// ...
if (Player.facingRight == false && transform.localScale.x > 0)
{
Turn();
}
else if (Player.facingRight == true && transform.localScale.x < 0)
{
Turn();
}
// ...
private void Turn()
{
transform.localScale = Vector3.Scale(transform.localScale, -Vector3.right);
}
Upvotes: 3