- Home /
transform.Position smoothly?
When i click on my object a counter goes + 1. Then when i press w it goes to that position. But it just "teleports" to the position. I want it to go smoothly to the position. How do i do that? Script:
var counter : int = 0;
function OnMouseDown () {
counter++;
}
function Update () {
if(Input.GetKey("w")) { transform.position.y = counter * Time.deltaTime;
} }
Answer by KellyThomas · Jan 19, 2014 at 10:54 PM
If you want something to happen "smoothly" it will involve making changes over a number of frames. Usually you will have some kind of trigger that will determine a target value, and then you will move closer to that target on each subsequent frame.
Here is one solution that uses `Vector3.MoveTowards()` to assist:
var counter : int = 0;
var movementStep : float = 0.1f;
private var targetPosition : Vector3;
private var shouldWeMove : boolean;
function OnMouseDown () {
counter++;
}
function Update () {
if(Input.GetKey("w")) {
shouldWeMove = true;
targetPosition = transform.position;
targetPosition.y = counter * Time.deltaTime;
}
if(shouldWeMove) {
transform.position = Vector3.MoveTowards(transform.position, targetPosition, movementStep );
}
}
Answer by DRProductions · Jan 19, 2014 at 10:41 PM
Try using Lerp:
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Lerp.html
http://unity3d.com/learn/tutorials/modules/beginner/scripting/lerp
Lerp always does the trick for me! If I helped remember to mark as answer!
imo lerp is the right answer because it allows for seamless control over the smoothing curve. MoveTowards
works well for simple linear smooth moves but it requires extra thought to apply smoothing with a curve.