How to move (translation or else) a GameObject from his position to a xyz (Vector3)?
[EDIT] Have a cube/GO that I want to move to a specific location on the terrain slowly, using Time.deltaTime . I don't want it to suddenly appear at that position.
Could you be more specific? In scripting you normally move a non-physics GameObject with the methods defined on transform. So something like:
but I doubt that's what you're after.
The easy, built-in way is to use a Lerp function. The Lerp function takes a start and end argument, and a floating point number which you can think of as being the percentage complete of the movement. Usually this argument is based on time. So at time=0.0 Lerp will return the first number, at 1.0 it will return the 2nd number, and for numbers less than 1.0 it will return some number in-between.
The Vector3 class has a Lerp function, so you can use that to calculate points between the start and end positions.
That just leaves the question of what to pass in for the last argument. If you store the starting time (startTime = Time.time) right when the movement starts, you can pass in t = (Time.time - startTime) for the third argument. This would finish the movement after one second. To make it last twice as long, multiply t by 0.5. To make it twice as fast, multiple t by 2.
You end up with something like: transform.position = Vector3.Lerp(startPos, endPos, speed * (Time.time - startTime)); You would typically do this in your object's Update function. Every frame your object moves a bit further along.
So that's the basic approach. For fancier movement, instead of linear interpolation (Lerp) you could instead use a function that starts slow ("ease-in") and/or slows down at the end ("ease-out"). The Unity wiki has some functions that perform these kinds of effects.
answered Nov 26, 2009 at 04:16 AM
What if I want the user to click on an object in 3D space and then the camera moves to a particular location? Where would I put this code?
answered Mar 26, 2010 at 05:11 PM
I don't think that you need it anymore , but it would be something like this:
Create a static boolean variable with its value false (static var myBool : boolean = false;) Write a code : when you click on that object myBool will get the value true and if myBool is true then Lerp the position...
script on the camera (CameraScript.js)
the script on the object (you want the user to click):
of course you can use:
I wrote both of them cuz' of some bad experiences in the past ...
answered May 15, 2011 at 02:05 PM