How to calculate final force vector for the SKSpriteNode - ios

Good afternoon, everybody!
I am creating space game which has an effect similar to black hole's gravitational effect. Wherever the spaceship is going, the black hole will attract it, summing up all the vectors together.
I know SKFieldNode has a method customFieldWithEvaluationBlock: that allows to calculate everything myself, but might it be another way to do that?
I have tried almost every type in SKFieldNode, but nothing helped.
There are some side effects that don't suit me (i.e. If I use an electric or magnetic field, the object repels from the black hole)
Moreover, moving with SKAction (i.e. for the spaceship) doesn't allow me to sum all movement vectors together (I cant do
- (void)moveTo:duration: actions simultaneously, even with grouping the actions)
What can you advice me? Thank you in advance!

Related

How to track ping pong ball during game

I want to track a ping pong ball during game using opencv.
I'm not really sure how to tackle this problem. I tried using the orange color for detecting the ball each frame, via cv.inRange in RGB & HSV color space, however this did not work quite well. But could any kind of preprocessing help with that?
Also using MOG the ball can be seen quite well when moving (still a lot of noise due to moving people in the scene), was not the best way I guess.
Any tips how to achieve a ball tracking script?
Here is an image how the scene looks like in a "bad" frame (ball is in the middle above the net):
I'm happy to get any tips,
thanks in advance
One possibility is to just ask people not to walk behind the table, to try to improve the performance of background subtraction/MOG. You can then crop out the players, to focus only on the table area.
There are also algorithms to detect people - e.g. HOG-based methods. https://thedatafrog.com/en/articles/human-detection-video/ includes a tutorial.
You could also try blob detection after subtracting the background, and filtering out any blobs that are too large, since you know how big the ping-pong ball is.
Another concept is to keep track of where you think the ball should be based on previous measurements.

Directional Lights

I'm working on a game idea (2D) that needs directional lights. Basically I want to add light sources that can be moved and the light rays interact with the other bodies on the scene.
What I'm doing right now is some test where using sensors (box2d) and ccDrawLine I could achieve something similar to what I want. Basically I send a bunch of sensors from certain point and with raycast detect collisions, get the end points and draw lines over the sensors.
Just want to get some opinions if this is a good way of doing this or is other better options to build something like this?
Also I would like to know how to make a light effect over this area (sensors area) to provide a better looking light effect. Any ideas?
I can think of one cool looking effect you could apply. Put some particles inside the area where light is visible, like sparks shining and falling down very slowly, something like on this picture
Any approach to this problem would need to use collision detection anyway so your is pretty nice providing you have limited number of box2d objects.
Other approach when you have a lot of box2d objects I would think of is to render your screen to texture with just solid colors (should be fast) and perform ray tracing on that generated texture to find pixels that are going to be affected by light. That way you are limited to resolution not the number of box2d objects.
There is a good source code here about dynamic and static lights in a 2D space.
It's Ruby code but easy to understand so it shouldn't be long to port it to Obj-C/Cocos2D/box2D.
I really hope it will help you as it helped me.
Hm, interesting question. Cocos2D does provide some rather flexible masking effects. You could have a gradient mask that you lay over your objects, where its position depends on the position of the "light", thereby giving the effect that your objects were being coloured by the light.

Graphical effects like elastic tentacles in Contre Jour

