La pregunta fué respondida y una respuesta ha sido aceptada
Vector3.back not working
Hi, I'm doing a 2D arcade game for Android devices and I'm having an issue with Vector3.back. What I'm trying to achive is that the player avatar moves to the part of the screen that the player had touched. Vector3.left, .right and .forward are working nice but when I use Vector3.back or -Vector3.forward the object doesn't moves to the touched position. The script I'm using is the following one (if someone knows a better and cheaper way to do this I'd be pleased to know :D):
if (mobileControls == true) {
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Stationary) {
double halfXScreen = Screen.width / 2.0;
double halfZScreen = Screen.height / 2.0;
Vector3 touchPosition = Input.GetTouch(0).position;
if(touchPosition.x < halfXScreen) { //works nice
gameObject.transform.Translate(Vector3.left * speed * Time.deltaTime);
}
else if (touchPosition.x > halfXScreen) { //works nice
gameObject.transform.Translate(Vector3.right * speed* Time.deltaTime);
}
if(touchPosition.z < halfZScreen) { //works nice
gameObject.transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
else if (touchPosition.z > halfZScreen) { //doesn't works :(
gameObject.transform.Translate(Vector3.back * speed * Time.deltaTime);
}
}
I'm using Unity 5.4.1f1 Personal Edition (64 bits)
Answer by saschandroid · Oct 24, 2016 at 09:30 PM
Input.GetTouch(0).position
gives you a Vector2
. With Vector3 touchPosition = Input.GetTouch(0).position;
you turn it into Vector3
, where the z-component of the vector will always be 0. So touchPosition.z < halfZScreen
is always true and touchPosition.z > halfZScreen
always false and therefor the translation in Vector3.back direction is never called. Use touchPosition.y
instead of touchPosition.z
and see if it works for you.
Follow this Question
Related Questions
How to replace KeyCode.Space with a simple tap on Android? 1 Answer
How can convert keyboard controller to touchscreen(android .ios ...etc) 1 Answer
Unity 2d android game How to "freeze" position on Y axis 1 Answer
Touchscreen Movement?? 1 Answer
i want to move object only when i swipe on screen not when touch, Unity 2d Android 0 Answers