I am making a game where fruit appear on screen (at the moment they fly in from the bottom of the screen moving up and then falling back off the screen) and you have to smash the fruit to earn points.
I am trying to figure out how to add a force in different angle so that the fruit fly up to different places on screen instead of just up in the middle and back down.
This is how I am adding force to the fruit:
foodItemRigidBody.AddForce(transform.up * force);
My spawn location is in the middle of the bottom of the screen, all fruit spawns there and a force is added so they fly up and fall down in a straight line.
How do i make it so they spawn in the middle and fly up, some fly slightly to the right and some slightly to the left?
CodePudding user response:
Supposed 2D, I would try randomizing your up direction a bit to the sides:
Vector3 upDirSlightlyRandomized = (transform.up transform.right new Vector3(Random.Range(-0.5f, 0.5f), 0, 0).normalized;
foodItemRigidBody.AddForce(upDirSlightlyRandomized * force);
Same but more direct maybe:
Vector3 upDirSlightlyRandomized = new Vector3(Random.Range(-0.5f, 0.5f), 1, 0)).normalized;
I would play with the -0.5f range until the desired is achieved. For 3D I would try randomizing also the z.
CodePudding user response:
Make 3 objects.
LeftBorder
RightBorder
Target
Have Target move to a random location between LeftBorder and RightBorder on the x-axis but to maintain its own y-axis and z-axis between each firing of the fruit.
Your spawnpoint should then just rotate towards the target using Transform.LookAt.
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
This way your spawnpoint rotates towards a random target location each time.
