Getting a random direction within screen view

I’m creating some asteroids and as they spawn, i want them to move in a random direction towards the screen view so they don’t just fly off into no where.

I found a topic that gave me a way of finding a random position within screen view using this:

direction = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0,Screen.width), Random.Range(0,Screen.height), Camera.main.farClipPlane/2));

I’ve placed this statement in the Start function including a function that I use to move the asteroid towards the point:

protected virtual void MoveInDirection()
		if(direction == null)
			Debug.LogError("No Direction");

		rig.AddForce(direction.normalized * moveSpeed, ForceMode2D.Force);

It does work as the asteroids do move but the problem is that they don’t seem to always move towards the screen view and will sometimes move the other way which isn’t what I want so I was wondering if someone could help.

Your problem is that the direction variable is not a direction, it’s a position. To move an asteroid towards that position, you need to calculate the direction as a difference from its current location. So try adding this before your AddForce call:

difference = difference - transform.position;

EDIT: I fixed the issue simply by using Camera.main.PixelWidth and height instead of Screen.Width and height

I should of really just said that the problem was that one statement wasn’t giving me a position within the camera view and sometimes gave me a position outside the camera view.