0
\$\begingroup\$

I am making a 2D game with HTML5 Canvas. The game has several shapes and I want them to move all over the map randomly.

  1. However, if I just give them a constant angle to follow, they will all end up in a corner after a certain amount of time.

  2. Also, I am building this game with client-server so I don't want to send a lot of data. For example, I don't want to constantly update the angle on the server side and send it to the client.

That's why I want to generate a random position base on the shape's position on the big map.

For example, it's angle of movement will be tangent of it's (x,y). (It obviously won't work because it will get stuck on the sides of the map).

So what's a good way of generating the new coordinates base on it's current one?

\$\endgroup\$
2
\$\begingroup\$

What you need then is a function in the format:

xy nextPosition(seed, x, y) 

A function which takes a seed value, and a current x and y location, and returns a new x and y location based on noise functions which use the seed for randomness, so that no matter how many times the function is called, the result returned for any given set of input is always the same. All the server would need to do is sync the seed, x and y values initially of all objects in a scene across all clients and from that the client could correctly calculate every update the object position after that, as long as the clients all update at the same frame rate, eg: 60/sec.

As for the nextPosition() function itself, if you want to avoid walls you need to blend the result of two equations. One equation which will move the object away from the wall, and one equation which will move the object in a noise randomised direction based on the seed value. And you'd just blend between the results based on how close the object is to the wall. So that as the object approaches the wall, the desire to move away from it increasingly takes over until eventually it's the sole driving motivator. But in the middle of the arena, there'd be no urge to avoid walls at all and objects would roam freely.

Alternatively, the server could calculate target locations for objects to move towards, and sync those targets, and clients could just simulate those objects moving towards their targets with infrequent updates of target locations whenever an object is close to reaching it's target. That way you're not sending an update of direction at 60hz, just a new target location every second or so.

I hope either of those solutions help?

|improve this answer|||||
\$\endgroup\$

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.