Search Unity

(C#) Unity - adding torque related to camera.

Discussion in 'Physics' started by Mike_MG, Nov 21, 2018.

  1. Mike_MG

    Mike_MG

    Joined:
    Nov 21, 2018
    Posts:
    1
    Hello, coders. I need to script sphere and camera's movement in third person perspective, 3D, in Unity 2018.2.14f1.

    Everything needs to work like this: While pressing "W" button, sphere moves forward towards the world (adding torque with function rigidbody.AddTorque(Vector3.right * 2f) causes adding torque towards particular axis in world. In that case, if I rotate my mouse around the sphere that I control - while pressing "W" I don't move in a direction that I am looking towards. The sphere still rolls forward towards the world.

    I got the value of vector transform.rotation from camera and according to this value I tried to add torque towards the camera, but, unfortunately, it gave no succes.

    I'm looking for a kind of easy way to implement adding torque towards the direction, that camera is turned to. I am a beginner doing a task for lessons.

    My code connected to the sphere object:

    Code (CSharp):
    1. FollowingCamera followingCamera = GameObject.Find("CameraBase").GetComponent<FollowingCamera>(); // getting CAMERA component
    2. float rotat = followingCamera.realRotY; // getting rotation of CAMERA around Y axis
    3. Vector3 direction = Vector3.zero; // creating direction vector
    4. void moveForward() // while pressing "W"
    5. {
    6.         Vector3 tempRot = transform.localEulerAngles; // assigning rotation of SPHERE around Y axis to a new, buffer vector
    7.         tempRot.y = rotat; // setting Y axis in CAMERA rotation around Y axis
    8.         transform.localEulerAngles = tempRot; // rotating SPHERE to position, that the CAMERA is rotated to (we want to move there)
    9.         direction = transform.right * 2f; // adding torque
    10. }