Touch to move and drag to rotate object
I need help :)
I want to move player with touch and rotate object when i drag them.
i create a script but problem is when i rotating ROT OBJECT my player also move to position where i touch on my screen.
(sorry for my bad english)
Answer by UnityCoach · Jan 10, 2017 at 03:31 PM
Input.GetTouch(0).phase == TouchPhase.Began
will always be true the frame you first touch the screen.
You need to Move your player on Input.GetTouch(0).phase == TouchPhase.Ended
, if there was no Input.GetTouch(0).phase == TouchPhase.Dragged
in between.
By the way, you may want to look at the EventSystem and IDragHandler, it's cross platform and a lot easier to work with than Input Touches.
There's also Input.GetTouch(0).phase == TouchPhase.Stationnary
which can help you.
Answer by Primorac · Jan 10, 2017 at 03:14 PM
@UnityCoach This is form my player movement:
public class Player : MonoBehaviour {
private bool flag = false;
private Vector3 endPoint;
public float duration = 50.0f;
private float yAxis;
public GameObject moveObject;
void Start(){
yAxis = moveObject.transform.position.y;
}
void Update () {
if((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
{
RaycastHit hit;
Ray ray;
#if UNITY_EDITOR
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
#elif (UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8)
#endif
if(Physics.Raycast(ray,out hit))
{
flag = true;
endPoint = hit.point;
endPoint.y = yAxis;
Debug.Log(endPoint);
}
}
if(flag && !Mathf.Approximately(moveObject.transform.position.magnitude, endPoint.magnitude)){
moveObject.transform.position = Vector3.Lerp(moveObject.transform.position, endPoint, 1/(duration*(Vector3.Distance(gameObject.transform.position, endPoint))));
}
else if(flag && Mathf.Approximately(moveObject.transform.position.magnitude, endPoint.magnitude)) {
flag = false;
Debug.Log("I am here. Click on some other point");
}
}
}
This script is for rotating object
public class rotatingObj : MonoBehaviour {
float rotSpeed = 20;
void OnMouseDrag()
{
float rotX = Input.GetAxis("Mouse X")*rotSpeed*Mathf.Deg2Rad;
transform.RotateAround(Vector3.up, -rotX);
}
}
Your answer
Follow this Question
Related Questions
Code help with mobile touch drag 3D Top Down 0 Answers
Struggling to get the rotation the player is moving in. 1 Answer
Grabbing the Relative eulerAngles.y of a Rotation 1 Answer
[C#] Rotate player to camera forward look 0 Answers
How can I make the camera not overreach a limit of rotation one axis. 0 Answers