"if (MouseEvent.CLICK = true) " error in Actionscript 3? - actionscript-3

These are the two errors;
1067: Implicit coercion of a value of type Boolean to an unrelated
type String.
1049: Illegal assignment to a variable specified as
constant.
I want to basically set it so, if mouse is click
the -y speed of symbol helicopter = variable 'speed'
Any help? Thanks

This test doesn't mean anything: MouseEvent.CLICK is a constant and its value is always "click". So (MouseEvent.CLICK) will always be true (testing a string returns true if this string is not null).
To check if the mouse is down, you should write something like that:
var mouseDown:Boolean;
addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onMouseDown(event:MouseEvent):void
{
mouseDown = true;
}
function onMouseUp(event:MouseEvent):void
{
mouseDown = false;
}
function onEnterFrame(event:Event):void
{
if (mouseDown)
{
helicopter.y += speed;
}
else
{
//maybe fall?
}
}

Related

Flash CC error 1136

I'm trying to stop this slideshow by pressing spacebar and I keep encountering error 1136 with no hope.
stop();
gotoAndPlay(15);
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressedKey);
function stopSlideshow (e:KeyboardEvent):void {
gotoAndStop("Home");
}
function pressedKey (event:KeyboardEvent):void {
if (event.keyCode == Keyboard.SPACE)
stopSlideshow();
}
The error 1136 is fired because you have defined the stopSlideshow() function with one parameter (an KeyboardEvent object) but when you've called it you forgot to pass it an KeyboardEvent object as its only argument.
So to avoid that, you can define the KeyboardEvent parameter as optional :
function stopSlideshow (e:KeyboardEvent = null):void
{
gotoAndStop("Home");
}
Also you can use the KeyboardEvent object used by your pressedKey() function as an argument :
function pressedKey(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.SPACE){
stopSlideshow(event);
}
}
Or you can define a new KeyboardEvent object, for example, like this :
var keyboard_event:KeyboardEvent = new KeyboardEvent(KeyboardEvent.KEY_DOWN);
stopSlideshow(keyboard_event);
This will avoid the error but I don't know why you need the stopSlideshow()'s KeyboardEvent parameter because according to your posted code you can use that function without any parameter ...
Hope that can help.

How to add keyboard interaction in AS3

I got 16 different buttons in this application, each button playing different kind of sound. Currently i only able to use mouse click to start playing sound, and click again to stop, but now i wish to add shortcut key to access those track buttons, like pressing "q" for track 1, "w" for track 2. Any hints or tips like what am i suppose to do to achieve this? Thanks a lot.
private var _ambientTracks:Array = [ambient1, ambient2, ambient3, ambient4];
private var _effectTracks:Array = [effect1, effect2, effect3, effect4];
private var _melodyTracks:Array = [melody1, melody2, melody3, melody4];
private var _beatTracks:Array = [beat1, beat2, beat3, beat4];
//handle click on track invoke start / stop functions
private function onTrackClicked(event:MouseEvent):void {
var track:Sprite = event.currentTarget as Sprite;
var trackName:String = track.name;
if (trackName in _playingTracks) {
stopTrack(track);
delete _playingTracks[trackName];
} else {
startTrack(track);
_playingTracks[trackName] = trackName;
}
}
//starts track animation and dispatch event for TrackMixer
private function startTrack(track:Sprite):void {
Actuate.tween(track, 0.6, {alpha: 0.3}).reflect().repeat();
dispatchEvent(new ObjectEvent(START_TRACK, track.name, true));
}
//stop track animation and dispatch event for TrackMixer
private function stopTrack(track:Sprite):void {
Actuate.stop(track, "alpha");
track.alpha = 1;
dispatchEvent(new ObjectEvent(STOP_TRACK, track.name, true));
}
Here is a basic concept similar to what you are trying to achieve you need to listen for a key press and use the specific key code handle what key is being pressed, if you have lots of key commands I suggest using a switch case.
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0x000000);
mc.graphics.drawCircle(30,30,30);
mc.graphics.endFill();
stage.addEventListener(KeyboardEvent.KEY_UP,keyUp);
function keyUp(e:KeyboardEvent):void{
if(e.keyCode == 81){//q
addChild(mc);
}
if(e.keyCode == 87){//w
if(mc.stage){
removeChild(mc);
}
}
}
It would still use the similar concepts, however you need to someway to "toggle" the same key to play and stop. A boolean variable would fit nicely to track the state of the key press.
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
//Code to create a simple black circle xpos: 30 ypos: 30 radius: 30
var mc: MovieClip = new MovieClip();
mc.graphics.beginFill(0x000000);
mc.graphics.drawCircle(30, 30, 30);
mc.graphics.endFill();
//Adding event listener to stage for a key up event
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
/*
Creating a boolean value to track "on" or "off" for one key.
Default value for boolean is false.
*/
var bool: Boolean;
function keyUp(e: KeyboardEvent): void {
if (e.keyCode == 81) {
if (!bool) {
addChild(mc);
bool = true;
} else {
if (mc.stage) {
removeChild(mc);
bool = false;
}
}
}
}
if key == q and bool == false add mc to stage and set bool to true.
The next time this method is called, bool will be true in which case the else statement
will be fired off (because bool is not false). The stage will be checked to see if mc exists to avoid errors, mc will be removed from stage, and bool will be set back to false in order to meet the condition of the if statement (bool is false).

How to register hitTest only if Mouse Down is true?

I was wondering on how to register a Hittest between two Movie Clips only if the MOUSE_DOWN event is equal to true.
So I have a Movie Clip called playerHook that acts as the Mouse and whenever that movie clip comes in contact with another movie clip called octopusBoss and Clicks on it I want it to register a hittest and subtract a point from its health.
Here is what I have so far but not sure what to do next:
In my main constructor function:
playerHook.addEventListener(Event.ENTER_FRAME, playerHookMove);
playerHook.addEventListener(MouseEvent.MOUSE_DOWN, onMDown);
playerHook.addEventListener(MouseEvent.MOUSE_UP, onMUp);
Then I have two booleas set up in the two functions onMDown and onMUp:
private function onMDown(e:MouseEvent):void
{
mouseIsDown = true;
}
private function onMUp(e:MouseEvent):void
{
mouseIsUp = false;
}
Then I have this function which is currently in my gameloop that I would want to happen only if the user clicks on the OctopusBoss:
private function checkPlayerHitOctopusBoss():void
{
if (playerHook.hitTestObject(octopusBoss))
{
trace("Hit Octopus");
octopusBossHealth --;
}else
if (octopusBossHealth <= 0)
{
octopusBoss.destroyOctopusBoss();
}
}
But I am having trouble passing the mouse booleans to the if statement. I know I am missing something crucial!
First you need some name to your octopusBoss like so:
octopusBoss.name = "octopusBoss";
Modify your onMDown function like so:
private function onMDown(e:MouseEvent):void
{
if(e.target.name == "octopusBoss") //Check if octopusBoss is under mouse
mouseIsDown = true;
}
And your checkPlayerHitOctopusBoss function like so:
private function checkPlayerHitOctopusBoss():void
{
if (playerHook.hitTestObject(octopusBoss) && mouseIsDown) // check mouse down
{
trace("Hit Octopus");
octopusBossHealth --;
}else
if (octopusBossHealth <= 0)
{
octopusBoss.destroyOctopusBoss();
}
}
UPDATE:
If it's ok to add MouseEvents directly to octopusBoss like so:
octopusBoss.addEventListener(MouseEvent.MOUSE_DOWN, onMDown);
octopusBoss.addEventListener(MouseEvent.MOUSE_UP, onMUp);
Then, you can also use e.currentTarget.name.

AS3 Drag always snaps back to original place?

