AS3/AIR Mobile Click and/or touchevents on moving objects - actionscript-3

few weeks ago i asked a question about a similair issue, but within the Starling Framework (Starling TouchEvent on Sprite)
Now, i am working on another mobile app/game with Away3d. I seem to have the same problem touching/tapping a moving sphere or box. When the sphere is not moving, i can just tap it exactly at its position, but when it rotates, the click-event doesnt fire very accurate.
this only happens on Mobile (tested on Android 4.2.2: Nexus7/Galaxy S2 and iOS: iPad2/iPad Retina)
package {
import away3d.containers.ObjectContainer3D;
import away3d.containers.View3D;
import away3d.core.pick.PickingColliderType;
import away3d.core.pick.PickingType;
import away3d.debug.AwayStats;
import away3d.entities.Mesh;
import away3d.events.MouseEvent3D;
import away3d.primitives.SphereGeometry;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.geom.Vector3D;
[SWF(frameRate="60")]
public class Main extends Sprite {
private var _container:ObjectContainer3D;
private var _view:View3D;
private var _sphere:Mesh;
public function Main()
{
super();
addEventListener(Event.ADDED_TO_STAGE, onAdded_toStage);
}
private function onAdded_toStage(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, onAdded_toStage);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, onResize_stage);
init3d();
}
private function onResize_stage(e:Event):void {
_view.width = stage.stageWidth;
_view.height = stage.stageHeight;
}
private function onEnter_frame(e:Event):void {
_container.rotationY += 1;
_view.render();
}
private function onClick_sphere(e:MouseEvent3D):void {
//reposition the sphere
var deg:Number = Math.random() * 360;
_sphere.x = 250 * Math.cos(deg);
_sphere.z = 250 * Math.sin(deg);
_sphere.y = 80 + (Math.random() * 40);
}
private function init3d():void {
//create the 3d-view
_view = new View3D();
_view.width = stage.stageWidth;
_view.height = stage.stageWidth;
addChild(_view);
//create a cub
_view.camera.z = -400;
_view.camera.y = 75;
_view.camera.lookAt(new Vector3D(0, 125, 0));
//create container
_container = new ObjectContainer3D();
_view.scene.addChild(_container);
//create sphere to tap
_sphere = new Mesh(new SphereGeometry(10));
_sphere.pickingCollider = PickingColliderType.AS3_FIRST_ENCOUNTERED;
_sphere.y = 100;
_sphere.z = -250;
_sphere.mouseEnabled = true;
_sphere.addEventListener(MouseEvent3D.CLICK , onClick_sphere);
_container.addChild(_sphere);
var stats:AwayStats = new AwayStats(_view);
addChild(stats);
addEventListener(Event.ENTER_FRAME, onEnter_frame);
}
}
NOTE: i also tried different framerates, more events(Mouse_up, down etc), different pickers.
As this problem also happens with 2d moving sprites (in starling) my guess is that is might be Stage3D or AIR related, instead of starling/away3d.
Anyone has some suggestions? Maybe i'm forgetting to set something in the app.xml?

Both framework have to deal with an event less system (Stage3D). Stage3D doesn't catch or receive any events and certianly not touch or mouse event. So both frameworks simulate those events with an internal system that catches events on the stage and try to reproduce an accurate estimation. I personally find those systems too CPU expensive and not accurate enough so my advice is to do like me, create your own system. Simply catch event on the stage and decide which of displayed objects (on Stage3D using their position) has been touched. I personally get a performance boost out of it (especially with starling) and much more accuracy.

Related

Gettling starling to work with box2d and debugdraw with as3

