- Home /
Making a gameobject move to a position
So I have this game object that I want to move to a position.
What I do not want to do is to have a FixedUpdate function that has anything similar to
MovePosition(pos speed Delta time)
Is there a way to only call a function once, and it does the moving for you instead? I don't want it to teleport from point A to B so just setting the transform.position = newPos isnt something that I am looking for.
The only thing that I can think of is using a coroutine, but I was wondering if there is a function that guarantees that it moves to a point without me having to update its position every frame in the Update function.
Answer by Vice_Versa · Aug 18, 2015 at 07:02 AM
i dont know why youre avoiding the update function.. that seems strange to me but there are a few ways to do what youre asking.
you can make a new animation that moves one object to another then call animation.Play() on that gameobject
you could set up a while loop for example:
float secondX;
float secondy;
float secondz;
Vector3 firstPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
Vector3 secondPosition = new Vecotr3(whatever, whatever, whatever);
while(transform.position.x < secondX)
{
transform.position = new Vecotr3(transform.position.x + 0.001f, transform.position.y, trnasform.position.z);
}
though, the above way is technically just you coding something similar to an update function
and yes, coroutines would also be another way.
I'm not sure what thought process was going through me when I was writing this question. I also find it strange how I did not want to use the update function. I'm sorry for the inconvenience.
Answer by Tom01098 · Aug 18, 2015 at 08:27 AM
According to http://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html , the code you need is simply
public Transform target;
public float speed;
void Update() {
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
So, yes, it does have to be in an updating function to my knowledge, but it's a very simple code.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
How to debug the object position in the grid of objects? 0 Answers
How to convert game object world position to hex grid cell coordinates? 1 Answer
Why Do My Obstacles Do This In My Object Pooler? 1 Answer
How to increment value of axis when something happens 2 Answers