- Home /
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");
return;
}
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.
This needs more information, in your scene, are the asteroids co$$anonymous$$g from one fixed area or 360 degrees. Are they all co$$anonymous$$g straight on, or are some co$$anonymous$$g from higher and some from lower. where are you instantiating them. Stuff like that, the more info you give the easier it'll be to solve
I haven't got a system yet that spawns the asteroids. I currently just drag them into the scene but out of the camera view hoping that when I click play, they'll move within the view of the camera which doesn't always happen and that's the problem
Ok, but are they supposed to come at the camera head on, or from the side just moving past. and would you like for them to come from one general area or from all over (360). these things change how the script and scene are going to need to be set up
Answer by Codelyy · Jul 21, 2016 at 02:15 AM
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.
Answer by tanoshimi · Jul 20, 2016 at 06:14 AM
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;
They do move towards the position but the problem is, the position isn't always within the screen's view.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Make 3D Player look exactly at mouse with ScreenToWorldPoint? (maths Question) 2 Answers
Apply gravity to my character through script. 0 Answers
Clamp an object on 2 sides 0 Answers