Making a blocking obstacle - actionscript-3

I'm new at ActionScript 3.0 so if you guys can help me a little.
I want to make an obstacle which block a path to player. I made this like that that I'm saving all movments to array and than if they collide it moves player to previous position. Is there another way because I think this is not the proper way to do it. And sometimes when it collides player is unable to move. Can you give me an example :)
Thanks

This is the only way you can ever detect a collision, but in a bit more refined way.
You actually collide the bodies (but do not apply the change to the actual object, yet).
Check for all colliding bodies on stage.
Take necessary step (roll back, destroy.. anything)
Apply the change & Render the bodies, on screen.
Considering the above as an example for flash :
var hero:Sprite = new Sprite();
addChild(hero);
while(1) {
var newX = hero.x + 1;
if(newX < 100)
hero.x = newX;
}
Every game should have a loop. The loop must branch out to various situations. So that's your start.
The hero object probably moves with the user interaction & the checks keep increasing, compelling you to re think the solution as your project grows more & more dense...

Related

Flash AS3 Scripted eyes do not tween with other layer animation

thanks for reading.
I have a small animation in Flash that is scripted to enable the eyes to follow the mouse. This further animates upwards on mouse click, but the eyes that are scripted do not follow the tween.
I have childed/ embedded the eyes objects inside the main animating layer but this also seems to NOT follow.
I'm a bit confused and expect I have missed some fundamental structural/ layering issue -but I'm at a bit of a loss and am concerned if it is not me, then is it a bug or something in Flash and scripted layers working together or something:(
Anyway, I enclose the actual .fla and the .swf in vain of any help that you wonderful dudes can pass down to me.
https://drive.google.com/open?id=0B4yGmvZlwZmWanJJX1IzTk5pYXM
I would really love to know why and what if there is something I have fundamentally missed here. (I haven't checked for AS3 in the Symbol conversion Advanced options dialogue for the eye instance, but this has not effected the interactive eye part and I suspect it shouldn't be the cause of the conflict as a result - happy to be wrong here though of course :))
Edit: Here is the code for the project {which started out as a youtube tut showing how to control a circular movement of some eye objects with the mouseMove event }
//this is an action script window
//we can code into here :)
this.stop();
this.loop = false;
stage.addEventListener(MouseEvent.MOUSE_MOVE, MoveEyes);
stage.addEventListener(MouseEvent.MOUSE_DOWN, PlayTimeline);
function MoveEyes(e:MouseEvent): void
{
var mouseYPosition = mouseY - EyeR.y;
var mouseXPosition = mouseX - EyeR.x;
var radiusR = Math.atan2(mouseYPosition, mouseXPosition);
var degreesR = radiusR / (Math.PI / 180);
EyeR.rotation = degreesR;
mouseYPosition = mouseY - EyeL.y;
mouseXPosition = mouseX - EyeL.x;
var radiusL = Math.atan2(mouseYPosition, mouseXPosition);
var degreesL = radiusL / (Math.PI / 180);
EyeL.rotation = degreesL;
}
//when clicked start the animation
function PlayTimeline(e: MouseEvent) : void
{
this.play();
}
...In fairness, and I am totally happy to be wrong of course but, I don't think the code is causing or has anything to do with the fault, it may be more my stage layer positions or something along those lines, hence the full .fla file for someone better than me to point out my mistake.
Cheers all and thanks again for reading and taking the time here.
:)
Gruffy
That's actually a very interesting bug. I believe what's happening is that by interacting with the Eyes' properties, you're removing it from the timeline tween.
Your best bet would be to simply remake the timeline tween in code like so:
function PlayTimeline(e: MouseEvent) : void
{
this.play();
new Tween(EyeL, "y", fl.transitions.easing.None.easeInOut, EyeL.y, 141.95, 100);
new Tween(EyeR, "y", fl.transitions.easing.None.easeInOut, EyeR.y, 141.95, 100);
}
This gives the affect you need. However if you start messing with the timeline animation you will need to change the tween, so perhaps it would be best to move all the tweening code side?
EDIT: I notice that the eyes don't animate whilst the bird is moving unless you continue to move the mouse. The solution for this would be to change the mouseEvent listener to an enterframe listener so that it will happen every frame regardless of whether the mouse is moving or not. That's not the best solution, as it's a bit overkill, but to do anything else would likely involve some timers or third part libraries, which I don't think are strictly necessary at this point

