Flash Games: Make a world continuous, circular - actionscript-3

I am writing now a flash game and I run into a an issue. I have a map for the game which is defined as a 2-D array, where each element represents a component of the map. The player is always in the center of the map.
The problem is when the player reaches one end of the map. Now it is empty space. I want that the player instead of seeing the empty space, to see another end of the map and in this way, the map will loo like it goes around.
So for example if the player goes to right he will eventually start seeing the the left side of the map and the world will look continuous.
Does anyone knows how to implement this functionality?

You could make the array 2 times and put the first one behind the second one again and than the second one behind the first etc etc..
It's done here with 2 pictures, just use the arrays instead:
//The speed of the scroll movement.
var scrollSpeed:uint = 2;
//This adds two instances of the movie clip onto the stage.
var s1:ScrollBg = new ScrollBg();
var s2:ScrollBg = new ScrollBg();
addChild(s1);
addChild(s2);
//This positions the second movieclip next to the first one.
s1.x = 0;
s2.x = s1.width;
//Adds an event listener to the stage.
stage.addEventListener(Event.ENTER_FRAME, moveScroll);
//This function moves both the images to left. If the first and second
//images goes pass the left stage boundary then it gets moved to
//the other side of the stage.
function moveScroll(e:Event):void{
s1.x -= scrollSpeed;
s2.x -= scrollSpeed;
if(s1.x < -s1.width){
s1.x = s1.width;
}else if(s2.x < -s2.width){
s2.x = s2.width;
}
}

You simply check if your player is about to get off the "right" or "left" edge of the map, and position him at the other edge. To draw a circular map, you can use the following technique: if you are about to draw a column of a number that exceeds the map's width, decrease that number by width and draw the column at resultant index; and if you are about to draw a column at index below zero, add width and draw the column at resultant index. If you are in troubles of making a hitcheck at continuous map's borders, you can employ the same trick to find neighbors. (The "circular array" is a pretty basic algorithmic problem, and is resolved in many ways already)

You have a few options here. You can do the pac-man style of just making your character pop up on the other side of the screen, but that would require you to abandon the cool bit of the character being in the middle at all times.
On to the real suggestions:
If you're not implementing your array as one solid object (i.e. making it draw individual collumns/rows at a time) then this is a no-brainer. Just have a function that returns the index of the next collumn/row, within certain bounds. Like, if your array is 40 elements wide, when it tries to draw element 41, subtract the size of the array, and make it draw element 1 instead.
If your array is one solid object (like if you drew it onto a stage object and are just manipulating that) and it's not very big, you could probably get away with drawing a total of four of them, and just having a new one cover up any whitespace that's about to appear. Like, as you approach the right edge of the first array, the second array moves to the right of it for a lawless transition.
If your array is a solid object and is very big, perhaps you could make eight buffer objects (one per edge and one per corner) that hold approximately half a screen's worth of the array. That way as you approach the right edge, you see the left edge, but then when you cross into the buffer zone, you could teleport the player to the corresponding position on the left of the array, which has the buffer for the right size. To the player, nothing has changed, but now they're on the other side of the world.

Related

How to remove something once drawn?

I'm using libgdx and recreating pac-man, I'm currently using this code to spawn in the pellets for the level (essentially they spawn everywhere that the walls and Pac-Man aren't)
for(int x = 1; x < 27; x++) {
normalPellet.setX((x * 70) + 25);
normalPellet.setY((y * 70) + 25);
if(!(normalPellet.overlaps(walls)) {
batch.draw(pellet,normalPellet.x,normalPellet.y);
pelletCount++;
}
}
My problem is that I don't know how to make it so that when Pac-Man moves over the pellets they get "eaten" and are removed from the field. When Pac-Man moves over them, they do disappear, but as soon as Pac-Man moves to a different place on the map they immediately reappear. How do I make it so they go away permanently?
Typically a game is redrawn on each render call (the render loop). Your game runs by calling your root render() method repeatedly. At the beginning of your render method, you clear the screen, and then draw everything again. So to remove something, you simply stop drawing it.
You need to create a List of all active pellets. This can be a list of some Pellet class that you create that has coordinates and any other state data that is relevant to your game (such as whether it's a "super-pellet"). Or it could just be a list of Vector2s if all your pellets are identical so the only thing you need to track is their position.
When a round starts, you should create all the pellets you need at the coordinates they should be at and add them all to the List.
Then, instead of doing your for(int x = 1; x < 27; x++) loop to draw them, you should loop through your list instead and draw each pellet based on its position (and possibly other data, for example if there are super pellets, you could choose how big to draw it based on that data).
When the character moves, you can check its overlap with each pellet in the list. When a pellet is overlapped, you can remove it from the list and update your score. When it is removed from the list, it will no longer be drawn in the other part of your code where you loop through the list to draw them.

how to make walls in actionscript 3.0?

i've been making a twist on the labyrinth game and i've got my ball to move with physics but im struggling with getting it to hit the walls around it. its currently a movie clip with black walls, and ive used this code to try and stop it:
if (character.hitTestObject(walls)){
character.x = //something
character.y = //something
}
all this does is when it hits any part of the movie clip, (even the blank spaces) it moves my character,
is there any sort of code i can use to maybe detect hitting a certain colour?
One way you could do this, is to use hitTestPoint() method to test if any of the corners have hit your wall.
hitTestPoint() tests only a single location to see if that point collides with an object. This is how you could test the top left corner of your character to see if it's touching the wall :
// I am assuming that x,y is the top left corner of your character
if (wall.hitPointTest(character.x, character.y, true))
{
// top left collided with wall
{
So you could do the same for all corners, or if you want, you can determine any collision points you want to check for the character.
Depending on your level of precision, this method might work just fine for your needs. But if you want pixel perfect collision, you can check out this link :
http://www.freeactionscript.com/2011/08/as3-pixel-perfect-collision-detection/

Flash drawing line overlapping check

I have an application where user have to draw a line on the canvas without overlapping it. Is there a way to test the overlapping? I have googled already but found result with circles and rectangle overlapping. My case is different. Here user will draw lines on canvas without overlap the line itself. May be I am missing something so any guidance is appreciated. Thanks
I take it you mean the user draws a line with some sort of pen tool, using the mouse.
Here's what I would do:
First, hold the path of the line drawn in a BitmapData object.
var lineBitmapData:BitmapData = new BitmapData(display.width,display.height,true,0x00000000);
This creates a transparent bitmap object with the user's line on it.
On each frame (or timer event, if you use timer) do the following:
1.capture the current mouse position and put it into a Point object.
var currentMousePosition:Point = new Point(mouse.x,mouse.y);
you will also need a point representing the upper-left corner of your bitmapData.
var pt1:Point = new Point(1,1);
2.perform collision detection between the current mouse position and the lineBitmapData
var result:Boolean = lineBitmapData.hitTest(pt1, 0xFF, currentMousePosition);
the second parameter in the hitTest method is the threshhold value. Basically, this needs to be set to the minimum alpha value that you want to count as a hit.
3.check the result of the hitTest. If it's false, this means what the user is about to draw this frame does not intersect what was already drawn. In this case, you add the bit that was drawn during the last frame to the lineBitmapData.
If the hitTest returns true, however, that means the user is about to make his line intersect, so your program needs to stop the drawing (or whatever behavior you want).
if(result){
myPenTool.stopDrawing();}else{
var drawnLastFrame:BitmapData = myPenTool.drawSingleFrameLine();
lineBitmapData.draw(drawnLastFrame);}
4.Update what the user sees on the screen with the new lineBitmapData

as3: Making an animation

I am playing with animation in AS3 and flex4, and I've come into a problem. My application is a game board (like a chess board), where each field is a border container added to some position.
Also I am adding a child element (shape), to this container on mouse click. What I want to achieve is to be able to move shapes smoothly from one field to another. But it appears that the shape goes behind the neighbor field this way http://screencast.com/t/iZ3DCdobs.
I believe this happens because shape is a child of specific border container, and to make it visible over every other container, I would need to use layers somehow....
I would be happy if anybody could suggest a solution
Yes you're right on that. You should add the movable objects to a different layer.
As there are no typical layers in AS, you could try to drop the fields in one sprite and any other objects to a different an than place them on each other, so that when you will move a object it won't go behind other objects.
If you place both sprites in the same position you will still have accurate x,y positions between movable objects and fields.
You have two options:
First one is to have different layers for your DisplayObjects: as an example, the bottom layer would hold all the boards, and the upper layer would hold all the pieces.
Second option is to manipulate the index of the objects with swapChildren(), swapChildrenAt(), and setChildIndex(). So to bring a MovieClip to the topmost front, you would do MovieClip(parent).setChildIndex(this, 0);
If the situation is that always the shape object gets hidden behind the next ( right side ) grid container, the I suggest you create your grid in reverse.
Suppose you are creating a chess grid. that is a 8x8 grid. Normally you would create your grid using 2 for loops, looping from 0 to 8 with say the x and y points starting at 0,0 for the first grid and going on till the end. What I suggest you to do is to create from 8,8 to 0,0.
Display objects in flash are stacked on top of each other based on their child index.
For example: If you create two objects. Rectangle and Circle as follows
var rect:Rectangle = new Rectangle();
this.addChild(rect);
var circ:Circle = new Circle();
this.addChild(circ);
The circle will always be on top of the rectangle in this scenario because the circle was added after the rectangle to the display list.
So if you reverse the order of creation of your grid, the right grid cell will be added to the display list first and so the grid cells to the left will always be on top of the right ones. Hence, the problem that you are facing will not occur.

Finding a free area in the stage

I'm drawing rectangles at random positions on the stage, and I don't want them to overlap.
So for each rectangle, I need to find a blank area to place it.
I've thought about trying a random position, verify if it is free with
private function containsRect(r:Rectangle):Boolean {
var free:Boolean = true;
for (var i:int = 0; i < numChildren; i++)
free &&= getChildAt(i).getBounds(this).containsRect(r);
return free;
}
and in case it returns false, to try with another random position.
The problem is that if there is no free space, I'll be stuck trying random positions forever.
There is an elegant solution to this?
Let S be the area of the stage. Let A be the area of the smallest rectangle we want to draw. Let N = S/A
One possible deterministic approach:
When you draw a rectangle on an empty stage, this divides the stage into at most 4 regions that can fit your next rectangle. When you draw your next rectangle, one or two regions are split into at most 4 sub-regions (each) that can fit a rectangle, etc. You will never create more than N regions, where S is the area of your stage, and A is the area of your smallest rectangle. Keep a list of regions (unsorted is fine), each represented by its four corner points, and each labeled with its area, and use weighted-by-area reservoir sampling with a reservoir size of 1 to select a region with probability proportional to its area in at most one pass through the list. Then place a rectangle at a random location in that region. (Select a random point from bottom left portion of the region that allows you to draw a rectangle with that point as its bottom left corner without hitting the top or right wall.)
If you are not starting from a blank stage then just build your list of available regions in O(N) (by re-drawing all the existing rectangles on a blank stage in any order, for example) before searching for your first point to draw a new rectangle.
Note: You can change your reservoir size to k to select the next k rectangles all in one step.
Note 2: You could alternatively store available regions in a tree with each edge weight equaling the sum of areas of the regions in the sub-tree over the area of the stage. Then to select a region in O(logN) we recursively select the root with probability area of root region / S, or each subtree with probability edge weight / S. Updating weights when re-balancing the tree will be annoying, though.
Runtime: O(N)
Space: O(N)
One possible randomized approach:
Select a point at random on the stage. If you can draw one or more rectangles that contain the point (not just one that has the point as its bottom left corner), then return a randomly positioned rectangle that contains the point. It is possible to position the rectangle without bias with some subtleties, but I will leave this to you.
At worst there is one space exactly big enough for our rectangle and the rest of the stage is filled. So this approach succeeds with probability > 1/N, or fails with probability < 1-1/N. Repeat N times. We now fail with probability < (1-1/N)^N < 1/e. By fail we mean that there is a space for our rectangle, but we did not find it. By succeed we mean we found a space if one existed. To achieve a reasonable probability of success we repeat either Nlog(N) times for 1/N probability of failure, or N² times for 1/e^N probability of failure.
Summary: Try random points until we find a space, stopping after NlogN (or N²) tries, in which case we can be confident that no space exists.
Runtime: O(NlogN) for high probability of success, O(N²) for very high probability of success
Space: O(1)
You can simplify things with a transformation. If you're looking for a valid place to put your LxH rectangle, you can instead grow all of the previous rectangles L units to the right, and H units down, and then search for a single point that doesn't intersect any of those. This point will be the lower-right corner of a valid place to put your new rectangle.
Next apply a scan-line sweep algorithm to find areas not covered by any rectangle. If you want a uniform distribution, you should choose a random y-coordinate (assuming you sweep down) weighted by free area distribution. Then choose a random x-coordinate uniformly from the open segments in the scan line you've selected.
I'm not sure how elegant this would be, but you could set up a maximum number of attempts. Maybe 100?
Sure you might still have some space available, but you could trigger the "finish" event anyway. It would be like when tween libraries snap an object to the destination point just because it's "close enough".
HTH
One possible check you could make to determine if there was enough space, would be to check how much area the current set of rectangels are taking up. If the amount of area left over is less than the area of the new rectangle then you can immediately give up and bail out. I don't know what information you have available to you, or whether the rectangles are being laid down in a regular pattern but if so you may be able to vary the check to see if there is obviously not enough space available.
This may not be the most appropriate method for you, but it was the first thing that popped into my head!
Assuming you define the dimensions of the rectangle before trying to draw it, I think something like this might work:
Establish a grid of possible centre points across the stage for the candidate rectangle. So for a 6x4 rectangle your first point would be at (3, 2), then (3 + 6 * x, 2 + 4 * y). If you can draw a rectangle between the four adjacent points then a possible space exists.
for (x = 0, x < stage.size / rect.width - 1, x++)
for (y = 0, y < stage.size / rect.height - 1, y++)
if can_draw_rectangle_at([x,y], [x+rect.width, y+rect.height])
return true;
This doesn't tell you where you can draw it (although it should be possible to build a list of the possible drawing areas), just that you can.
I think that the only efficient way to do this with what you have is to maintain a 2D boolean array of open locations. Have the array of sufficient size such that the drawing positions still appear random.
When you draw a new rectangle, zero out the corresponding rectangular piece of the array. Then checking for a free area is constant^H^H^H^H^H^H^H time. Oops, that means a lookup is O(nm) time, where n is the length, m is the width. There must be a range based solution, argh.
Edit2: Apparently the answer is here but in my opinion this might be a bit much to implement on Actionscript, especially if you are not keen on the geometry.
Here's the algorithm I'd use
Put down N number of random points, where N is the number of rectangles you want
iteratively increase the dimensions of rectangles created at each point N until they touch another rectangle.
You can constrain the way that the initial points are put down if you want to have a minimum allowable rectangle size.
If you want all the space covered with rectangles, you can then incrementally add random points to the remaining "free" space until there is no area left uncovered.