AS3 - How can multiple objects that appear randomly NEVER touch each other? - actionscript-3

I have multiple objects that appear randomly on stage, but i want them to never touch each other when they appear.
object1.x = Math.random() * stage.stageWidth;
object1.y = Math.random() * stage.stageHeight;
object2.x = Math.random() * stage.stageWidth;
object2.y = Math.random() * stage.stageHeight;
object3.x = Math.random() * stage.stageWidth;
object3.y = Math.random() * stage.stageHeight;
etc...
And also how can i make them appear inside a box, instead of the stage.

I have multiple objects that appear randomly on stage, but i want them
to never touch each other when they appear
They obviously can't appear at random then.
A naive but quick to code solution is to use bounding box collision before actually placing the element using:
// http://stackoverflow.com/questions/2752349/fast-rectangle-to-rectangle-intersection
function rectIntersection(r1,r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
If there is indeed a collision you can re-run the random placement of that particular element until there is not any collision.
This method is naive because you need to run the collision detection for all elements on your screen each time you are attempting to do a random placement. If it fails (meaning there is a collision), then you need to run it again until there is not.
Keep in mind that you can also pre-calculate the placements instead of checking on animation runtime (if it's an animation).
For the second part of you question.
And also how can i make them appear inside a box, instead of the
stage.
Instead of using the stageWidth as a placement variable, you can use a function that returns a random integer within a range.
The ranges provided would be:
top-left/top-right for width
bottom-left/bottom-right for height
..of the box you want to constraint your elements in.
The function would return a random integer within those ranges and your boxes would always fall within that box.
Here's a code snippet to get you started:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

Related

How to make an object randomly spawn inside of the stage only

My stage size is 640 x 1136
I want to spawn my objects randomly but only inside of the stage.
I used this
object.x = Math.random() * stage.stageHeight;
How can I make the x position spawn within the stage area?
You would want a "random in range" function like the one here
(included below).
However, if you are doing a game you may not be satisfied with the result of randomly spawning objects (e.g. objects piling up on each other, etc.) and want to exert more control. Lots of ways to be clever with that – like defining a set of regions or quadrants, picking one of those randomly and then generating random coordinates within that region, or having an array of defined "good" points and randomly selected from it. Actual randomness is often less interesting than the idea or appearance of randomness.
public function randRange(minNum:Number, maxNum:Number):Number {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
TOMATO answer is the same as what you actually do so it's not really helpful. What you need to do is account for the object size. If you have an object that is at maximum 100 pixel wide then:
var size:Number = object.width;
object.x = size + Math.random() * (stage.stageWidth - size * 2);
This make sure the object spawn on the x axis inside the stage x axis. Same operation needs to be repeated for the y axis of course.

as3 Math.random() cant seem to get it working correctly

im working on as3 adobe flash, the FLA is a catching game and seems to work fine but i want to tweak it. i currently got :
trying to implement random speed per ball, i tried this:
var speed:Number = 7;
var RandomSpeed:Number = Math.random() * 7;
var ymov:Number = RandomSpeed + speed;
and in the function i put this:
bgame[j].y += ymov;
(its [ j ] because i had to make another array to get the ball to drop)
its currently randomising all the balls in the game to the same speed but i want it to do it to individual balls.
there's also one more problem, when the game is finish (once player gets a score of 2 the game takes you back to home screen) the ball sprites that were on the screen and not caught still remain on the screen,
You need to assign different ymov speeds to each ball. As it is now you assign the value at the top level scope, then use it to update each ball's position. This is why they are all the same speed.
You can assign a new random ymov property to each ball in your addBall() function:
bgame[i].ymov = 7 + Math.random() * 7;
Then in your Ballgame() update function move the ball based on that property:
bgame[j].y += bgame[j].ymov;
BTW as a style note, classes usually are UpperCase while variables and functions are lowerCase.
Your issue is that you are only "rolling the dice" once and using that result for the speed of every ball. Make ymov into a function it will produce a different result every time. IE:
function ymov():Number
{
var speed:Number = 7;
var RandomSpeed:Number = Math.random() * 7;
return RandomSpeed + speed;
}

ActionScript 3 stage width

Im doing my first flash AS game, so need a little help.
I have only 1 thing on the stage, its ball (layer instance) which has anchor point in the middle. I'm trying to make this ball bounce off walls (i mean screen).
This instance name is called 'kugla1'
Heres my code (its second frame):
if(kugla1.x<=kugla1.width/2 || kugla1.x>=stage.stageWidth-kugla1.width/2)
speedX=-speedX;
if(kugla1.y<=kugla1.height/2 || kugla1.height>=stage.stageHeight-kugla1.height/2)
speedY=-speedY;
kugla1.x+=speedX;
kugla1.y+=speedY;
First frame is:
var speedX:int=5;
var speedY:int=5;
kugla1.x=100;
kugla1.y=100;
And third frame is only:
gotoAndPlay(2);
what am I doing wrong?
Thanks!
Your problem, is likely this line:
if(kugla1.y<=kugla1.height/2 || kugla1.height>=stage.stageHeight-kugla1.height/2)
In the second part (after the ||) you are comparing the height of kugla1 instead of the y position.
Another issue you could run into, is your ball could potentially meet the same condition for longer than one frame, so it would be best to separate your speed from the current direction of movement.
See code comments:
On your first frame, you'll need two additional variables:
var speedX:int=5;
var speedY:int=5;
var curSpeedX:Number = speedX;
var curSpeedY:Number = speedY;
on your second frame:
if(kugla1.x <= kugla1.width/2){
curSpeedX = speedX; //we need the positive value to make it go right
}
if(kugla1.x >= stage.stageWidth - kugla1.width/2){
curSpeedX = -speedX; //we need the negative value to make it go left
}
if(kugla1.y <= kugla1.height/2){
curSpeedY = speedY; //we need the positive value to make it go down
}
if(kugla1.y >= stage.stageHeight - kugla1.height/2){
curSpeedY = -speedY; //we need the negative value to make it go up
}
kugla1.x+= curSpeedX;
kugla1.y+= curSpeedY;

AS3 create a trail of movieclips following each other

So, I'm trying to get a few movieclips to follow it's precursor and have the last one follow the mouse. The problem is I'm creating them from code instead of using the interface and, since I'm not an expert, I can't get them to work.
All I have in the library is a MovieClip(linkage:"LETRA") which contains a textField inside(instance name:"myTextField").
Here's what I have:
import flashx.textLayout.operations.MoveChildrenOperation;
import flash.display.MovieClip;
import flash.events.Event;
//this are the letters that will be following the mouse
var phrase:Array = ["H","a","c","e","r"," ","u","n"," ","p","u","e","n","t","e"];
//variable to spread them instead of creating them one of top of each other
var posXLetter:Number = 0;
//looping through my array
for (var i:Number = 0; i < phrase.length; i++)
{
//create an instance of the LETRA movieclip which contains a text field inside
var newLetter:MovieClip = new LETRA();
//assing a letter to that text field matching the position of the phrase array
newLetter.myTextField.text = phrase[i];
//assign X position to the letter I'm going to add
newLetter.x = posXLetter;
//add properties for storing the letter position
var distx:Number = 0;
var disty:Number = 0;
//add the listener and the function which will move each letter
newLetter.addEventListener(Event.ENTER_FRAME, moveLetter);
function moveLetter(e:Event){
distx = newLetter.x - mouseX;
disty = newLetter.y - mouseY;
newLetter.x -= distx / 10;
newLetter.y -= disty / 10;
}
//add each letter to the stage
stage.addChild(newLetter);
//increment the next letter's x position
posXLetter += 9;
}
With that code, only one letter is following the mouse (the "E") and the rest are staying where I added them using addChild and the posXLetter variable.
Also, I'm trying to get it to behave more like a trail, so if I move up, the letters will lag beneath me; if I move to the left, the letters will lag to my right but I think that with my current approach they will either A) move all together to the same spot or B) always hang to the left of the cursor.
Thanks for any possible help.
This is a kind of motion called Inverse Kinematics and it is a quite popular way to make rag dolls in games. It uses a design pattern called the Composite Pattern where one object adds another object as a child of its and then when it's update() function if called, it calls all of its (usually one) child's update() functions. The most common example of this is of a snake. The snake's head follows your mouse, and the rest of the snake's body pieces move with the snake, and it looks immensely realistic. This exact example is explained and build here although it does not include joint restrictions at all.
This example is in the middle of a book, and so may be hard to start reading, but if your somewhat familiar with design patterns and/or have some intermediate experience with programming, then i'm sure you can understand it. I advise that you, after reading and understanding the example, scratch what you have now because it is not very elegant coding. You may feel that this example uses too many classes, but trust me, its worth it as it allows you to very easily edit your code, if you decide to change it in the future, with no drawbacks.
Also, i know that this snake is not what you want, but if you understand the concept then you can apply it to your own specific needs.
I hope this helps.
I think it is a scoping issue. You might need to modify your handler
function moveLetter(e:Event){
trace(e.target); //check if this is the right movie clip
distx = e.target.x - mouseX;
disty = e.target.y - mouseY;
e.target.x -= distx / 10;
e.target.y -= disty / 10;
}

Zoom to and from point

I'm trying to zoom a DisplayObject into a certain point. I figured it would be easy, but I've spent a day now trying to figure it out.
Basically, I think this should work. Emphasis on should.
//newPoint is the point being centered. There is no initial scaling, so I do not need to compensate for that (yet)
//scale is the zoom level
//container is the parent of the obj
//obj is the object being scaled/panned
var p:Point = new Point(
( this.container.width - this.obj.width * scale + newPoint.x * scale ) / 2,
( this.container.height - this.obj.height * scale + newPoint.y * scale ) / 2
);
this.obj.scaleX = this.obj.scaleY = scale;
this.obj.x = p.x;
this.obj.y = p.y;
It centers the point if scale is 1, but it gets further and further away from center as you increase the scale. I've tried dozens of different methods. This method, which I have seen on several sites, produced the same exact results. Anyone have any idea how to get this to work?
EDIT 10-1-12:
As a followup, I took the code snippet that LondonDrugs_MediaServices provided as a basis for my original issue. I needed to be able to zoom to a specific point at a specific scale relative to the unscaled image (think how Google Maps zooms to a specific location). To do this, I had to center my image on the point before running the translation code. I've posted the additional code below. For other uses (pinch to zoom, scrolling, and double click), I used the code provided by Vesper, which worked quite well.
//obj is the object being translated
//container is its parent
//x and y are the coordinates to be zoomed to, in untranslated scaling
//obj.scaleX and obj.scaleY are always identical in my class, so there is no need to account for that
//calculates current center point, with scaling
var center:Point = new Point( ( this.container.width - this.obj.width * this.obj.scaleX ) / 2, ( this.container.height - this.obj.height * this.obj.scaleX ) / 2 );
//calulcates the distance from center the point is, with scaling
var distanceFromCenter:Point = new Point( this.obj.width * this.obj.scaleX / 2 - x * this.obj.scaleX, this.obj.height * this.obj.scaleX / 2 - y * this.obj.scaleX );
//center the object on that specific point
this.obj.x = center.x + distanceFromCenter.x;
this.obj.y = center.y + distanceFromCenter.y;
var mat:Matrix=new Matrix();
mat.translate(-p.x,-p.y);
mat.scale(desiredScale,desiredScale);
mat.translate(p.x,p.y);
yourObject.transform.matrix=mat;
The core point is that scaling is done around (0,0), but you can do it with matrix that describes affine transformations. You first make an empty matrix (that is, a matrix that doesn't transform), then apply a set of transformations to it. First, place a desired point at (0,0) by translating by -1*coordinates, then scale, then translate back.
hie guys....
thank's your comments...
i found the answer...
code :
gambar.addEventListener(TransformGestureEvent.GESTURE_ZOOM , onZoom);
function onZoom(event:TransformGestureEvent):void {
var locX:Number=event.localX;
var locY:Number=event.localY;
var stX:Number=event.stageX;
var stY:Number=event.stageY;
var prevScaleX:Number=gambar.scaleX;
var prevScaleY:Number=gambar.scaleY;
var mat:Matrix;
var externalPoint=new Point(stX,stY);
var internalPoint=new Point(locX,locY);
gambar.scaleX *= event.scaleX;
gambar.scaleY *= event.scaleY;
if(event.scaleX>1 && gambar.scaleX>6){
gambar.scaleX=prevScaleX;
gambar.scaleY=prevScaleY;
}
if(event.scaleY>1 && gambar.scaleY>6){
gambar.scaleX=prevScaleX;
gambar.scaleY=prevScaleY;
}
if(event.scaleX<1 && gambar.scaleX<0.8){
gambar.scaleX=prevScaleX;
gambar.scaleY=prevScaleY;
}
if(event.scaleY<1 && gambar.scaleY<0.8){
gambar.scaleX=prevScaleX;
gambar.scaleY=prevScaleY;
}
mat=gambar.transform.matrix.clone();
MatrixTransformer.matchInternalPointWithExternal(mat,internalPoint,externalPoint);
gambar.transform.matrix=mat;
}
The matrix answer is absolutely correct, but if you happen to be a Club GreenSock member you can get some nice functionality with very simple code with the TransformAroundPointPlugin
http://www.greensock.com/as/docs/tween/com/greensock/plugins/TransformAroundPointPlugin.html
You can see an example in the plugin explorer here:
http://www.greensock.com/tweenlite/#plugins
I use this to tween all my zooms and have much better performance than when I tried to do this manually. IMO the whole library is worth it's weight in gold (and no I have no connection other than liking the library). If you need any of the other features I'd look into it. It also has the ThrowProps plugin ( http://www.greensock.com/throwprops/ )which is very important if you are going to have a bounding box on mobile that you want to have a smooth return into the boundaries.
Set obj.x to -p.x and obj.y to -p.y, set the container scaleX and scaleY to the desired value and add p.x to the container x and p.y to the container y. Done!