My sprite will not display, I am making a side scroller on as3 - actionscript-3

I am making a game where my rocket ship has to avoid asteroids. However, my rocket ship sprite will not display. Any helps is appreciated.
var myRocket:MovieClip;
addChild(myRocket);
myRocket.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
myRocket.addEventListener(KeyboardEvent.KEY_UP, keyUp);
myRocket.x=200;
myRocket.y=150;

Ok, that's how you instantiate things from Library.
First, the Library object must have an AS3 class. You assign it in the Library object's properties. Let's say the class name is SpaceRocket.
Then you do the following:
// Instantiate the object by its class.
var rocket:SpaceRocket = new SpaceRocket;
// Assign coordinates.
rocket.x = 200;
rocket.y = 150;
// Add the instance to the display list.
addChild(rocket);
Also, I don't recommend listening the rocket for the keyboard events. It means the rocket should have the keyboard focus, which can be lost quite easily. You should rather listen it at the stage because all the keyboard events go there eventually:
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);

Related

click events don't reach root flash object

I started using as3 a while ago, and mostly used starling instead of native flash objects. Today I decided to give a try to raw flash, and created a simple button:
private var _button: SimpleButton;
public function Main()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
_button = new SimpleButton(new BUTTON); //BUTTON is an embedded bitmap
addChild(_button);
_button.useHandCursor = true;
_button.addEventListener(MouseEvent.CLICK, OnClick);
}
private function OnClick(e:MouseEvent):void
{
trace("clicked");
}
This would definely work in starling, but I found that the click event won't dispatch to the button for some reason. Neither is hand cursor shown on mouse over. I tried mouse over, mouse up and other mouse events, but none of them work. I checked that the button is correctly added to stage. Also, when I add a mouse click event listener to the stage itself, clicks register normally. When I add a listener to Main, no events are registered again.
I'm probably misunderstanding something obvious. Maybe I need to dispatch events manually down to the children? But that would be strage, though. Or can it be a bug in FlashDevelop? Please, help.
The constructor of SimpleButton takes 4 optional parameters:
public function SimpleButton(upState:DisplayObject = null,
overState:DisplayObject = null,
downState:DisplayObject = null,
hitTestState:DisplayObject = null)`
of which you supply the first one (upState):
_button = new SimpleButton(new BUTTON); //BUTTON is an embedded bitmap
The others default to null. That includes hitTestState which is the same as property of the class hitTestState:
Specifies a display object that is used as the hit testing object for the button. [...] If you do not set the hitTestState property, the SimpleButton is inactive — it does not respond to user input events.
It also includes a solution to your problem:
For a basic button, set the hitTestState property to the same display object as the overState property.
However, if all you want is to add click functionality to that Bitmap, which it doesn't have on its own, because it's not an InteractiveObject, simply use a Sprite:
// entry point
_button = new Sprite();
_button.addChild(new BUTTON); //BUTTON is an embedded bitmap
addChild(_button);
_button.useHandCursor = true;
_button.addEventListener(MouseEvent.CLICK, OnClick);
Use SimpleButton only if you want the functionality of its 4 states.
Please be careful with the overloaded term "stage":
I checked that the button is correctly added to stage.
If you mean the "drawing area" that you can see in the Adobe Flash IDE or the main time line with "stage", then yes, you'd be correct that your button is added to that.
The stage property of DisplayObject however is something different. It's the top most element of the display list and the container that the instance of your Main class is added to, which happens at the start of the execution of your .swf in the FlashPlayer.
As your Main class adds the _button to itself by calling its ownaddChild(), the button is added to the instance of Main and not stage, which are two different objects.

Does adding eventListener with same params null/replace previous eventListeners?

I've inherited a large, legacy Flex project and the deeper I get into the code, the more concerned I am becoming. For example, I am looking at code for a "window" type image viewer within the app. Every time it is displayed, the eventListeners below are added and never removed.
Since these are strong references and never removed, that is one problem but this repeatedly adding eventListeners is giving me pause. The "window" can be displayed and hidden many times in the lifecycle of the app.
My question: does this mean that is has n = (4 * number of times displayed) eventListeners? (...shudder).
This is a huge project revision on a tight budget so I am trying to determine if I fix this sort of thing or just let it go.
addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
If they are different eventlisteners, they will be added multiple times. If they all refer to the same function, it will be overridden each time, calling the specific function only once.
try out the following short example to see what i mean:
var s:Sprite = new Sprite(); //some sort of displayobject with EventDispatcher capabilities
s.addEventListener(MouseEvent.CLICK, onClick);
s.addEventListener(MouseEvent.CLICK, onClick);
function onClick(e:MouseEvent):void{
trace("hey");
}
pressing on the Sprite will give you a console output of "hey", not two "hey"s.
Now consider the following:
var s:Sprite = new Sprite();
s.addEventListener(MouseEvent.CLICK, onClick);
s.addEventListener(MouseEvent.CLICK, onClick2);
function onClick(e:MouseEvent):void{
trace("hey");
}
function onClick2(e:MouseEvent):void{
trace("sup");
}
This will give you an output of "hey" and "sup" once you press on the Sprite.
If you are really concerned, you could just give the event listener a weak reference. I don't know how complex the project is you're working on, but implementing something to get rid of all eventlisteners at once (like, waiting for Event.REMOVED_FROM_STAGE and then manually removing the listeners) shouldn't be too time-intensive.

MouseEvent not dispatching on movie clip

I know this must be easy but somehow I have not been able to figure it out after spending more than hours. I have two movie clips in a class that extends Sprite. When I add event listener to the stage every thing works fine. But when I try to add event listener to one of the movie clips, the event never dispatches it seems. Here is how it looks like -
public class MyClass extends Sprite
{
private var movieclip1:MovieClip, movieclip2:MovieClip;
private function init(e:Event == null):void
{
movieclip1 = new MovieClip();
movieclip2 = new MovieClip();
//works fine, dispatches event
stage.addEventListener(MouseEvent.MOUSE_DOWN. mousedown);
//not working
movieclip1.addEventListener(MouseEvent.MOUSE_DOWN, mousedown);
addChild(movieclip1);
addChild(movieclip2);
}
}
Actually I want both the movie clips to work mutually exclusively, i.e., a mouse event on one movie clip should not interfere with that of the other. Any pointers?
Empty MovieClips and Sprites CANNOT be sized, they will be 0,0 and then they will not be able to dispatch MouseEvents.
You can resize a MovieClip when it has some content.
The Sprite will be of the size of the rectangle that encloses the 2 MovieClip.
If the MovieClips are empty = 0,0 the Sprite will be 0,0
About the events between the 2 MovieClips:
They are not going to interfere because the events when are bubbling goes upwards.
So the listeners put on MC1 will listen ONLY onClick on MC1 and the same does MC2
You can trace the width and height of the movieclip1 or movieclip2, you will get 0 both.
So, you can't click them.
You can use graphcis to draw a shape in these two mcs, and try again.

AS3 MouseEvent and weakReference

Ok, here's a weird thing:
I have a class, which is a MovieClip that has 2 children, MovieClips also.
I add the children to him and base MovieClip to stage.One of the children is animated.
All is perfect.
Now when I add MouseEvent.MOUSE_UP on the children, all works fine.
Yet if I set useWeakReference to true (the 5th parameter) mouse event does not fire anymore,but the items are on stage. Basically, somehow, they are not in the memory.
Of course if I add a simple onEnterFrame that does nothing to base MovieClip, it traces the MovieClip, yet the MouseEvents does not trigger. That means the object is still there, but somehow for flash is not
Now, this is a simplified concept, that is easy to clean, but my code is very big and a simple removeEventListener is not a solution. At least not a simple one.
What are your suggestions to work around this?
I'm not sure how complex your code is, but if each movieclip has MOUSE_UP event handler - some function, you could indeed use removeEventListener MOUSE_UP function. For instance:
var mc:MovieClip = new MovieClip();
mc.addEventListener( MouseEvent.MOUSE_UP, onMU );
function onMU(e:MouseEvent){
var target = MovieClip(e.currentTarget);
target.removeEventListener( MouseEvent.MOUSE_UP, onMU );
}
This way you can have multiple movieclips and remove listeners without knowing object name.
Alternatively you could modify your code to add aray of all added events and then listen to REMOVE_FROM_STAGE event. Something like this:
var mc:MovieClip = new MovieClip();
mc.events = [];
mc.events.push( { evt: MouseEvent.MOUSE_UP, fn: onMU } );
mc.addEventListener( MouseEvent.MOUSE_UP, onMU } )
//or use events array reference to keep events and functions in one place.
//when object is removed you can iterate through events array and automatically remove
//all listeners
Another alternative would be to create Class that extends MovieClip - but since your code is huge you probably don't want to do that.
You can also look on Robert Penner's Signals library, which is interesting alternative to AS3 events. (https://github.com/robertpenner/as3-signals)

AS3 collision dectection mouse movement

I am making a game which uses collision detection with the mouse.
The player is a custom mouse cursor when the mouse collies with an object the mouse is moved to the coordinates X0,Y0. The code I have used to achieve this is below. However when the mouse is moved to X0,Y0 after a collision when the mouse is moved it starts back where the collision took place rather than moving from the top of the screen.
import flash.events.Event;
var cursor:MovieClip;
function initializeMovie ():void {
cursor = new Cursor();
addChild (cursor);
cursor.enabled = false;
Mouse.hide ();
stage.addEventListener (MouseEvent.MOUSE_MOVE, dragCursor);
}
function dragCursor (event:MouseEvent):void{
cursor.x = this.mouseX;
cursor.y = this.mouseY;
}
initializeMovie ();
this.addEventListener( Event.ENTER_FRAME, handleCollision)
function handleCollision( e:Event ):void{
if(cursor.hitTestObject( wall )){
cursor.x = 0
cursor.y = 0
}
}
Create a button at the 0, 0 coord that is required to click to continue again. Then your user will have to move the mouse to to that spot where you can continue to have the custom cursor track your mouse.
When you reset the position of cursor object you aren't moving the actual mouse position, I don't believe you can actual do what you're trying to (that is write to the mouse position to move the users cursor, I believe this would require system specific code, like C# or I believe Objective C and Cocoa or Carbon on the Mac side).
http://www.kirupa.com/forum/showthread.php?354641-Possible-to-set-mouse-position-in-flash
Here's a way you would do it on Mac apparently
https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/Quartz_Services_Ref/Reference/reference.html#//apple_ref/c/func/CGWarpMouseCursorPosition
And a way on Windows
Set Mouseposition in WPF
And a way on Linux (Although this only has AIR support up to 2.6)
How to set the mouse position under X11 (linux desktop)?
So if you implemented both of those solutions and are packaging as an AIR app you could make this work, but otherwise I'm pretty sure it's impossible.