c# – Move Ball left and right with mouse drag Unity 3D

You have a couple of options depending on what it is you want.

Also as @Hamed answered, when using physics you don’t want to update the transform directly but add force using the Rigidbody.

Force Constant relative to where the Mouse is

if (Input.GetMouseButton(0))
{
    Vector2 force = Vector2.zero;

    //Get the Balls current screenX position
    float ballX = Camera.WorldToScreenPoint(Ball.transform.position).x;

    //Check if Click was Left or Right of the Ball
    if (ballX > Input.mousePosition.x)
    {
        //Click was Left of the Ball
        force = new Vector2(-1f, 0f);
    }
    else if (ballX < Input.mousePosition.x)
    {
        //Click was Right of the Ball
        force = new Vector2(1f, 0f);
    }

    //Adjust force amount to your suiting
    Ball.Addforce(force * Time.deltaTime);
}

Force relative to the mouse movement

if (Input.GetMouseButton(0))
{
    Vector2 force = Vector2.zero;

    float mouseDelta = Input.GetAxis("Mouse X");

    //Check if the Mouse is going Left or Right
    if (mouseDelta < 0f)
    {
        //Click was Left of the Ball
        force = new Vector2(-1f, 0f);
    }
    else if (mouseDelta > 0f)
    {
        //Click was Right of the Ball
        force = new Vector2(1f, 0f);
    }

    // Update force relative to mouse movement
    force = Mathf.Abs(mouseDelta) * force;

    //Adjust force amount to your suiting
    Ball.Addforce(force * Time.deltaTime)
}

Hastily written, look then write your own 🙂

Read more here: Source link