我有一个小伙伴陪着玩家,但他也应该在玩家跟随时转身。但是相反,他不断地转弯,有人可以帮我看看我哪里出了错
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;
}
答案 0 :(得分:3)
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);
}