So I've been trying to get started with game development for Android using Unity3D. For my first project I've made a simple cube that you can spin using touch. For that I have the following code:

using UnityEngine;
using System.Collections;

public class TouchScript : MonoBehaviour {

float speed = 0.4f;
bool canRotate = false;
Transform cachedTransform;

public bool CanRotate {
    get { return canRotate; } 
    private set { canRotate = value; } 

void Start () {
    // Make reference to transform
    cachedTransform = transform;

// Update is called once per frame
void Update () {
    if (Input.touchCount > 0) {
        Touch touch = Input.GetTouch (0);

        // Switch through touch events
        switch (Input.GetTouch (0).phase) {
        case TouchPhase.Began:  
            if (VerifyTouch (touch))
                CanRotate = true;
        case TouchPhase.Moved:  
            if (CanRotate)
                RotateObject (touch);
        case TouchPhase.Ended:  
            CanRotate = false;

bool VerifyTouch (Touch touch) {
    Ray ray = Camera.main.ScreenPointToRay (touch.position);
    RaycastHit hit;

    // Check if there is a collider attached already, otherwise add one on the fly
    if (collider == null) gameObject.AddComponent (typeof(BoxCollider));

    if (Physics.Raycast (ray, out hit)) {
        if (hit.collider.gameObject == this.gameObject)
            return true;
    return false;

void RotateObject (Touch touch) {
    cachedTransform.Rotate (new Vector3 (touch.deltaPosition.y, -touch.deltaPosition.x, 0) * speed, Space.World);


The above code works fine. However, I'm wondering how I can keep the cube spinning after the user lifts his finger. The user should be able to "fling" the cube, which would keep spinning and after a while would slowly come to a stop due to drag.

Should I do this using AddForce or something? I'm really new to this stuff so I'd like it if you guys could point me in the right direction here :) .


Right now, you're feeding the delta directly into the Rotate() method.

Instead, try saving the delta to a temporary Vector3 struct and decaying the value over time. The best way to do this is using a co-routine.

I also noticed that CanRotate is being set to false when the touch ends, which will make the check for RotateObject() fail, so I suggest you use check against the temporary value to determine if you can fling it again.

  • \$\begingroup\$ This is a good start, could you possibly elaborate on your answer - what code would you put in place? \$\endgroup\$ Jan 15 '14 at 10:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .