- Home /
Move towards touch position
I am kind a new to unity and JS so this may be a stupid question but I have been searching for hours to find an answer, still no succes :/
I am working on a small game where the player needs to go hit objects (the object has a bounce) currently I am using this wasd script to test the game on a desktop, this one works perfectly fine.
var moveUp : KeyCode;
var moveDown : KeyCode;
var moveLeft : KeyCode;
var moveRight : KeyCode;
static var speed : float = 10;
function Update () {
if (Input.GetKey(moveUp))
{
rigidbody2D.velocity.y = speed;
}
else if (Input.GetKey(moveDown))
{
rigidbody2D.velocity.y = speed * -1;
}
else if (Input.GetKey(moveLeft))
{
rigidbody2D.velocity.x = speed * -1;
}
else if (Input.GetKey(moveRight))
{
rigidbody2D.velocity.x = speed;
}
else
{
rigidbody2D.velocity.y = 0;
rigidbody2D.velocity.x = 0;
}
}
At this moment I am working on the following script for touch controls, unfortunately it shows the following error "BCE0017: The best overload for the method 'UnityEngine.Vector3.MoveTowards(UnityEngine.Vector3, UnityEngine.Vector3, float)' is not compatible with the argument list '(float, float, float)'."
If someone could please help me solve this script I would really appriciate it.
var speed : float = 10;
var pos : Vector3;
function Start (){
Screen.sleepTimeout = SleepTimeout.NeverSleep;
}
function Update(){
MoveUpdate();
}
function MoveUpdate(){
if (Application.platform == RuntimePlatform.Android){
pos = Camera.main.ScreenToWorldPoint(Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y));
}
else{
pos = Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x, Input.mousePosition.y));
}
transform.position = Vector3.MoveTowards(pos.x,pos.y, speed);
}
Thanks!
Sorry to be a grumpy old sod, but what part of:
UnityEngine.Vector3.$$anonymous$$oveTowards(UnityEngine.Vector3, UnityEngine.Vector3, float)' is not compatible with the argument list '(float, float, float)'
is hard to understand? The first part of that message tells you the types for each argument, and the second part gives the types that you are passing in.
I know what the error means, I just don't know how to resolve it in a proper way, how do I get the script to work?
What Graham Dunnett was trying to say is, that your code in line 25 has wrong parameters (it's all floats, but needs Vector3, Vector3, float) try that:
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, pos, speed);
$$anonymous$$ultiply speed by Time.deltatime and you're good to go