Keep cube spinning after fling
Posted
by
Zero
on Game Development
See other posts from Game Development
or by Zero
Published on 2013-10-18T10:04:45Z
Indexed on
2013/10/18
10:19 UTC
Read the original article
Hit count: 244
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;
break;
case TouchPhase.Moved:
if (CanRotate)
RotateObject (touch);
break;
case TouchPhase.Ended:
CanRotate = false;
break;
}
}
}
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 :) .
© Game Development or respective owner