1
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ That is not unit/second. You'll need to multiply all your movements by Time.deltaTime \$\endgroup\$ – Ben Dec 25 '14 at 10:34
  • \$\begingroup\$ how is this done? \$\endgroup\$ – mirzahat Dec 25 '14 at 11:03
3
\$\begingroup\$

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);
}
\$\endgroup\$
  • \$\begingroup\$ transform.position = new Vector2(transform.position.x , transform.position.y - movespeed) * Time.deltaTime; does not work...it gives me odd results \$\endgroup\$ – mirzahat Dec 25 '14 at 11:42
  • \$\begingroup\$ ransform.position = new Vector2(transform.position.x, transform.position.y - (movespeed * Time.deltaTime)); did the trick \$\endgroup\$ – mirzahat Dec 25 '14 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.