Unity How to limit rotation of canon with touch for Android
I'm creating a small 2D game that fires an object from a canon for Android. To make the controls easy for the user I've decided on touch input for one finger to swipe up or down to rotate the angle of the canon. (Later I'll hopefully add a means to fire a projectile with the other finger).
The problem I'm having is limiting the angle between what the inspector says is 0 degrees (horizontal) and 70 degrees (not completely pointing up). Here's what I have so far:
using UnityEngine;
using System.Collections;
public class SwipeRotate : MonoBehaviour {
public GameObject myGameObject;
// Allows rotation of target object via touch vertically
void Update ()
{
if (Input.touchCount == 1)
{
Debug.Log ("Z Rotation = " + myGameObject.transform.rotation.z);
//if (myGameObject.transform.rotation.z >= 0f && myGameObject.transform.rotation.z <= 6f)
{
// Get Touch 0
Touch touch0 = Input.GetTouch(0);
// Apply The Rotation
if (touch0.phase == TouchPhase.Moved)
{
myGameObject.transform.Rotate(0f, 0f, touch0.deltaPosition.y);
}
}
}
}}
(I've commented out the conditional line for now).
I was hoping to use Mathf.Clamp, but all the examples rely on me using vector 3 for rotation - and as you can see I didn't use that method to rotate the canon as I'm not sure how to change the code to work well.
The problem with my current 'fix' is that the canon inevitably gets stuck when it reaches one of it's maximums or minimums.
I've looked into how this limiting is done with the mouse, but I couldn't find a good example where the mouse moves and object but is limited between two fixed points. A real head scratcher for me!
I have another question regarding this, and that's regarding the angles. The inspector shows numbers that don't tally with my debug I added. Am I missing something?
Any help appreciated, thanks, Jay.
Your answer
![](https://koobas.hobune.stream/wayback/20220612063603im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Android Touch Double Jump - Not working 0 Answers
Android/Apple native plugin for touch input? 0 Answers
Android| Camera scrolling 1 Answer
How to ignore touches on a layer 0 Answers