I am wondering how beautiful is "Contre jour" game for IOS.
Especially i like elastic "tentacles",shown in this video on 2 min 20 seconds:
http://www.youtube.com/watch?v=ptdTdJarWLw
How can I implement such effects?
I know that there is technic called "Verlet integration" and even implementation of "verlet rope" for drawing ropes in cocos2d, but how to make such nice elastic effects to "tentacle" sprite?
I have experience of box2D usage, and may try to implement physics for this effect, but cann't find a solution how to draw sprite with such elastic morphing.
Can anybody help me or give some hints?
Just even explanation of technics, that can help me?
I have a little of experience in opengl, great cocos2d experience, so I plan to use cocos2d.
Sorry for bad english, I hope, you will understand my problem:)
If you use Box2D, you could try a distance joint with the frequencyHz and dampingRatio options set to non-default values. Perhaps a low frequency of around 4-6, and a damping of around 0.5-0.7 could be a good point to start from. You could think of frequency as how many times per second the joint tries to correct the distance, and damping as how well the distance is corrected each time. Setting the damping to a value lower than 1 will means the joint will be slower to correct the distance, and it will have a springy/rubbery behavior.
As for rendering, you could indeed use verlet integration for this. Take the two anchor points of the distance joint as the endpoints of the 'rope', and put a handful of points (doesn't look like too many would be necessary) in between them in an evenly spaced line. Every timestep, the points in between will simply move towards the average of the two points on either side of themselves. You could make the rope look tighter or looser by adjusting how far the inbetween points move to the target position each time step.
The final texture/sprite rendering would then take its position from the current location of the verlet points.

How to use the A* path finding algorithm on a grid less 2D plane?

How can I implement the A* algorithm on a gridless 2D plane with no nodes or cells? I need the object to maneuver around a relatively high number of static and moving obstacles in the way of the goal.
My current implementation is to create eight points around the object and treat them as the centers of imaginary adjacent squares that might be a potential position for the object. Then I calculate the heuristic function for each and select the best. The distances between the starting point and the movement point, and between the movement point and the goal I calculate the normal way with the Pythagorean theorem. The problem is that this way the object often ignores all obstacle and even more often gets stuck moving back and forth between two positions.
I realize how silly mu question might seem, but any help is appreciated.
Create an imaginary grid at whatever resolution is suitable for your problem: As coarse grained as possible for good performance but fine-grained enough to find (desirable) gaps between obstacles. Your grid might relate to a quadtree with your obstacle objects as well.
Execute A* over the grid. The grid may even be pre-populated with useful information like proximity to static obstacles. Once you have a path along the grid squares, post-process that path into a sequence of waypoints wherever there's an inflection in the path. Then travel along the lines between the waypoints.
By the way, you do not need the actual distance (c.f. your mention of Pythagorean theorem): A* works fine with an estimate of the distance. Manhattan distance is a popular choice: |dx| + |dy|. If your grid game allows diagonal movement (or the grid is "fake"), simply max(|dx|, |dy|) is probably sufficient.
Uh. The first thing that come to my mind is, that at each point you need to calculate the gradient or vector to find out the direction to go in the next step. Then you move by a small epsilon and redo.
This basically creates a grid for you, you could vary the cell size by choosing a small epsilon. By doing this instead of using a fixed grid you should be able to calculate even with small degrees in each step -- smaller then 45° from your 8-point example.
Theoretically you might be able to solve the formulas symbolically (eps against 0), which could lead to on optimal solution... just a thought.
How are the obstacles represented? Are they polygons? You can then use the polygon vertices as nodes. If the obstacles are not represented as polygons, you could generate some sort of convex hull around them, and use its vertices for navigation. EDIT: I just realized, you mentioned that you have to navigate around a relatively high number of obstacles. Using the obstacle vertices might be infeasible with to many obstacles.
I do not know about moving obstacles, I believe A* doesn't find an optimal path with moving obstacles.
You mention that your object moves back and fourth - A* should not do this. A* visits each movement point only once. This could be an artifact of generating movement points on the fly, or from the moving obstacles.
I remember encountering this problem in college, but we didn't use an A* search. I can't remember the exact details of the math but I can give you the basic idea. Maybe someone else can be more detailed.
We're going to create a potential field out of your playing area that an object can follow.
Take your playing field and tilt or warp it so that the start point is at the highest point, and the goal is at the lowest point.
Poke a potential well down into the goal, to reinforce that it's a destination.
For every obstacle, create a potential hill. For non-point obstacles, which yours are, the potential field can increase asymptotically at the edges of the obstacle.
Now imagine your object as a marble. If you placed it at the starting point, it should roll down the playing field, around obstacles, and fall into the goal.
The hard part, the math I don't remember, is the equations that represent each of these bumps and wells. If you figure that out, add them together to get your final field, then do some vector calculus to find the gradient (just like towi said) and that's the direction you want to go at any step. Hopefully this method is fast enough that you can recalculate it at every step, since your obstacles move.
Sounds like you're implementing The Wumpus game based on Norvig and Russel's discussion of A* in Artifical Intelligence: A Modern Approach, or something very similar.
If so, you'll probably need to incorporate obstacle detection as part of your heuristic function (hence you'll need to have sensors that alert your agent to the signs of obstacles, as seen here).
To solve the back and forth issue, you may need to store the traveled path so you can tell if you've already been to a location and have the heurisitic function examine the past N number of moves (say 4) and use that as a tie-breaker (i.e. if I can go north and east from here, and my last 4 moves have been east, west, east, west, go north this time)

Surface Detection in 2d Game?

