- Home /
move an object towards the touch or mouseclick position
hey. i have a cube which is going round and round along the a and y axes and i need it to translate it towards the place where the user touches or clicks the screen with a limited speed. the object must move in the direction as long as the finger or cursor is pressed. currently i an using a code which stores the location of the object and its change in position every second. here's the code
//Unity will constantly check the position of the GameObject. function Update () {
//Creates a variable to check the objects position.
myPosition = transform.position;
//Prints the position to the Console.
Debug.Log(myPosition); }
Answer by 767_2 · Sep 10, 2014 at 10:49 AM
void Update()
{
if(Input.GetMouseButtonDown(0))
{
newPosition.x = Input.mousePosition.x;
newPosition.y = Input.mousePosition.y;
//set new position as destination of your object
}
Answer by NickP_2 · Sep 10, 2014 at 10:53 AM
In human language: - Get the world position of the mouse position (worldPos vs screenPos) - get the normalized direction, formula: direction = normalize(end position - currentposition), and multiply it by a certain speed. (always normalize, or else the speed ill be different each location
To get the position of the mouse, simple use:
Vector3 mousePos = Camera.Main.ScreenpointToWorldPoint(Input.MousePosition);
//Because the object's Z position has to be the same:
mousePos.z = transform.position.z;
Get normalized direction:
Vector3 dir = (mousePos - transform.position).normalized;
//Create final force where speed is a float
Vector3 force = dir * speed;
To noly execute this code when the mouse button is down, use:
if(Input.GetMouseButton(0))//0 is left, 1 is right
{
//....
}
Your answer
Follow this Question
Related Questions
Boat moving forward while rotating towards point 1 Answer
translate 2 Answers
Loop from Point A to Point B after Point C 2 Answers
touch move slide object 0 Answers
iOS -Touch position unchanged, deltaPosition reported -1 Answers