- Home /
Why does this script crash Unity? Also simple random 2D movement?
For some reason this script crashes Unity when I run my game. I'm trying to get some simple random 2D movement. This is my first time using coroutines so I'm sure I'm doing it wrong but I didn't think I was doing it so wrong to get Unity to crash lol. Anyone know what's wrong and also anybody know how to get my script doing what I want it to do?
{
Rigidbody2D rb;
public float moveSpeed = 10f;
Vector2 currentPos;
Vector2 targetPos;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
StartCoroutine(ghostMoveRandom());
}
IEnumerator ghostMoveRandom()
{
yield return new WaitForSeconds(2);
currentPos = new Vector2(rb.position.x, rb.position.y);
targetPos = Random.insideUnitCircle;
while(currentPos != targetPos)
{
rb.transform.Translate(targetPos);
}
StartCoroutine(ghostMoveRandom());
}
}
Answer by rh_galaxy · Feb 20, 2020 at 06:36 PM
The most obvious problem is that most likely currentPos will never equal targetPos, because you are never changing currentPos. I guess that you will want to move towards targetPos over several frames.
I would solve this in Update() instead to avoid coroutines, but some prefere them. (Untested code)
Rigidbody2D rb;
float timer = 0;
float speed = 10;
Vector2 currentPos;
Vector2 targetPos;
void Start()
{
rb = GetComponent<Rigidbody2D>();
targetPos = rb.position;
}
void Update()
{
currentPos = rb.position;
timer += Time.deltaTime;
if (timer >= 2.0)
{
targetPos = Random.insideUnitCircle;
timer = 0;
}
rb.MovePosition(Vector2.MoveTowards(currentPos, targetPos, speed * Time.deltaTime));
}
Okay so your script works well, but for some reason the ghosts' first target position is always a single point near the beginning of the level, regardless of where I place them, and then they will start their random motion when they've reached that place. Any ideas? Also if you think I should just post this as a separate question then I'll do that :)
Hmm, the first two sec loop it should just stand still since currentPos and targetPos are the same, then to get movement that makes it wander around more you could maybe do
targetPos = currentPos + Random.insideUnitCircle * 2.0;
But not sure I understand.
Hey thanks for the response, I suppose I didn't explain properly. It does stay still for the first 2 secs, and when it goes to find a location for the first time, it will exceed the boundaries of the circle it should be moving in and will always travel far away to this one specific spot. Once there, it will start moving around within the boundaries of the circle as I would expect.
Your answer
Follow this Question
Related Questions
how to have object fall using random speed 0 Answers
Random crash in ntdll.dll 0 Answers
Player Dash doesn't work properly 0 Answers
How to fix my movement? 0 Answers
Unity Webplayer Random Crashing 1 Answer