making a simple app with a slider that changes a text box value, but whenever i drop the slider, it snaps back to its 0 position. i need it to stay in place. please help!
code:
theroot.settings_but.phone1.slider.addEventListener(MouseEvent.MOUSE_DOWN, slide);
public function slide(e:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP, dragstop);
var bounds:Rectangle = new Rectangle(0,27,550,0);
theroot.settings_but.phone1.slider.startDrag(false, bounds);
txtboxint = setInterval(changetextbox, 500);
}
public function dragstop(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, dragstop);
clearInterval(txtboxint);
trace("what", e.target.x, e.currentTarget, e.target.name) // returns proper x value, [object Stage], slider
trace("almost", theroot.settings_but.phone1.slider.x);// returns proper x value
theroot.settings_but.phone1.slider.stopDrag();
trace("last", theroot.settings_but.phone1.slider.x); //returns proper x value
}
public function changetextbox():void
{
trace(theroot.settings_but.phone1.slider.x) //returns proper x value
theroot.settings_but.phone1txt.text = (Math.floor(((theroot.settings_but.phone1.slider.x) / 550) * 40));
}
Try this,
theroot.settings_but.phone1.slider.addEventListener(MouseEvent.MOUSE_DOWN, slide);
public function slide(e:MouseEvent):void
{
theroot.settings_but.phone1.slider.removeEventListener(MouseEvent.MOUSE_DOWN, slide);
stage.addEventListener(MouseEvent.MOUSE_UP, dragstop);
var bounds:Rectangle = new Rectangle(0,27,550,0);
theroot.settings_but.phone1.slider.startDrag(false, bounds);
theroot.settings_but.phone1.slider.addEventListener(Event.ENTER_FRAME,changetextbox);
}
public function dragstop(e:MouseEvent):void
{
theroot.settings_but.phone1.slider.stopDrag();
stage.removeEventListener(MouseEvent.MOUSE_UP, dragstop);
trace("what", e.target.x, e.currentTarget, e.target.name) // returns proper x value, [object Stage], slider
trace("almost", theroot.settings_but.phone1.slider.x);// returns proper x value
trace("last", theroot.settings_but.phone1.slider.x); //returns proper x value theroot.settings_but.phone1.slider.removeEventListener(Event.ENTER_FRAME,changetextbox);
theroot.settings_but.phone1.slider.addEventListener(MouseEvent.MOUSE_DOWN, slide);
}
public function changetextbox(e:Event):void
{
trace(theroot.settings_but.phone1.slider.x) //returns proper x value
theroot.settings_but.phone1txt.text = (Math.floor(((theroot.settings_but.phone1.slider.x) / 550) * 40));
}
problem was event bubbling over to main MC, which caused the MC with the sliders within to goto frame 0
thanks for all your help!

What is the most effective way to test for combined keyboard arrow direction in ActionScript 3.0?

