Search Unity

Move object relative to camera's Z Rotation

Discussion in 'Scripting' started by wxxhrt, Oct 23, 2018.

  1. wxxhrt

    wxxhrt

    Joined:
    Mar 18, 2014
    Posts:
    163
    I have objects that get instantiated then moved slightly according to this script:-

    Code (CSharp):
    1. public void Trigger(Vector2 mouseDelta, float emptySize){
    2.         Vector3 mouseDelta3 = new Vector3(mouseDelta.x, mouseDelta.y, 0);
    3.         Vector3 finalPosition = this.transform.position + mouseDelta3;
    4.         this.transform.DOMove(finalPosition, (6f / emptySize) / 40f).SetEase(Ease.OutSine);
    5.         //Debug.Log(this.transform.position + " " + finalPosition);
    6.     }
    DOMove being from the DOTween Library.

    So when the mouse gets dragged the speed of that drag flings objects off in the direction of mouse travel.

    The problem comes when I rotate the camera around its local Z axis, the objects fling off in world space rather than relative to the camera.

    I guess I have to multiply something by the cameras up vector but am not quite sure and trial and error isn't helping.

    Any ideas? Thanks.
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    The additional step you are missing is applying the camera rotation to the mouse delta. This shortcut should work unless you do strange things with your camera, just add this just before you calculate your "finalPosition":

    Code (CSharp):
    1. mouseDelta3 = myCamera.transform.right * mouseDelta.x + myCamera.transform.up * mouseDelta.y + myCamera.transform.forward * mouseDelta.z;