开发者

How to code a random movement in limited area

开发者 https://www.devze.com 2023-03-24 14:14 出处:网络
I have a limited area (screen) p开发者_开发百科opulated with a few moving objects (3-20 of them, so it\'s not like 10.000 :). Those objects should be moving with a constant speed and into random direc

I have a limited area (screen) p开发者_开发百科opulated with a few moving objects (3-20 of them, so it's not like 10.000 :). Those objects should be moving with a constant speed and into random direction. But, there are a few limitation to it:

  • objects shouldn't exit the area - so if it's close to the edge, it should move away from it
  • objects shouldn't bump onto each other - so when one is close to another one it should move away (but not get too close to different one).

On the image below I have marked the allowed moves in this situation - for example object D shouldn't move straight up, as it would bring it to the "wall".

How to code a random movement in limited area

What I would like to have is a way to move them (one by one). Is there any simple way to achieve it, without too much calculations?

The density of objects in the area would be rather low.


There are a number of ways you might programmatically enforce your desired behavior, given that you have such a small number of objects. However, I'm going to suggest something slightly different.

What if you ran the whole thing as a physics simulation? For instance, you could set up a Box2D world with no gravity, no friction, and perfectly elastic collisions. You could model your enclosed region and populate it with objects that are proportionally larger than their on-screen counterparts so that the on-screen versions never get too close to each other (because the underlying objects in the physics simulation will collide and change direction before that can happen), and assign each object a random initial position and velocity.

Then all you have to do is step the physics simulation, and map its current state into your UI. All the tricky stuff is handled for you, and the result will probably be more believable/realistic than what you would get by trying to come up with your own movement algorithm (or if you wanted it to appear more random and less believable, you could also just periodically apply a random impulse to a random object to keep things changing unpredictably).


You can use the hitTest: method of UIView

UIView* touchedView=[self.superview hitTest:currentOrigin withEvent:nil];

In This method you have to pass the current origin of the ball and in second argument you can pass nil.

that method will return the view with which the ball is hited.

If there is any hit view you just change the direction of the ball.

for border you can set the condition for the frame of the ball if the ball go out of the boundary just change the direction of the ball.

0

精彩评论

暂无评论...
验证码 换一张
取 消