Sunday, May 29, 2016

c# - Smoother object movement in Unity?


I'm using this code in my script to move a gameobject:


void Update () {

// Move the object forward along its z axis 1 unit/second.
transform.position = new Vector2(transform.position.x , transform.position.y - 0.2f);


}

On screen the movement is a bit jaggy and not fluent.


Is there a different approach?


Hint: Please do not suggestion to use rigidbody functions since adding rigidbody would disrupt everything I did.


Can I use FxedUpdate?


Mirza



Answer



You can use Update method and just multiply velocity with Time.deltaTime. But when you need more complex movement than "move on const velocity" better use both Update and FixedUpdate. Method FixedUpdate should chooses current velocity for object. For example, if you want to move object to specified position FixedUpdate method should calculates velocity depends on current object position and target position. Method Update in this case will be used for smoothing movement, it will not change real position of object but recalculates each time. Here example:


private Vector3 fixed_position;

private Vector3 velocity;

void FixedUpdate() {
// apply previous velocity
fixed_position += velocity * Time.fixedDeltaTime;

// calculate new velocity
velocity = new Vector3(0.0f, 0.0f, 1.0f);
}


void Update() {
// recalculate smoothed position of object
transform.position = fixed_position + velocity * (Time.time - Time.fixedTime);
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...