- Home /
Moving the cube on a surface.
Hello everyone. I've got some really hard question for me. I have a cube and some surface where it moves. And I need to move the cube anywhere on the surface by touching of the finger(the cube should follow the touch). I already have a script that makes the cube move towards the touch but when I touch the screen it falls UNDER the surface and it cannot move forward. I'm just new to Unity so I don't have any ideas how do I do this. And also, for some reason cube always moves backwards when touching. Please help.
public GameObject cube;
public new GameObject camera;
void Update()
{
if (Input.touchCount > 0)
{
Vector3 touch = (Input.GetTouch(0).position);
if (Input.GetTouch(0).phase == TouchPhase.Stationary || Input.GetTouch(0).phase == TouchPhase.Moved)
{
float zDistance = cube.transform.position.z - camera.transform.position.z;
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.x, 0, zDistance));
transform.position = touchPosition;
}
}
}
Answer by mchts · Apr 18, 2019 at 01:43 PM
public GameObject cube;
public new GameObject camera;
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved)
{
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(touch.position); //this is the world coordinate representation of your touch position. You can use this as you wish
}
}
}
But when I use this as "transform.position = touchPosition" the cube just starts to fly up
If you want to move along just one axis use that value. For e.g. for x axis:
transform.position = new Vector3(touchPosition.x, transform.position.y, transform.position.z);
Nom I want to move along z too, on the surface, forward, backward etc,
Your answer
Follow this Question
Related Questions
On Collide script not working! 1 Answer
General mobile game developing questions 0 Answers
Possible to get touch area data? 1 Answer