AS3 collision detection in an object itself

I´m programing a space ship side scroll in as3. The bottom of the stage are mountains and here comes the problem, when I try to detect the ship collision against the mountains..
Because the poor collision detection and the need of avoid large loops my idea is create an object that works as a collider itself detecting a collision and avoiding parse all the stage or more selective metod.
I place "by hand" in the flash stage several instances of circles with a class for manage them where I place the If(this.collider.hits(ship)....
I spent looong time but I can find the way to make it work some of the mistakes i get are like this
Error 1061: Call to a possibly undefined method hitTestObject through a reference with static type Class.
some Idea? Thanks in advance
when you hit test with points it is important that the point being tested is relative to the object being tested against, eg
if(mountain.hitTestPoint(this.x + circle1.x, this.y + circle1.y))
will return true if the circles are inside the object calling the function because their position relative to the mountain is now relative to it rather then relative to the ships xy position within the clip... hope that makes sense.
btw I have done this myself in the past but I would have to remind you that you can only hit test with the points so there is no need to have circles, use blank sprites instead and set the visible flag in the properties panel to false, no drawing will make it slightly faster... not that you will notice, also sprites/graphics use less memory then movie clips.
also I would recommend hard coding some points in the clips rather then actually adding the clips in the sprite/clip itself, this will make it easier to work with them and scale later on (believe me this will annoy the hair from your head to do something later and slow the game to scale on the fly)
try something like this... you can determine the points values by adding a clip to the movie clip and getting its position from the properties if you must.
private var hitPoints:Vector.<Point> = new Vector.<Point>
hitPoints.push(new Point(10, 40));
hitPoints.push(new Point(30, 40));
//...do this for all your points
//loop through all your points and check if the hit relative to the ships position.
for(var i:int = 0; i < hitPoints.length; i++)
{
if (scene.hitTestPoint(ship.x + hitPoints[i].x, ship.y + hitPoints[i].y))
{
//do your hit stuff here
break;//don't forget to break
}
}
in this code you will need to make sure the scene object is a reference to your scenery at the bottom of the screen.
I hope this helps but if this is not enough help then you should post some of your code here so we can have a look and see where it can be improved.

Moving text across screen smoothly

For a long time I've been searching for a solution to this problem, so I decided to post a tread instead when the search didn't clarify anything.
I have a textfield that is supposed to move across the screen. I've solved this by adding a speed to its x-value dynamically through an "enter-frame function". However, the movement is very "laggy" and consists of sudden "jumps" in the movement. I've tried a couple of possible solutions to this, all of them without luck.
embedding fonts
changing the textfield's antiAliasType
using BitmapData like this:
bmd = new BitmapData (myTextField.width, myTextField.height, true, 0);
bmd.draw (myTextField);
bm = new Bitmap (bmd);
bm.x = myTextField.x;
bm.y = myTextField.y;
bm.cacheAsBitmap = true;
bm.smoothing = true;
this.addChild(bm);`
And then moving the "bm" instance
None of these methods worked.
EDIT: By request, I am adding the relevant code for the actual movement of the text.
stage.addEventListener(Event.ENTER_FRAME, time);
private function time(evt:Event):void
{
bm.x-= textSpeed;
}
The variable textSpeed is defined as a public static var. Its value is 2.
*EDIT2: I've prepared a clean fla-file with nothing but moving text. The same lag occurs for me also here. The code is in the actions panel. Download link
the way Flash IDE works, is that setting the framerate is actually the 'maximum' framerate. That is, it doesn't force the animation to run at that rate - it can vary depending on the machine and available resources.
As far as I know, there's no way to force Flash to run at a certain framerate - the best way to make animations 'smooth' is to use Tween classes like TweenLite.
If you NEED to animate by incrementing position values, then I suggest making it time based instead, for example:
var fps = 24;
var moveTimer:Timer = new Timer(1000/fps);
moveTimer.addEventListener(TimerEvent.TIMER, onMoveTimer);
moveTimer.start();
function onMoveTimer(e:TimerEvent){
bm.x -= 1;
}
Again, this doesn't solve the smoothness of the animation, but it will be much more reliable across different machines than using enter frame.
Try increasing the framerate. Because you naturally try to read text as it animates, you can generally notice the gaps between frames at 24fps. Try setting stage.frameRate to 30, 48, or 60 (60 being the max) and see if that solves your issues. I've had similar issues with animating text in the past and increasing frame rate has fixed them.
I would also recommend only increasing it as needed. You are much more likely to drop frames with a higher frame rate (makes logical sense; each frame has less time to calculate as frame rate increases), so you might want to do something like:
stage.frameRate = 48;
// run animations here
stage.frameRate = 24; // in an Event.COMPLETE handler
That will make sure your animations are smooth while giving the rest of your application the best shot of running well on lesser devices. If you are running a lot of animations, you might consider keeping it elevated permanently.
You should also look into using the Greensock animation library (TweenLite/TweenMax) instead of Flash's built-in tweening. Greensock has a vastly superior API, both in terms of features and performances, especially on mobile.

Flash AS3: Keeping the mouse within certain boundaries

So this one is a tricky one (for me) vital to the development of my project due to the fact that we can't directly modify the position of mouseX and mouseY - they are read-only variables.
Basically, what I want to do is have a player able to move their mouse only within a certain triangular area when a specific instance is active. The latter bit I can manage just fine, however I am having trouble restricting mouse movement -- or apparent mouse movement.
Here's what I have done so far:
1. Assign a library moveclip to the mouseX and mouseY position in the Event.ENTER_FRAME event - although I acknowledge that this should be moved to Mouse.MOUSE_MOVE. (this does not matter yet)
2. Using Corey O'Neils Collision detection kit, do a hit test on the border instances of the area with the crosshair/cursor.
3. Offset the cursor appropriately, and then set a standard Boolean value to false so that the cursor will not keep bouncing back into the cursor over and over.
My problem is, I am not sure what the best way is to go about allowing mouse movement again. Can anyone give me some tips on the best way to do this, or if necessary, point me in another direction where restricting mouse movement is a little easier?
For what it's worth, this is to stop users from aiming in an unrealistic direction with a character in a top-down (ish) shooter.
For those unfamiliar with Corey O'Neil's Collision Detection Kit, I believe it is just a pre-built setup of bitmap (or maybe vector) collision testing - I could be wrong. I'm not sure on the details of how it works, just its basic implementation.
Here is my code regarding mouse movement thus far:
import flash.ui.Mouse;
import flash.events.event
import com.coreyoneil.collision.CollisionList;
Mouse.hide();
var c:crosshair = new crosshair();
addchild(c);
var myCollisionList:CollisionList;
myCollisionList = new CollisionList(c); //sets up detection for the object c
myCollisionList.addItem(mcB); // adds mcB to the list of objects to check c's hittest with
function aim(e:Event) {
var collisions:Array = myCollisionList.checkCollisions();
if (collisions.length>0)
{
hashit = true; // tells the program that the mouse has collided with a boundary
c.x += 1;
c.y += 1;
}
else
{
if (hashit == false)
{
c.x = mouseX;
c.y = mouseY;
}
}
}
Apologies for the code block, but I figure it is best to show all relevant code -- I'm not sure about the complexity of this issue due to the read-only nature of the mouse's X and Y position.
Also, I'm looking for a possible solution which will not be clunky - that is, as soon as the mouse is back in the area, mouse movement will be smooth as it is originally, and where the cursor will still be matching the mouse position (meaning, the cursor is ALWAYS relevant to the mouse and will not change position should the mouse leave the boundaries).
Could anyone please give me some pointers? Sorry for the long question. I gather there might be a bit to get my head around here, being relatively new to AS3 - but I still feel this is a problem I can get past, if one of you can show me the right direction and help me with both the logic and programming side of things slightly.
Here is a diagram of my stage to clarify the boundary areas etc.
Thanks very much for any help in advance, I really do appreciate it!
Cheers, Harry.
How about trying getObjectsUnderPoint which returns an array of objects under a certain point.
If your triangle object is within the array the cursor must be above it.
var pt:Point = new Point(c.x, c.y);
var objects:Array = stage.getObjectsUnderPoint(pt);
if (objects.indexOf(triangleObject) > -1) {
trace("still within bounds");
}
The workaround here could be to hide the system mouse cursor and add a bespoke cursor movieclip to the stage.
Using a MOUSE_MOVE event listener attached to the stage, set the bespoke cursor movieclip to match the stage.mouseX and stage.mouseY values and also test whether the movieclip is outside your bounds. If so, set it back within your bounds.

Split screen in Actionscript 3

I'm trying to make a pure AS3 game, and need a way to split the screen so that two players can have individual "cameras" that follow the around the game world. The problem is that a sprite can't have multiple parents. I'm trying to hack my way around this problem by having classes that duplicate sprites and manage all of their updates, but I'm not getting very far and my code is getting very, very ugly.
Does anyone know a good workaround or method for doing this? I can't seem to find much on-line on the subject.
I think you should use BitmapData copyPixels method
.copyPixels(point_0, rectangle_0)---> FirstPlayerScreen
World.Bitmap -
.copyPixels(point_0, rectangle_0)---> SecondPlayerScreen
Thanks for everyone's suggestions. What I've ended up with is a World class that I can add regular Sprite objects to as children. The World object manages and updates copies of those sprites, and world.getCamera() can be called as many times as necessary to display custom copies of the game world.
The key part is making copies of the sprites, this is the function I wrote to do that:
public function bitmapCopy(original:DisplayObject):Sprite
{
var returnSprite:Sprite = new Sprite();
if (original.width == 0 || original.height == 0) return returnSprite
var x = original.x; var y = original.y
var rotation = original.rotation
original.x = 0; original.y = 0; original.rotation = 0
var bounds:Rectangle = original.getBounds(original.parent)
var m:Matrix = new Matrix()
m.tx = -bounds.x
m.ty = -bounds.y
var bitmapData:BitmapData = new BitmapData( bounds.width, bounds.height, true,
0xFF0000 );
bitmapData.draw(original, m);
var bitmap:Bitmap = new Bitmap( bitmapData );
bitmap.x = bounds.x
bitmap.y = bounds.y
returnSprite.addChild(bitmap);
returnSprite.x = original.x = position.x
returnSprite.y = original.y = position.y
returnSprite.rotation = original.rotation = rotation
return returnSprite;
}
The returned Sprite can be added to the stage and will act in exactly the same way as the original (except for being static, of course). Hopefully this should help anyone else who comes across this problem.
Your theory is on the right track - you're probably just stumbling over your implementation. Organization and keeping things object-oriented will be your best friend in this scenario.
It's hard to give you a good example based off of a limited description of your game, but in general, I'd have a Screen class that can be instantiated multiple times, and I'd keep track of each instantiation (that gives us our multiple "players"). Each Screen has a stage, and you're building your game world on that stage.
The key here is data organization and good communication. Remember, there's only one "world", and you're just showing multiple instances of it. So you'll want a central Model to store data about every object in your singular game world. That Model will drive the rendering of that world to your multiple screens. If a player changes an object on their screen (let's say they move it), then you'll update the Model with that object's new location. Then, you'll broadcast those new coordinates to each Screen instance, so that all of your screens will update.
How you "broadcast" this can vary (and depends largely on the real-time nature of your game). If your game is very real-time and you're running a game loop, then you may just want to pass the objects' data along in every loop, and they'd update that way. If your game isn't as dependent of being real-time, then you can set up event listeners or a custom notification system that'll alert all of the instances of an object to update itself.
I know this is very high-level, but it's hard to give an in-depth answer without more info about your game. Hopefully this helps point you in the right direction - what you're attempting is definitely not simple, so don't get discouraged!
If you develop your game using MVC architecture principles then it should be trivial to draw your game twice, each player having an instance of the game's "view" but positioned according to a different character. If you give a layer mask to each instance then you could put the two instances side by side and so create a split screen effect.
Happy coding!
I'm working on a split screen myself just now:
masking to draw 1 world in 2 branches of your DisplayObject tree (separated cleanly), copying pixels for a split screen is a bad idea
data object to describe the world (not Sprite or DisplayObject)
Works very well so far. I've got 1 level, 2 players who move independently from each other and 2 screens that follow one player at a time. I see the other player in one player's screen and the one player in the other player's screen.
Here is how I did the data object part:
Define a central data object which describes the world and all it's world objects.
Write: make some sprites being able to manipulate 1 object of the world.
Read: update sprites by checking the properties of the world objects. 2 Screens -> 2 sprites for every world object. Check them every frame or try events.