Taik
Taik

Reputation: 265

How to rotate 3d object by swiping?

I have a horizontal cylinder in my scene and I want to rotate it (in the z-axis) by swiping left and right, I've created this script but it didn't work, can you please tell me where's the problem?

public class SwipeControl : MonoBehaviour {

    public Transform Cylinder;

    void Update()
    {
        if (Input.touchCount == 1)
        {
            // GET TOUCH 0
            Touch touch0 = Input.GetTouch(0);

            // APPLY ROTATION
            if (touch0.phase == TouchPhase.Moved)
            {
                Cylinder.transform.Rotate(0f, 0f, touch0.deltaPosition.x);
            }

        }
    }
}

Upvotes: 0

Views: 164

Answers (2)

Lotan
Lotan

Reputation: 4283

Don't use Cylinder as the name of your variable, cause it's a class name for Unity primitive:

https://docs.unity3d.com/ScriptReference/PrimitiveType.Cylinder.html

Edit: As Stijn says, the code will work, but it's a bad practice name the variables exactly equal as some class name.

So if you replace the name of your variable for myCylinder for example, and your code now looks like that:

public class SwipeControl : MonoBehaviour {

    public Transform myCylinder;

    void Update()
    {
        if (Input.touchCount == 1)
        {
            // GET TOUCH 0
            Touch touch0 = Input.GetTouch(0);

            // APPLY ROTATION
            if (touch0.phase == TouchPhase.Moved)
            {
                myCylinder.transform.Rotate(Vector3.Right, touch0.deltaPosition.x, Space.World);
            }

        }
    }
}

Tell me if changing the name and setting the reference from Editor it works.

EDIT: Take care with the Rotate function, if you are entering 3 arguments, they should be Rotate(Vector3 axis, float angle, Space relativeTo = Space.Self);

So you are are currently applying 0 degrees of difference!

Here is the documentation link to Rotate function, and all the differenct constructors and overload methods that you can use:

https://docs.unity3d.com/ScriptReference/Transform.Rotate.html

Upvotes: 1

Ryanas
Ryanas

Reputation: 1827

Are you using touch or mouse when you're testing this swiping?

Touch only works for touches, not mouse clicks.

Have you tried using the mouse input to move it around?

public class SwipeControl : MonoBehaviour {

    public Transform cylinder;
    private float sensitivity = 10f;

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            float xAxis = Input.GetAxis("Mouse X");
            cylinder.Rotate(0, -xAxis * sensitivity * Time.deltaTime, 0);
        }
    }
}

Upvotes: 1

Related Questions