I'm trying to write logic when the player moves away from the summon further than 10f, the summon gets a random point around the player and moves towards it.
I already have a calculation of the distance to the player, when it is more than 10, a random point is generated around the player and a beam is directed there.
The problem is that this point is updated every frame and I can't figure out how to record it once until the summon reaches it.
void Update()
{
Vector3 RelativePosition = transform.position;
Vector3 PlayerPosition = Player.transform.position;
float DistanceToPlayer = Vector3.Distance(PlayerPosition, RelativePosition);
if (DistanceToPlayer >= MaxDistanceToPlayer)
{
MoveToPlayer = true;
StartCoroutine(MovingToPlayer());
}
}
IEnumerator MovingToPlayer()
{
Vector3 NewPositionToPlayer = Player.transform.position new Vector3 (Random.Range(-2.0f, 2.0f), 0f, Random.Range(-2.0f, 2.0f));
Debug.DrawLine(transform.position, NewPositionToPlayer, Color.red);
while (transform.position != NewPositionToPlayer)
{
yield return null;
}
MoveToPlayer = false;
}
PS
As if the code below was solved, but now the object is teleported, instead of moving over time to a new point.
while (transform.position != NewPositionToPlayer)
{
var step = WalkSpeed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, NewPositionToPlayer, step);
Debug.DrawLine(transform.position, NewPositionToPlayer, Color.red);
}
yield return null;
CodePudding user response:
Update: my last answer was wrong, the problem lies in the while loop. Because loops run in a single frame, all your script does is run the code inside the loop until it reaches the target position, and it looks like it teleports because it does all of that in a single frame. Instead, you should put the code in the update loop, but add a boolean check, or if the object was instantiated then destroy it.
CodePudding user response:
If anyone can help:
void Update()
{
Vector3 RelativePosition = transform.position;
Vector3 PlayerPosition = Player.transform.position;
float DistanceToPlayer = Vector3.Distance(PlayerPosition, RelativePosition);
var step = WalkSpeed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, Pivot.transform.position, step);
if (DistanceToPlayer >= MaxDistanceToPlayer)
{
if(MoveToPlayer == false)
{
MoveToPlayer = true;
Vector3 NewPositionToPlayer = Player.transform.position new Vector3 (Random.Range(-2.0f, 2.0f), 0f, Random.Range(-2.0f, 2.0f));
Pivot.transform.position = NewPositionToPlayer;
Debug.DrawLine(transform.position, NewPositionToPlayer, Color.red);
}
}
if (Pivot.transform.position == transform.position)
{
MoveToPlayer = false;
}
}