This topic has been raised before, but not one of the examples I've found online seem to work for me! I am trying to get starling to work with box2d, and also for the box2d debugdraw.
I have tried a bunch of different methods, and my code is now a bit of a mess due to commenting out to try different mixes of the "solution". Does anyone know how to do all this properly? I would be greatly in dept if someone could explain it.
Here is the last attempt I tried:
In my Startup class:
package {
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
//import flash.events.Event;
import starling.core.Starling;
//import starling.display.Sprite;
import flash.events.Event;
[SWF(width="640", height="480", frameRate="60", backgroundColor="#000000")]
public class Startup extends Sprite {
public static var mStarling:Starling;
public static var debugSprite:Sprite;
public function Startup() {
//addChild ( new Stats() );
super();
//stage.align = StageAlign.TOP_LEFT;
//stage.scaleMode = StageScaleMode.NO_SCALE;
// create our Starling instance
mStarling = new Starling(Game, stage);
// set anti-aliasing (higher the better quality but slower performance)
mStarling.antiAliasing = 1;
mStarling.showStats = true;
// start it!
mStarling.start();
stage.stage3Ds[0].addEventListener(Event.CONTEXT3D_CREATE, onContextCreated);
}
private function onContextCreated(e:Event):void{
////debug mode
// debugSprite=new Sprite();
// //addChild(debugSprite);
// Starling.current.nativeOverlay.addChild(debugSprite);
//var debugSprite:Sprite=new Sprite();
addChild(debugSprite);
(mStarling.stage.getChildAt(0) as Game).DebugDraw(debugSprite)
}
I call the debugdraw like this:
debugDraw(Startup.debugSprite);
Here is a heavily commented out debugdraw:
private function debugDraw(debugSprite:flash.display.Sprite):void {
/*var worldDebugDraw:b2DebugDraw=new b2DebugDraw();
//var debugSprite:flash.display.Sprite = new flash.display.Sprite();
var debugSprite:Sprite = new Sprite();
addChild(debugSprite);
//mStarling.current.nativeOverlay.addChild(debugSprite);
//worldDebugDraw.SetSprite(debugSprite);
//debugDraw.SetSprite(Starling.current.nativeOverlay); //DOESN'T SEEM TO WORK
worldDebugDraw.SetDrawScale(worldScale);
worldDebugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
//worldDebugDraw.SetFillAlpha(0.0);
//worldDebugDraw.SetAlpha(0.0);
//visible
worldDebugDraw.SetFillAlpha(0.8); //for testing
worldDebugDraw.SetAlpha(1); //for testing
world.SetDebugDraw(worldDebugDraw);*/
var worldDebugDraw:b2DebugDraw = new b2DebugDraw();
worldDebugDraw.SetSprite(debugSprite);
world.SetDebugDraw(worldDebugDraw);
}
DebudDraw works with ONE classic Flash Sprite (you keep creating new ones for some reason). Only one b2DebugDraw should be created and set with that ONE Sprite.
Starling pretends to own the stage and all displaylist but it doesn't. Use simply your StartUp instance or even directly the stage itself without passing through Starling it will avoid some confusion.
The right way to do all this:
public var debugSprite:Sprite;//no static var
Starting what?
//don't start it!
mStarling.start();
You star something that cannot be started. At this point you are trying to create a valid Context3D so be patient. Remove that line.
Now in onContextCreated:
mStarling.start();//now you can start
debugSprite = new Sprite();//create your sprite
addChild(debugSprite);
var game:Game = mStarling.stage.getChildAt(0) as Game;//Game? somebody is following a tutorial ...
if(game)
{
game.setDebug(debugSprite);//this is a new public method to create in Game
}
In Game in method setDebug (with one parameter Sprite):
var worldDebugDraw:b2DebugDraw = new b2DebugDraw();
worldDebugDraw.SetSprite(myspriteparameter);
world.SetDebugDraw(worldDebugDraw);
That's it, don't create new Sprite, don't create new debugdraw, you are good to go that's all you need.

Accessing timers within a actionscript class

I recently started programming in as3, and lately, I've started to learn object oriented programming. My problem is to access functions within a class. I guess that the "main" code is not very suitable for doing so, but I'm pretty much just asking for advice for every part of the code.
Main Code:
import flash.utils.Timer;
import flash.events.TimerEvent;
stage.addEventListener(MouseEvent.CLICK, makeCircle);
function makeCircle(event:MouseEvent):void
{
var s = new Circle();
addChild(s);
s.x = mouseX;
s.y = mouseY;
}
Class code (connected to a MovieClip circle with a MovieClip fill inside):
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.filters.BlurFilter;
import flash.geom.ColorTransform;
public class Circle extends MovieClip
{
private var t:Timer = new Timer(30,1000);
var time:Number = 0;
var size:Number;
var bf = new BlurFilter();
var ct:ColorTransform = new ColorTransform();
public function Circle()
{
// constructor code
t.addEventListener(TimerEvent.TIMER, updateCircle);
t.start();
ct.color = 0xffffff * Math.random();
fill.transform.colorTransform = ct;
fill.blendMode = "hardlight";
}
public function updateCircle(event:TimerEvent):void
{
time = t.currentCount / 10;
size = Math.pow(Math.E, - time) * Math.sin(5 * time) * (Math.log(time));
width = (size * 20 + 100 - time * 5) * 2;
height = (size * 20 + 100 - time * 5) * 2;
bf.blurX = time;
bf.blurY = time;
filters = [bf];
alpha = 1 - time / 20;
}
}
}
What I want to do is to remove the child of s (main code) when the t.currentCount (class code) is a set value (when the alpha value is 0).
Thanks in advance.
whay you want to do is do create either an even inside the Circle class that triggers when your timer completes (alpha == 0). The custom event would have to be caught in your main class.
To put a custom event listener in your main class write:
s.addEventListener("RemoveChild", removeChild)
add the handler function
function removeChild(e:Event)
{
removeChild(s);
}
in your circle class you can add the event when you want to trigger it:
this.dispatchEvent(new Event("RemoveChild");
Alternatively you control the Alpha value from your main class by placing the loop there and call removeChild(s); directly.
An easy way to get your custom events working is by using the AS3Signals framework.
Hope that helps

How can I use a document class in a single AS3 movie clip?

I have a confetti generator that I am tyring to add to a single movie clip within my flash file. The clip is masked and I want to have some graphics and text appear above the confetti (which will be above a background layer as well).
I purchased a decent script and have modified it to work with some original confetti artwork but I can't figure out how to use this class (or change it for use) in just the one movie clip. Pasting the class below. I've been stressing about this for a couple of hours now, any help would be greatly appreciated.
package com.pixeljunkyard
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import caurina.transitions.*;
import fl.motion.Color;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
public class Main extends Sprite
{
//Create Heart Instance
private var hearts:Heart;
//Amount of hearts
private var totalHearts:Number = 30;
//Falling Speed
private var speed:Number = 1.5;
//Constructor
public function Main()
{
//Align top left for screen aspect ratio
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
//Loop through the amount of heart to be created
for (var i = 0; i < totalHearts; i++)
{
//Create new heart
var heart = new Heart();
//Set Random value
var randScale:Number = randRange(50, 100);
var randRotation:Number = randRange( -180, 180);
var randRotationY:Number = randRange( -360, 360);
//Random position and scale
heart.x = randRange(0, stage.stageWidth);
heart.y = randRange( -stage.stageHeight, stage.stageHeight);
heart.scaleX = randScale/100;
heart.scaleY = randScale/100;
//Name each heart with the number of creation
heart.name = "heart" + i;
var Low : int = 1;
var High : int = 8;
var myRandomNumber:int = Math.floor(Math.random()*(1+High-Low))+Low;
heart.gotoAndStop(myRandomNumber);
//Add eventlisteners for interactions
heart.addEventListener(MouseEvent.ROLL_OVER, hit_heart);
heart.addEventListener(Event.ENTER_FRAME, change_shade);
//Initial Animation
Tweener.addTween(heart, {time:randRange(1,5)/speed, rotation:randRotation,rotationY:randRotationY,y:stage.stageHeight+(heart.height/2)+20, transition:"linear", onComplete:rebirth,onCompleteParams:[heart]} );
//Add to Stage
addChildAt(heart, i);
}
}
//Change shade to give lighting effect
private function change_shade(e:Event):void
{
//New color instance
var c:Color = new Color();
//Set properties
c.brightness = e.target.rotation / 300;
//Apply color to heart
e.target.transform.colorTransform = c;
}
//Random Function
private function randRange(min:Number, max:Number):Number
{
var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
return randomNum;
}
//Interactive animation
private function hit_heart(e:Event):void
{
Tweener.addTween(e.target, { time:randRange(1,3), rotationY:e.target.rotationY+180 } );
}
//Reset heart to top of the screen once fallen
private function rebirth($heart:Heart):void
{
$heart.x = randRange(0, stage.stageWidth);
$heart.y = -$heart.height;
Tweener.addTween($heart, {time:randRange(1,5)/speed, rotation:randRange(-180,180),y:stage.stageHeight+($heart.height/2)+20, transition:"linear", onComplete:rebirth,onCompleteParams:[$heart]} );
}
}
}
Now I understand your problem.
First of all, I suggest to never write code on the timeline, except simple stuff like stop() or gotoAndPlay("loop").
The easiest way to achieve what you want is to do the following:
Make a blank MovieClip in Flash IDE Ctrl + F8
Give it a linkage like this:
Then click the edit button (marked with a red rectangle)
Open in Flash Professional if asked
Save the file in your .FLA directory and copy the contents of your Main.as file into this file
Remove the package name ("com.pixeljunkyard")
Change the public class Main extends Sprite to public class ConfettiContainer extends MovieClip and import flash.display.MovieClip
Now you have a class ConfettiContainer which does the same stuff that you Main.as file did. Don't forget to copy anything that this Main.as class uses from stage to your ConfettiContainer MovieClip.
You can now create and use it like this:
var confetti:ConfettiContainer = new ConfettiContainer();
addChild(confetti);
P.S. If you can't see Export for Actionscript option when creating a Symbol in Flash, click Advanced.

Actionscript: How do I rotate an external png image using a matrix?

Okay so I have two import pieces of code involved in this. This first tiny bit is what creates an object called OBJECT_arrow. It is located in the main function of my main class:
new OBJECT_arrow().CREATE(this,200,200);
It isn't really all that important. Now this next bit is the OBJECT_arrow class. What it does is loads an external png image and draws it.
package
{
import flash.net.URLRequest;
import flash.display.*;
import flash.system.*;
import flash.events.*;
import Math;
public class OBJECT_arrow extends Sprite
{
public var X:Number = 0; public var Y:Number = 0;
public var DEPTH:int = 0 ;
public var CONTAINER:Sprite = new Sprite();
public var imageLoader:Loader = new Loader();
public var image:URLRequest = new URLRequest ('ARROW.png');
public function CREATE(CONTAINER:Sprite,X:Number,Y:Number):void
{
this.X = X; imageLoader.x = this.X;
this.Y = Y; imageLoader.y = this.Y;
this.CONTAINER = CONTAINER;
CONTAINER.stage.addEventListener(Event.ENTER_FRAME,STEP);
imageLoader.load(image);
DRAW();
}
public function STEP(event:Event):void
{
DRAW();
}
public function DRAW():void
{
addChild (imageLoader);
(CONTAINER as MAIN).DRAW_LIST[(CONTAINER as MAIN).DRAW_LIST.length] = this;
(CONTAINER as MAIN).DRAW_LIST[(CONTAINER as MAIN).DRAW_LIST.length] = DEPTH;
}
}
}
Now I know the mathematics behind rotation and know to rotate before I translate and everything but I simply don't know how to apply the transformation to an external image in as3.
When you load an image with Loader it is stored as an object of type DisplayObject.
If you want it to be rotated, just set the rotation property.
To apply a matrix, you can use the transform() method of the DisplayObject.
You should also take a look at the BitmapData (raw image data) and Bitmap (DisplayObject to hold the BitmapData) classes. Depending on the complexity of what you're trying to do, they may serve you better. Specifically, BitmapData will allow you to lock() the image while you are fiddling with its bits. Flash won't render the BitmapData until you unlock() it, which can be a great performance improvement if you're doing a lot of fiddling.

Flash CS4 AS3 horizontal movieclip scrolling with mouse move

I'm new to AS3 and have been working on an XML driven navigation system written in AS3.
At present, I've imported the contents of an XML file and plotted it inside a containing MovieClip created at root level dynamically on the stage. This MovieClip is called 'container'.
What I want to accomplish is a smooth, accelerating / decelerating effect which animates the container movieclip along the X axis depending on where the mouse cursor is in relation to the middle of the stage.
My code can be found here: http://pastie.org/521432
Line 87 onwards is the code I'm using right now to make the movieclip scroll left & right.
What I have does work but is clunky but does work - I just want it to be a little more polished and have drawn a blank with Google. Because I want the MovieClip to continue to scroll at the current relative speed even when the mouse stops moving, I used an instance of the Timer class.
Can anyone suggest improvements? Thanks in advance.
You should separate out you calculations and your drawing methods. So have it do all the calculations in an onMouseMove handler, but actually draw the changes in an onEnterFrame handler.
Also I think your algorithm could be much simpler and nobody would notice. I made a quick example of how you might do it. paste this code into an AS3 file called Main.as and make it the document class of a new FLA.
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends Sprite
{
private const boxCount:int = 10;
private const boxWidth:int = 45;
private const boxMargin:int = 5;
private const startPoint:int = 150;
private const boxesWidth:int = boxCount * (boxWidth + boxMargin);
private const endPoint:int = boxesWidth + startPoint;
private const zeroPoint:int = boxesWidth / 2 + startPoint;
private var container:MovieClip;
private var targetX:Number;
private var speed:Number = 0;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
container = new MovieClip();
addChild(container);
container.x = 150;
container.y = 300;
for (var i:int = 0; i < boxCount; i++)
{
container.graphics.beginFill(Math.random() * 0xFFFFFF);
container.graphics.drawRect(i*(boxWidth+boxMargin), 0, boxWidth, boxWidth);
}
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
}
private function mouseMoveHandler(e:MouseEvent):void
{
var distanceFromCenter:int = stage.mouseX - zeroPoint;
speed = distanceFromCenter * -0.01; // Bring number into a good range, and invert it.
}
private function enterFrameHandler(e:Event):void
{
container.x += speed;
}
}
}