- Home /
Rotate disk from above on touch to choose ball direction.
Hi,
I am trying to allow the user to set the direction of a ball before then choosing power and hitting GO. To do this i have a disk (which will later be completely transparent and just have an arrow on the edge as a transparent gif) sitting at the same X Y Z position as the ball; the ball is at the center of the disk.
I want the user to be able to rotate the disk to choose the direction the ball will follow, using a finger (IOS game). I would then send the rotation co-ordinates of the disk to the ball and add force in that direction when hitting the ball.
Thing is, I can't nail down how to rotate the disk on touch. I can rotate it in the wrong direction on touch - or I can rotate it correctly but then after the finge goes a certain distance it starts to spin the other way.
What I want is to be able to spin the disk like a DJ on a turntable; you can move your finger in a circular motion and the disk will spin with you.
This is the code I'm using so far:
public class CR_Rotate : MonoBehaviour {
[SerializeField]
float _speed = 1f;
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;
}
}
}
///
/// Verifies the touch.
///
///
/// The touch.
///
///
/// If set to true touch.
///
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;
}
///
/// Rotates the object.
///
///
/// Touch.
///
void RotateObject(Touch touch)
{
_cachedTransform.Rotate(new Vector3(0, -touch.deltaPosition.x,0)*_speed, Space.World);
}
}
Any help is greatly appreciated.
Your answer
Follow this Question
Related Questions
rotation in dragging 2 Answers
How to rotate an object based on angles? 1 Answer
Rotate on drag for IOS? 1 Answer
C# rotating a 3D object left&right using mousedrag 0 Answers
Drag Rotation Objet Snapping to 0,0,0 on new drag. 0 Answers