I need to monitor the direction a user is indicating using the four directional arrow keys on a keyboard in ActionScript 3.0 and I want to know the most efficient and effective way to do this.
I've got several ideas of how to do it, and I'm not sure which would be best. I've found that when tracking Keyboard.KEY_DOWN events, the event repeats as long as the key is down, so the event function is repeated as well. This broke the method I had originally chosen to use, and the methods I've been able to think of require a lot of comparison operators.
The best way I've been able to think of would be to use bitwise operators on a uint variable. Here's what I'm thinking
var _direction:uint = 0x0; // The Current Direction
That's the current direction variable. In the Keyboard.KEY_DOWN event handler I'll have it check what key is down, and use a bitwise AND operation to see if it's already toggled on, and if it's not, I'll add it in using basic addition. So, up would be 0x1 and down would be 0x2 and both up and down would be 0x3, for example. It would look something like this:
private function keyDownHandler(e:KeyboardEvent):void
{
switch(e.keyCode)
{
case Keyboard.UP:
if(!(_direction & 0x1)) _direction += 0x1;
break;
case Keyboard.DOWN:
if(!(_direction & 0x2)) _direction += 0x2;
break;
// And So On...
}
}
The keyUpHandler wouldn't need the if operation since it only triggers once when the key goes up, instead of repeating. I'll be able to test the current direction by using a switch statement labeled with numbers from 0 to 15 for the sixteen possible combinations. That should work, but it doesn't seem terribly elegant to me, given all of the if statements in the repeating keyDown event handler, and the huge switch.
private function checkDirection():void
{
switch(_direction)
{
case 0:
// Center
break;
case 1:
// Up
break;
case 2:
// Down
break;
case 3:
// Up and Down
break;
case 4:
// Left
break;
// And So On...
}
}
Is there a better way to do this?
You can keep track of whether each key is down or not by listening for all KEY_DOWN and KEY_UP events, and storing each key state in an array. I wrote a class a while ago to do just that (included at the end of my answer).
Then you are no longer tied to the event model to know if a certain key is down or not; you can periodically check every frame (or every timer interval). So you could have a function like:
function enterFrameCallback(e:Event):void
{
var speed:Number = 1.0; // net pixels per frame movement
thing.x += (
-(int)Input.isKeyDown(Keyboard.LEFT)
+(int)Input.isKeyDown(Keyboard.RIGHT)
) * speed;
thing.y += (
-(int)Input.isKeyDown(Keyboard.UP)
+(int)Input.isKeyDown(Keyboard.DOWN)
) * speed;
}
which would take into account all possible combinations of arrow key presses. If you want the net displacement to be constant (e.g. when going right and down at same time, the object moves X pixels diagonally, as opposed to X pixels in both horizontal and vertical directions), the code becomes:
function enterFrameCallback(e:Event):void
{
var speed:Number = 1.0; // net pixels per frame movement
var displacement:Point = new Point();
displacement.x = (
-(int)Input.isKeyDown(Keyboard.LEFT)
+(int)Input.isKeyDown(Keyboard.RIGHT)
);
displacement.y = (
-(int)Input.isKeyDown(Keyboard.UP)
+(int)Input.isKeyDown(Keyboard.DOWN)
);
displacement.normalize(speed);
thing.x += displacement.x;
thing.y += displacement.y;
}
Here is the Input class I wrote (don't forget to call init from the document class). Note that it also keeps track of mouse stuff; you can delete that if you don't need it:
/*******************************************************************************
* DESCRIPTION: Defines a simple input class that allows the programmer to
* determine at any instant whether a specific key is down or not,
* or if the mouse button is down or not (and where the cursor
* is respective to a certain DisplayObject).
* USAGE: Call init once before using any other methods, and pass a reference to
* the stage. Use the public methods commented below to query input states.
*******************************************************************************/
package
{
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.display.Stage;
import flash.geom.Point;
import flash.display.DisplayObject;
public class Input
{
private static var keyState:Array = new Array();
private static var _mouseDown:Boolean = false;
private static var mouseLoc:Point = new Point();
private static var mouseDownLoc:Point = new Point();
// Call before any other functions in this class:
public static function init(stage:Stage):void
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, false, 10);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp, false, 10);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown, false, 10);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp, false, 10);
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove, false, 10);
}
// Call to query whether a certain keyboard key is down.
// For a non-printable key: Input.isKeyDown(Keyboard.KEY)
// For a letter (case insensitive): Input.isKeyDown('A')
public static function isKeyDown(key:*):Boolean
{
if (typeof key == "string") {
key = key.toUpperCase().charCodeAt(0);
}
return keyState[key];
}
// Property that is true if the mouse is down, false otherwise:
public static function get mouseDown():Boolean
{
return _mouseDown;
}
// Gets the current coordinates of the mouse with respect to a certain DisplayObject.
// Leaving out the DisplayObject paramter will return the mouse location with respect
// to the stage (global coordinates):
public static function getMouseLoc(respectiveTo:DisplayObject = null):Point
{
if (respectiveTo == null) {
return mouseLoc.clone();
}
return respectiveTo.globalToLocal(mouseLoc);
}
// Gets the coordinates where the mouse was when it was last down or up, with respect
// to a certain DisplayObject. Leaving out the DisplayObject paramter will return the
// location with respect to the stage (global coordinates):
public static function getMouseDownLoc(respectiveTo:DisplayObject = null):Point
{
if (respectiveTo == null) {
return mouseDownLoc.clone();
}
return respectiveTo.globalToLocal(mouseDownLoc);
}
// Resets the state of the keyboard and mouse:
public static function reset():void
{
for (var i:String in keyState) {
keyState[i] = false;
}
_mouseDown = false;
mouseLoc = new Point();
mouseDownLoc = new Point();
}
///// PRIVATE METHODS BEWLOW /////
private static function onMouseDown(e:MouseEvent):void
{
_mouseDown = true;
mouseDownLoc = new Point(e.stageX, e.stageY);
}
private static function onMouseUp(e:MouseEvent):void
{
_mouseDown = false;
mouseDownLoc = new Point(e.stageX, e.stageY);
}
private static function onMouseMove(e:MouseEvent):void
{
mouseLoc = new Point(e.stageX, e.stageY);
}
private static function onKeyDown(e:KeyboardEvent):void
{
keyState[e.keyCode] = true;
}
private static function onKeyUp(e:KeyboardEvent):void
{
keyState[e.keyCode] = false;
}
}
}