Search code examples
c#unity-game-enginephysicsrigid-bodies

Adding force in different angles in Unity


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?


Solution

  • 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.