Animating with Tween to Keep X or Y the Same Value

Hello,

I am trying to animate some object using tween, but I need to keep either the same value for X or for Y. However, I cannot omit the value that must stay the same.

For example:

var tween = scene.tweens.add({
  targets: myObject,
  x: 500, 
  y: y,   // Must keep Y same, and cannot omit it.
  ease: 'Linear', 
  duration: 1000
});

I also tried something like:

y: += 0,

But doesn’t work either. Any idea?

neb

I don’t understand. What’s happening? If the y is changing, what’s changing it?

Thanks for the reply. My question be better asked like this: how can I reference the object being tweened, so that I can do something like:

y: myObject.y,

That should work. What happens?

Actually, my code somehow refers to the Y value of the object on page’s load, as the Tween engine seems to preset the values already on the moment of its creation. So if I create a tween and specify myObject.y = 40, then move myObject.y to 80 before executing the tween, the tween still uses the Y=40 value from when it was created (under my understanding and my tests).

To fix the issue, I cannot specify the myObject.y on the moment I create the tween, and instead use something like ‘+=0’ to dynamically set the Y to same value. To my surprise, setting:

y: += 0, // doesn't work: it seems to add some pixels on each iteration

but:

y: += 0.0, // works

Not sure if this is a bug, but it seems to solve my issue.

Thanks again.

If you don’t want to tween the y value, you can just omit it.

If you need a dynamic value, use

scene.tweens.add({
  y: () => myObject.y
  // …
});

Great, didn’t think of setting a dynamic value like this. Thanks!