I'm working on a 2D Platform game, and I was wondering what's the best (performance-wise) way to implement Surface (Collision) Detection.
So far I'm thinking of constructing a list of level objects constructed of a list of lines, and I draw tiles along the lines.
alt text http://img375.imageshack.us/img375/1704/lines.png
I'm thinking every object holds the ID of the surface that he walks on, in order to easily manipulate his y position while walking up/downhill.
Something like this:
//Player/MovableObject class
MoveLeft()
{
this.Position.Y = Helper.GetSurfaceById(this.SurfaceId).GetYWhenXIs(this.Position.X)
}
So the logic I use to detect "droping/walking on surface" is a simple point (player's lower legs)-touches-line (surface) check
(with some safety approximation
- let`s say 1-2 pixels over the line).
Is this approach OK?
I`ve been having difficulty trying to find reading material for this problem, so feel free to drop links/advice.
Having worked with polygon-based 2D platformers for a long time, let me give you some advice:
Make a tile-based platformer.
Now, to directly answer your question about collision-detection:
You need to make your world geometry "solid" (you can get away with making your player object a point, but making it solid is better). By "solid" I mean - you need to detect if the player object is intersecting your world geometry.
I've tried "does the player cross the edge of this world geometry" and in practice is doesn't work (even though it might seem to work on paper - floating point precision issues will not be your only problem).
There are lots of instructions online on how to do intersection tests between various shapes. If you're just starting out I recommend using Axis-Aligned Bounding Boxes (AABBs).
It is much, much, much, much, much easier to make a tile-based platformer than one with arbitrary geometry. So start with tiles, detect intersections with AABBs, and then once you get that working you can add other shapes (such as slopes).
Once you detect an intersection, you have to perform collision response. Again a tile-based platformer is easiest - just move the player just outside the tile that was collided with (do you move above it, or to the side? - it will depend on the collision - I will leave how to do this is an exercise).
(PS: you can get terrific results with just square tiles - look at Knytt Stories, for example.)
Check out how it is done in the XNA's Platformer Starter Kit Project. Basically, the tiles have enum for determining if the tile is passable, impassable etc, then on your level you GetBounds of the tiles and then check for intersections with the player and determine what to do.
I've had wonderful fun times dealing with 2D collision detection. What seems like a simple problem can easily become a nightmare if you do not plan it out in advance.
The best way to do this in a OO-sense would be to make a generic object, e.g. classMapObject. This has a position coordinate and slope. From this, you can extend it to include other shapes, etc.
From that, let's work with collisions with a Solid object. Assuming just a block, say 32x32, you can hit it from the left, right, top and bottom. Or, depending on how you code, hit it from the top and from the left at the same time. So how do you determine which way the character should go? For instance, if the character hits the block from the top, to stand on, coded incorrectly you might inadvertently push the character off to the side instead.
So, what should you do? What I did for my 2D game, I looked at the person's prior positioning before deciding how to react to the collision. If the character's Y position + Height is above the block and moving west, then I would check for the top collision first and then the left collision. However, if the Character's Y position + height is below the top of the block, I would check the left collision.
Now let's say you have a block that has incline. The block is 32 pixels wide, 32 pixels tall at x=32, 0 pixels tall at x=0. With this, you MUST assume that the character can only hit and collide with this block from the top to stand on. With this block, you can return a FALSE collision if it is a left/right/bottom collision, but if it is a collision from the top, you can state that if the character is at X=0, return collision point Y=0. If X=16, Y=16 etc.
Of course, this is all relative. You'll be checking against multiple blocks, so what you should do is store all of the possible changes into the character's direction into a temporary variable. So, if the character overlaps a block by 5 in the X direction, subtract 5 from that variable. Accumulate all of the possible changes in the X and Y direction, apply them to the character's current position, and reset them to 0 for the next frame.
Good luck. I could provide more samples later, but I'm on my Mac (my code is on a WinPC) This is the same type of collision detection used in classic Mega Man games IIRC. Here's a video of this in action too : http://www.youtube.com/watch?v=uKQM8vCNUTM
You can try to use one of physics engines, like Box2D or Chipmunk. They have own advanced collision detection systems and a lot of different bonuses. Of course they don't accelerate your game, but they are suitable for most of games on any modern devices
It is not that easy to create your own collision detection algorithm. One easy example of a difficulty is: what if your character is moving at a high enough velocity that between two frames it will travel from one side of a line to the other? Then your algorithm won't have had time to run in between, and a collision will never be detected.
I would agree with Tiendil: use a library!
I'd recommend Farseer Physics. It's a great and powerful physics engine that should be able to take care of anything you need!
I would do it this way:
Strictly no lines for collision. Only solid shapes (boxes and triangles, maybe spheres)
2D BSP, 2D partitioning to store all level shapes, OR "sweep and prune" algorithm. Each of those will be very powerfull. Sweep and prune, combined with insertion sort, can easily thousands of potentially colliding objects (if not hundreds of thousands), and 2D space partitioning will allow to quickly get all nearby potentially colliding shapes on demand.
The easiest way to make objects walk on surfaces is to make then fall down few pixels every frame, then get the list of surfaces object collides with, and move object into direction of surface normal. In 2d it is a perpendicular. Such approach will cause objects to slide down on non-horizontal surfaces, but you can fix this by altering the normal slightly.
Also, you'll have to run collision detection and "push objects away" routine several times per frame, not just once. This is to handle situations if objects are in a heap, or if they contact multiple surfaces.
I have used a limited collision detection approach that worked on very different basis so I'll throw it out here in case it helps:
A secondary image that's black and white. Impassible pixels are white. Construct a mask of the character that's simply any pixels currently set. To evaluate a prospective move read the pixels of that mask from the secondary image and see if a white one comes back.
To detect collisions with other objects use the same sort of approach but instead of booleans use enough depth to cover all possible objects. Draw each object to the secondary entirely in the "color" of it's object number. When you read through the mask and get a non-zero pixel the "color" is the object number you hit.
This resolves all possible collisions in O(n) time rather than the O(n^2) of calculating interactions.

Resources