- Home /
How to make the object player followsmooth2D the mouse or the touch?
I am thinking in buying unity but i am being beaten up by a simle coding task that is to create all types of controlls for the iphone. I have completed the joypad tutorial BUT i am having a real hard time trying to find the DAM mouse positions and realocate that on the position of my object that controls the SmoothFollow2D.js script ( as I really don't use java I ask for a resonable answer to this simple task in C sharp ) a task sooo simple that in itorque i can make it, in Gamesalad i can make it ( in 1 minute) but in unity I can't!!
I am seeing that unity is very flexible and transparent in many things but in Input it lacks ( very hard ) tutorials especially regarding touch and accelerometer functionalities!!
A simple code like this ( the object that my player will lock the SmoothFollow2D.js) :
using UnityEngine; using System.Collections;
public class MousePosition : MonoBehaviour { private float y; private float x;
void Update() { if (Input.GetMouseButtonDown(0)) { y = Input.mousePosition.y; x = Input.mousePosition.x; }
transform.Translate(x, y, Time.deltaTime);
}
}
and then after I choose my player to follow this object I can see that my player follows him, but when i click on the screen to test if i can make it follow my click the object goes up-right and stays there?
What am I doing wrong here?
Answer by lhk · Oct 24, 2010 at 01:46 PM
The mouse position is given in Screen coordinates. Therefore you have two values x and y. However the y in the Scene regards the heigth of your objects - unless you have turned everything by 90 degrees. You should use the following:
void Update() {
if (Input.GetMouseButtonDown(0))
{
y = Input.mousePosition.y;
x = Input.mousePosition.x;
}
Vector3 move=new Vector3(x,0,y);
move*=movespeed;
move*=Time.deltaTime;
transform.Translate(move);}
As you see the mouse's y coordinate maps to the world's z coordinate.
Answer by beatrage · Oct 26, 2010 at 06:32 PM
Thanks for the answer my friend but, this code makes my object goes to the right position of the screen and stays there!Also it doesn't update the inputs, strange my code above :
using UnityEngine; using System.Collections;
public class MousePosition2 : MonoBehaviour {
private float x, y; private float movespeed = 10;
void Update() { if (Input.GetMouseButtonDown(0)) { y = Input.mousePosition.y; x = Input.mousePosition.x; } Vector3 move = new Vector3(x,0,y); move*=movespeed; move*=Time.deltaTime; transform.Translate(move);
}
}
My camera is an Orthographic camera so I can only make 2D games ( for while of course ) but the problem here is that as I am making games for iphone I wanted not to depend only on touches but also use the Input.mousePosition to acess the screen input positions.
Answer by Casey · Dec 17, 2010 at 02:27 PM
you could try casting a ray from your finger position onto a surface and then moving the object to that position.
Your answer
