#pragma strict
var speed : float = 2f;
public var worldPos:Vector2;
public var target : Transform;
public var cameraloc:Camera;
function Start () {
}
function Update () {
var mousePos:Vector2;
cameraloc = GameObject.Find("Camera").GetComponent(Camera);
mousePos = Input.mousePosition;
worldPos = cameraloc.ScreenToWorldPoint(mousePos);
if (Input.GetButtonDown ("Fire1")) {
Debug.Log("Move!");
transform.position = Vector2.MoveTowards(target.position, worldPos, speed);
}
}
When I click somewhere, my object is just teleporting, but not to my location, but to a portion of that location. In case if you don’t understand: let’s say my object has to SMOOTHLY travel 10m. When I click on a location, it just go 2m , but instantly. So, my object travel 10m only if I click 5 times, which is not what I want.
What is wrong ?
Nonono… I want it to to MoveTowards, but it teleports, I DON’T want it to teleport. Do you want a video proof ? I can do it fast.
edit: I tried to use transform.position = worldPos and it teleports me to the location, but I want it to move smoothly, so I use Move Towards. By this, I get that the problem is the MoveTowards part, but I still can’t solve it.
transform.position = Vector2.MoveTowards(target.position, worldPos, speed);
The first parameter should be the starting point, the second should be the destination. Unless “target” is the same transform, you’re going to need to replace target.position with transform.position, or vice versa.
Secondly, I’m guessing you want the object to move over time. MoveTowards will only give you the next position, not do the whole series of movements required. For that, you’d set a Vector2 on mouse down, and have the Update method continue to do MoveTowards until the Vector2 is reached.
So what should I do ? I tried to use Lerp too but, It didn’t work at all. If you don’t mind, can you help me making this code work properly ? I will be really thankfull.
Your code is wrong if I understand what you want to do.
MoveTowards moves from current position to target position. You are moving the transform position from the mouse position to the target position, which I assume is under the mouse. Replace the mouse position with transform.position.
Not really. Actually I want to move my ‘target’ to the click location (worldPos). I tried your code but it didn’t work (it didn’t move but in my console it sais “Move!”.
I think the problem is that you’re using MoveTowards inside the Fire button, which is a quick event.
I use a boolean to move Objects with MoveTowards, so when you hit the Fire button, set a public bool like “isMoving” to true, move this line outside the Fire button event, and wrap it into an if statement, something like:
public bool isMoving;
…
…
if (Input.GetButtonDown ("Fire1")) {
isMoving = true;
}
if(isMoving){
transform.position = Vector2.MoveTowards(target.position, worldPos, speed);
}