Monkey Mayhem – Dev Log 02

By September 30, 2018 Dev Blog

Welcome back for another development log post. In the last post, I talked about getting the initial swinging and releasing done (as seen below). This post is going to talk about attaching the player back to the branch.

Catch me buddy!

So in order to be able to re-attach the player to a branch, I need to do a couple things:

  1. I need to get a list of all branches in a scene.
  2. I need to check which branch is closest to the player.
  3. I need to check if the branch is close enough to the player.
  4. I need to setup a new hinge joint

My solution to problems 1 and 2 was simple. Store all the branches in the scene into an array and then sort that array by distance to the player. I did this with the following code:

Branches = GameObject.FindGameObjectsWithTag("Branch");
Branches = Branches.OrderBy(Branches => Mathf.Abs((Branches.transform.position - transform.position).magnitude)).ToArray();

This resulted in Branches[0] being the closest branch to the player.

Now I know which branch is the closest, I need to check if it is close enough for us to attach. I did this by doing the following as an if statement:

Mathf.Abs((Branches[0].transform.position - transform.position).magnitude) < requiredDistance)

Here we are checking the absolute value of the distance between the two vectors, against the requiredDistance value. requiredDistance is a public variable which allows me to check which value works best from within Unity.

Now I know the closest branch is within range, I need to connect the player to the branch.

Firstly, I set our position to be that of the branch

transform.position = Branches[0].transform.position;

Next, I created a new Hinge Joint and store it into our local variable

hinge = gameObject.AddComponent<HingeJoint>();

Then, I set up the values of the hinge joint

hinge.connectAnchor = Branches[0].transform.position;
hinge.connectedBody = Brances[0].GetComponent<Rigidbody>();
hinge.axis = Vector3.forward;
hinge.useMotor = true;

JointMotor motor = hinge.motor;
motor.targetVelocity = 500.0f;
motor.force = 500.0f;
hinge.motor = motor;

You can see the result below.

This set-up was a bit janky, because I couldn’t change the direction I was spinning in without accessing the motor.  So I will come up with a better solution for spinning around the branch.

 

Thanks for reading and see you next time,

Ethan

Leave a Reply