Sprite Moveto to every position with the same speed?

My monster will shoot the player, when the player enters the range, the bullet of the monster will perform " moveTo " to the character coordinates, the problem is that if the character standing too close to the bullet will fly very slowly because i fixed the move time moveTo.

I do not quite understand what you mean by this

the bullet will fly very slowly because I fixed the move time moveTo.

Do you mean you want to create a direct correlation between the bullet speed and the distance of the player?

1 Like

It’s very simple.

What you need is to do is calculate duration based on some time/velocity proportion.

You have to define for example given 1 second how much speed you want to cover in pixels.

For example you could write:

float speedPerSecond = 100.0f

The above would mean that your sprite will travel 100 pixels per second.

In your action code:

auto currentPosition = your_sprite->getPosition(); 
auto dstPosition = your_destination_position;   // some Vec2

// getDistance is an arbitrary Vec2 function to get the distance between two points
auto distance = currentPosition.getDistance(dstPosition);
auto duration = distance/speedPerSecond;             // This is the key part               
auto moveTo = MoveTo::create(duration, dstPosition);

your_sprite->runAction(moveTo);

If your distance is 50 your sprite will move to it’s destination in half a second.
If your distance is 1 it will move to it’s destination very quickly, precisely in 1/100 seconds.

I’m sure you get the point if you have any questions i’m all ears!

:slight_smile:

1 Like

@sheshmoshen with your solution need to stop previous action and start new one each time the player moves.

I think much simpler and effective is to calculate position by self in update method.

1 Like

I too like the update method for this.

1 Like

That’s a general problem with using any cocos2d Action, but his question was specifically
in the context of using MoveTo.

In general in-game animations I will always use the update() method but one-time animations I will use Action whenever I can. His use case is a bullet which I consider a one-time animation.

1 Like

This makes sense too. I’m looking at how I use Actions and I do have a lot outside of update()

1 Like

My point is that it will moveTo to a point whether far or near, the speed is the same

thank you :slight_smile: :slight_smile: