Pavol
Pavol

Reputation: 19

Calculate distance travelled on objects in Unity c#

I'm currently struggling to write a dynamic script that gets the position of two objects(hands) When I don't include public variables and put the script under each of the hands it works but not when I drag them in as game objects.There is no errors. The values just don't get updated.

This is an Oculus Rift application running on Unity 5.5 with the latest SDKs with Newton plug in.

public class calorieCounter : MonoBehaviour
{
    public Text displayMessage;

    public GameObject leftHand;
    public GameObject righHand;

    float distanceTravelledL = 0;
    float distanceTravelledR = 0;

    float distanceTravelled = 0;
    Vector3 lastPosition;

    Vector3 lastPositionL;
    Vector3 lastPositionR;

    void Start()
    {

        lastPositionL = leftHand.transform.position;
        lastPositionR = righHand.transform.position;
        lastPosition = transform.position;
    }

    void Update()
    {

        distanceTravelledL += Vector3.Distance(transform.position, lastPositionL);
        distanceTravelledR += Vector3.Distance(transform.position, lastPositionR);

        lastPositionL = transform.position;
        lastPositionR = transform.position;

        print("Left hand distance: " + distanceTravelledL);
        displayMessage.text = ("L: " + distanceTravelledL);


        print("Right hand Distace: " + distanceTravelledR);
        print("Right hand position: " + lastPositionR);
        print("Left hand position: " + lastPositionL);
        displayMessage.text += ("R: " + distanceTravelledR);
    }

}

Upvotes: 0

Views: 2713

Answers (2)

Ginxxx
Ginxxx

Reputation: 1648

I guess just by doing this manually it can be like this

 Vector3 temp = new Vector3(0,0,0);
 myGameObject.transform.position += temp;

I hope it helps

Upvotes: 0

Serlite
Serlite

Reputation: 12258

You've mixed up some of your variables - in your Update() method, you're storing the last position as transform.position, instead of the respective positions of the hands. In the same way, your distance calculation should be based on the hands' positions, not the script's transform.position.

Here's some updated code that references the correct transforms:

void Update()
{
    distanceTravelledL += Vector3.Distance(leftHand.transform.position, lastPositionL);
    distanceTravelledR += Vector3.Distance(righHand.transform.position, lastPositionR);

    lastPositionL = leftHand.transform.position;
    lastPositionR = righHand.transform.position;

    // ...
}

On a side note, you should probably also remove lastPosition from the script if you're not using it - it looks like a relic from when you attached the script individually to both hands, and it could cause a similar mix-up if you're not careful.

Hope this helps! Let me know if you have any questions.

Upvotes: 2

Related Questions