- Home /
Game Object Follow finger
I am making a game where I need the x touch to follow a gameobject so I can slide it from side to side. I am a beginner so I'm not sure what to do.
Answer by ElijahShadbolt · Feb 04, 2018 at 03:16 AM
As a quick solution, use Input.mousePosition and Camera.main.ScreenPointToWorldPoint. You could also get individual touch positions with Input.touches.
FollowTouch.cs
using UnityEngine;
// Attach this component to the GameObject you want to follow the touch position.
public class FollowTouch : MonoBehaviour
{
// every frame
void Update ()
{
// if left-mouse-button is being held OR there is at least one touch
if (Input.GetMouseButton(0) || Input.touchCount > 0)
{
// get mouse position in screen space
// (if touch, gets average of all touches)
Vector3 screenPos = Input.mousePosition;
// set a distance from the camera
screenPos.z = 10.0f;
// convert mouse position to world space
Vector3 worldPos = Camera.main.ScreenToWorldPoint(screenPos);
// get current position of this GameObject
Vector3 newPos = transform.position;
// set x position to mouse world-space x position
newPos.x = worldPos.x;
// apply new position
transform.position = newPos;
}
}
}
Tested with mouse. I have not tested with touches.
I put it on my object and all that happened was it went to the far left side and did nothing else.
Never $$anonymous$$d I figured it out myself with a simpler solution, I'm not sure if it will work on touch though. gameObject.transform.position = new Vector3(Input.mousePosition.x, 343, 0);
With my script you must hold the left mouse button down.
Your answer
![](https://koobas.hobune.stream/wayback/20220612151902im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Player not following touch after camera is rotated? 0 Answers
How to make 2 or more Objects to follow 2 or more fingers 1 Answer
Camera rotation around player while following. 6 Answers
player following touch position 0 Answers
Touch Follow 3d. 1 Answer