0
\$\begingroup\$

I watched a tutorial about Unity Mobile From Scratch: Moving a 3D Object with Touch in Perspective on YouTube but when I added a camera follow script to follow that 3D object the object keeps moving even I clicked or dragged the ball once. Does anyone know why this is happening?

This is the code of moving the ball with mouse or touch from the tutorial

if (Input.GetMouseButtonDown(0))
    {
        Ray mouseRay = RayGenerator();
        RaycastHit hit;

        if (Physics.Raycast(mouseRay.origin, mouseRay.direction, out hit))
        {
            if (hit.transform.gameObject.tag == "BowlingBall")
            {
                obj = hit.transform.gameObject;
                objPlane = new Plane(Camera.main.transform.forward * -1, obj.transform.position);

                Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);
                float rayDistance;
                objPlane.Raycast(mRay, out rayDistance);
                ballTouchOffset = obj.transform.position - mRay.GetPoint(rayDistance);
            }

        }
    } else if (Input.GetMouseButton(0) && obj)
    {
        cameraFollow.enabled = false;
        isDragging = true;
        Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        Ray mouseRay = RayGenerator();
        Debug.DrawRay(mouseRay.origin, mouseRay.direction, Color.red);

        float rayDistance; 

        if (objPlane.Raycast(mRay, out rayDistance))
        {
            obj.transform.position = Vector3.Lerp(transform.position, new Vector3(mRay.GetPoint(rayDistance).x + ballTouchOffset.x, obj.transform.position.y, obj.transform.position.z), sideForce * Time.deltaTime);
        }


    } else if (Input.GetMouseButtonUp(0) && obj)
    {
        obj = null;
        isDragging = false;
        cameraFollow.enabled = true;
    }
}

And this is the camera script to follow that ball

public Transform bowlingBall;
public Vector3 offset;
public float cameraSlideSpeed = 5f;

void LateUpdate()
{
    transform.position = Vector3.Lerp(transform.position, bowlingBall.position + offset, cameraSlideSpeed * Time.deltaTime);
}
\$\endgroup\$
2
  • \$\begingroup\$ Can you post the code that is giving you trouble? \$\endgroup\$ May 10, 2018 at 14:27
  • \$\begingroup\$ @user3797758 I've added the code of BallMovement and CameraFllow Script. Even if you copy the same code from the tutorial and add camera follow script to camera to follow that object the problem will occur \$\endgroup\$ May 11, 2018 at 15:19

0

You must log in to answer this question.

Browse other questions tagged .