Vector3.MoveTowards (movement stops)

Hey guys,
I want to move an object from one position to another fluently. Lets say I want to move an object from current coordinates to new position (3, 1, 5) upon pressing up key once (not by holding it). I’m new to C# so I’m sorry for probably stupid and simple question :slight_smile:

My script looks like this:

void Update ()
{

if (Input.GetKeyDown(“up”))
{
transform.position = Vector3.MoveTowards (transform.position, new Vector3 (3, 1, 5), 1f * Time.deltaTime);
}
}

I guess the problem is the transform.position command executes just once (when i press up key), problem is i don’t know how to tell unity to keep changing the position after i once press that “up” key until object hits those (3,1,5) coordinates.

I’ll appreciate any help :slight_smile:

Ty

B.

You need to throw a boolean flag so it will keep moving.

bool isMoving = false;
Vector3 target = new Vector3 (3, 1, 5);
void Update () 
{
if (Input.GetKeyDown("up")) 
{isMoving = true;}
if(isMoving){
transform.position = Vector3.MoveTowards (transform.position, target, 1f * Time.deltaTime);
if(transform.position == target) isMoving = false;
}
}
1 Like

thx a lot for the reply, i was just about to write that i figured out the same after 2 hours of changing everything all over again :smile:

well i have similar thing, just maybe in maybe like 3 times more lines, but it finally works and my dungeon rat is moving as intended :slight_smile:

i also find out i should rather use quesions instead, will do it next time.

TY

Glad you got it worked out.