Question by
ItzChris92 · Sep 30, 2021 at 11:09 AM ·
2dphysics2d game
How to set direction to a random point on camera viewport?
Hello, I am spawning object off camera and I am trying to get them to start moving towards a random point on the camera screen (2D, orthographic). They spawn correctly and move with a constant velocity, but they don't aim themselves at the camera. Any help would be appreciated!
private void OnEnable()
{
//Randomise the size of the asteroid
asteroid.localScale = new Vector3((Random.Range(0.25f, 0.75f)), (Random.Range(0.25f, 0.75f)));
//Give a random angular velocity/rotation
asteroidRB.angularVelocity = Random.Range(-0.0f, 90.0f);
//Set direction of travel
float x = Random.Range(0.05f, 0.95f);
float y = Random.Range(0.05f, 0.95f);
travelDirection = new Vector2(x, y);
travelDirection = Camera.main.ViewportToWorldPoint(travelDirection);
}
private void FixedUpdate()
{
asteroidRB.velocity = travelDirection * (Random.Range(minSpeed, maxSpeed));
}
Comment
Your answer
Follow this Question
Related Questions
Object with rigidbody2D doesn't move when it's supposed to 0 Answers
stick-figure piercing 0 Answers
2D Game Fliping Player problem 0 Answers
Why/How 2d tower of blocks collapse? 0 Answers
Trouble with controlling the direction of projectiles with C# code 1 Answer