- Home /
C#: Move a gameobject from a random location?
Hi I have a game object that spawns at a random location on the Y axis and moves along the X axis. Is there any way I could make it move(travel there, not just appear) to a specific XYZ location when it its a certain point on the X axis?
Any help would be greatly apreciated :)
Have you considered using iTween(free in the asset store)? It will do all the math for you and this is a common usage.
I have tried to figure it out, but have no clue as of how to get it working.
iTween.$$anonymous$$oveTo(gameObject, Vector3(2,0,0), 3);
I put this where I want it to happen in the script attached to the gameObject but I get this error message:
Expression denotes a
type', where a
variable',value' or
method group' was expected
Anyone got an idea how I should set it up properly?
This is a frequently asked question. In addition to iTween, take a look at $$anonymous$$oveObject. And to code it yourself, you will find numerous examples if you search this list for 'Lerp' or '$$anonymous$$oveTowards'.
You need a new before Vector3().
iTween.$$anonymous$$oveTo(gameObject, new Vector3(2.0f, 0.0f, 0.0f), 3.0f);
Answer by hoy_smallfry · Feb 05, 2013 at 07:55 PM
http://en.wikipedia.org/wiki/Linear_interpolation
Psuedo-code (to give you the idea):
function start()
{
timeElapsed = 0
startPoint = the game object world position
}
function move_to(Vector3 targetPoint)
{
timeElapsed = 0
endPoint = targetPoint
}
function update()
{
if timeElapsed < totalMovementDuration, then
{
durationInterval = timeElapsed / totalMovementDuration
game object world position = linear interpolate (startPoint, endPoint) with durationInterval
}
else
{
startPoint = the game object world position
}
timeElapsed + Time.deltaTime;
}
Unity has Vector3.Lerp() function for linear interpolation, try it out.
Thank you, robertbu's comment helped, but I'll be checking this out too :D