**I'm not looking for a way to fix the code since this wouldn't have the intended effect anyway, I was just wondering why it made Unity crash.**
The code was supposed to make this sprite move away from the player, but it just crashed Unity instead.
public Rigidbody2D rb2D;
public Transform player;
public float sensePlayerRadius = 3f;
public float stopRunningRadius = 6f;
public float speed = 10f;
bool isRunning = false;
void Update()
{
StartRunningAway();
}
void StartRunningAway()
{
// If player is within the range the emu can sense
if (Vector3.Distance(transform.position, player.position) <= sensePlayerRadius && !isRunning)
{
print("run");
isRunning = true;
RunAway();
}
else print("safe");
}
void RunAway()
{
while(Vector3.Distance(transform.position, player.position) <= stopRunningRadius)
{
// Moves away from the player, a negative distance to move results in the object moving away from the target, not towards, multiplied by deltaTime to be framerate independent
rb2D.MovePosition(Vector3.MoveTowards(transform.position, player.position, -speed * Time.deltaTime));
}
isRunning = false;
}
↧