1084: Syntax error: expecting rightbrace before function - actionscript-3

I'm new to as3 can you help me please.
getting this error 1084: Syntax error: expecting rightbrace before function.
Please let me know if you would like the rest of the code. This one line might not explain all of the needed information.
public function U1A4_Monnaie():void
{
EDIT
Here is the original code. I counted the amount of brackets both closing and opening, and they seem to match up with eachother, but I might be wrong...
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.text.TextInteractionMode;
public class U1A4_Monnaie extends MovieClip {
private var monMessage:TextField=new TextField;
private var maMiseEnForme:TextFormat=new TextFormat;
**private var btnSoumettre:Sprite;
private var montant:TextField=new TextField;**
public function U1A4_Monnaie():void
{
montant = new TextField();
montant.border=true;
montant.text = "100";
montant.height = 20;
montant.type = TextFieldType.INPUT;
this.addChild(montant);
btnSoumettre = new Sprite();
btnSoumettre.y = 22;
btnSoumettre.graphics.beginFill(0xFF0000, 1);
btnSoumettre.graphics.drawRect(0, 0, 100, 20);
btnSoumettre.graphics.endFill();
this.addChild(btnSoumettre);
btnSoumettre.addEventListener(MouseEvent.CLICK, calculeMonnaie);
}
private function calculeMonnaie(event:MouseEvent):void {
nouvMessage.font="Arial";
nouvMessage.size=20;
nouvMessage.bold=true;
nouvMessage.color=0xFFFFFF;
nouvMessage.x=20;
nouvMessage.y=20;
maMiseEnForme.font="Arial";
maMiseEnForme.size=20;
maMiseEnForme.bold=true;
maMiseEnForme.color=0x660000;
monMessage.x=20;
monMessage.y=190;
monMessage.autoSize=TextFieldAutoSize.LEFT;
monMessage.border=true;
monMessage.defaultTextFormat=maMiseEnForme;
var somme:Number;
var totalCents:int;
var pieces25Cents:int=0;
var pieces10Cents:int=0;
var pieces5Cents:int=0;
var pieces1Cent:int=0;
var restant:int=0;
var nouvMessage:String;
somme = Number(montant.text);
totalCents = int(somme * 100);
pieces25Cents = totalCents / 25;
restant= totalCents % 25;
pieces10Cents = restant / 10;
restant = restant % 10;
pieces5Cents = restant / 5;
restant = restant % 5;
pieces1Cent = restant;
montant.text="";
nouvMessage =("Montant à transformer en monnaie: " + somme + "$" +
"\n25 cents: " + pieces25Cents +
"\n10 cents: " + pieces10Cents +
"\n5 cents: " + pieces5Cents +
"\n1 cent: " + pieces1Cent);
trace()monMessage.text=nouvMessage;
addChild(monMessage);
}
}

That error can sometimes be deceiving because it can be thrown even if the all the brackets are there.
In your case, the issue is this line (second to last line of code):
trace()monMessage.text=nouvMessage;
There should be a terminator after trace() to separate it from the next character.
trace(); monMessage.text=nouvMessage;
Or (since an empty trace is rather pointless) perhaps you mean to do the following:
trace(monMessage.text = nouvMessage);
which would trace the updated value of monMessage.text.
Though most would probably agree that this is cleaner:
monMessage.text = mouvMessage;
trace(monMessage.text);

Related

Access of undefined propety and other errors (AS3)

ok so I am trying to work on making my scripts external .as files.
I had them on the timeline and they worked fine but when I put them in the as file they don't work at all.
This is my code as of right now
so I got the script working externally thank you very much :)
I just need to addchild to the stage. I use
import Scripts.resources.main;
var Main:main = new main;
addChild(Main);
In my external script I addchild in the main function now.
package Scripts.resources
{
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoader;
import flash.net.URLRequestMethod;
import flash.events.OutputProgressEvent;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.EventDispatcher;
public class main extends EventDispatcher{
private var _stage:Stage;
var url:String = "php/data_user.php";
//declare our graphic vars
var stmBar:resourceBar;
var tenBar:resourceBar;
var potBar:resourceBar;
var spdBar:resourceBar;
var crtBar:resourceBar;
var awrBar:resourceBar;
var resBar:resourceBar;
var statUp:Sprite;
//This Returns the number of milliseconds since midnight January 1, 1970
//Tacking the time variable at the end of your php file locations will ensure their is no caching
var now:Date = new Date();
var time:Number = now.getTime();
/*
* These should point to your PHP files. I recommend NOT using an http path because accessing
* the site via 'www.yoursite.com' versus 'yoursite.com' makes a difference and will cause undefined
* issues. Instead use a relative path like: var registerLocation:String = "membership/php/register.php";
*/
var registerLocation:String = "php/register.php" + "?" + time;
var loginLocation:String = "php/login.php" + "?" + time;
var editProfileLocation:String = "php/editprofile.php" + "?" + time;
var forgotPWLocation:String = "php/forgotpw.php" + "?" + time;
var statsLocation:String = "php/user_stats.php" + "?" + time;
var statsGylph:String = "php/data_user.php" + "?" + time;
//userInfo is the Object that gets populated that stores all of the users information.
var userInfo:Object = new Object();
//The minimum length of a password.
var passwordLength:Number = 4;
/*
* var cookie refers to swfObjects addVariable. If you look at membership.php, where swf
* object is defined, addVariable shows a var called usercookie.
* This help decide if the program should remember the users username or not.
*/
//cookieUserName would be the username that gets put into the user field if the cookie has been set
public function main(stage:Stage)
{
_stage = stage;
var _loader:URLLoader = new URLLoader();
var _request:URLRequest = new URLRequest(url + "?id=" + userInfo.id);
_request.method = URLRequestMethod.GET;
_loader.addEventListener(Event.COMPLETE, onLoadData);
_loader.load(_request);
_stage.addChild(stmBar);
stmBar.x = -50;
stmBar.y = 200;
}
public function MyClass(){
this.addEventListener(Event.ADDED_TO_STAGE, addedToStage);
}
private function addedToStage(e:Event):void {
this.removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
//this code will run after you've added this object to the stage
//it is the equivalent of when timeline code runs
}
function onLoadData(e:Event):void {
var str:String = e.target.data;
var array:Array =str.split("-");
for(var i:int;i < array.length; i++)
output(i+1,array[i]);
}
public function output(field:Number,i:int):void
{
if (field == 5)
{
stmBar = new resourceBar(0, 0, i, "Stamina", 0x990000);
stmBar.x = -200;
stmBar.y = 50;
}
else if (field == 6)
{
tenBar = new resourceBar(0, 0, i, "Tenacity", 0xFF9900);
tenBar.x = 200;
tenBar.y = 50;
}
else if (field == 7)
{
potBar = new resourceBar(0, 0, i, "Potency", 0xCC3399);
potBar.x = -200;
potBar.y = 100;
}
else if (field == 8)
{
spdBar = new resourceBar(0, 0, i, "Speed", 0x00CC00);
spdBar.x = 200;
spdBar.y = 100;
}
else if (field == 9)
{
crtBar = new resourceBar(0, 0, i, "Crit", 0x009999);
crtBar.x = -200;
crtBar.y = 150;
}
else if (field == 10)
{
awrBar = new resourceBar(0, 0, i, "Awareness", 0x3399CC);
awrBar.x = 200;
awrBar.y = 150;
}
else if (field == 11)
{
resBar = new resourceBar(0, 0, i, "Resistance", 0x999999);
resBar.x = -200;
resBar.y = 200;
addEventListener(Event.ENTER_FRAME, onLoop);
}
function onLoop(e:Event):void
{
stmBar.change(1);
tenBar.change(1);
potBar.change(1);
spdBar.change(1);
crtBar.change(1);
awrBar.change(1);
resBar.change(1);
}
}
}
}
my problem is it won't add the children in the main function when I addchild of main. am I able to add a child with children inside it?
In class files, all code needs to be wrapped in a function. So where you have:
_loader = new URLLoader();
_request = new URLRequest(url + "?id=" + (STAGE.parent as MovieClip).userInfo.id);
_request.method = URLRequestMethod.GET;
_loader.addEventListener(Event.COMPLETE, onLoadData);
_loader.load(_request);
You need to place it in a function for the code to be valid. If you want that bit of code to run right away, then you can place it in a constructor (that is the function in class that runs when you instantiate with the new keyword, eg new main(). If main is your document class, then the constructor is the very first code to run in the application.
Constructors are public functions that have the exact name of your Class.
public function main(){
_loader = new URLLoader();
_request = new URLRequest(url + "?id=" + (STAGE.parent as MovieClip).userInfo.id);
_request.method = URLRequestMethod.GET;
_loader.addEventListener(Event.COMPLETE, onLoadData);
_loader.load(_request);
}
Something to keep in mind, is that in the constructor of display objects, the stage/parent/root keywords will NOT have any value, as those are populated once the display object has been added to the display. So, it's common to use this approach:
package MyClass extends Sprite {
public function MyClass(){
this.addEventListener(Event.ADDED_TO_STAGE, addedToStage);
}
private function addedToStage(e:Event):void {
this.removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
//this code will run after you've added this object to the stage
//it is the equivalent of when timeline code runs
}
}
Also, a tip now that you are writing class files - follow the convention of making class names start with an Uppercase letter, and instances of classes start with lowercase letters.

Flash CS4, Inactive buttons

I have no syntax errors when I run this code. I checked the variables and the functions in the action panel and it works fine. But, when I remove the codes from the action panel, and try to run the .as file nothing happens when I click the button.
Here's my code:
package
{
import flash.display.*;
import flash.events.MouseEvent;
import flash.text.*;
import flash.display.MovieClip;
public class U1A4_Sommeil extends MovieClip
{
private var monMessage:TextField = new TextField;
private var maMiseEnForme: TextFormat = new TextFormat;
public function U1A4_Sommeil ()
{
btnSoumettre.addEventListener(MouseEvent.CLICK,Calcule);
}
private function Calcule (event:MouseEvent):void
{
maMiseEnForme.font= "Arial";
maMiseEnForme.size = 20;
maMiseEnForme.color = 0xFF0000;
maMiseEnForme.bold = true;
monMessage.autoSize = TextFieldAutoSize.LEFT;
monMessage.defaultTextFormat = maMiseEnForme;
monMessage.x = 260;
monMessage.y = 260;
monMessage.border = true;
var intAn : int = int(txtAn.text) - int(txtAnNaissance.text);
var intMois : int = int(txtMois.text) - int(txtMoisNaissance.text);
var intJour : int = int(txtJour.text) - int(txtJourNaissance.text);
var strResultat : String = ("Tu es agé de "+ (intAn*365+intMois*30+intJour) + " jours."
+ "\n"
+ "Tu as dormi " + ((intAn*365 + intMois*30 + intJour)*8) + " heures"
+ "\n"
+ "depuis ta naissance.");
monMessage.text = strResultat;
addChild (monMessage);
}
}
}
I think that your have just to add your U1A4_Sommeil class as your document class using your document properties :
Or, from File Menu > ActionScript Settings... then :
Hope that can help.

Nape Physics ShapeDebug seems to be scaled

i have a strange problem with a simple nape demo... here's my code
package com.secretpackage {
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import nape.phys.Body;
import nape.shape.Circle;
import nape.space.Space;
import nape.util.ShapeDebug;
import nape.geom.Vec2;
import nape.phys.BodyType;
import nape.phys.Material;
public class Main extends Sprite {
// -------
private var world_db:Space=new Space(new Vec2(0,1000));
private var debug:ShapeDebug;
private var napeDebugSprite:Sprite = new Sprite();
private var sphere:Body;
private var labels:TextField;
// -------
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);
// entry point
debug = new ShapeDebug(stage.stageWidth, stage.stageHeight, stage.color);
labels = new TextField();
var posX:int = stage.stageWidth/4;
var posY:int = stage.stageHeight/4;
var r:int = 10;
sphere= new Body(BodyType.KINEMATIC, new Vec2(posX, posY));
sphere.shapes.add(new Circle(r, new Vec2(posX, posY), Material.rubber()));
sphere.space = world_db;
labels.x = 0;
labels.y = 0;
addChild(labels);
var tc:test_circle = new test_circle();
addChild(tc);
tc.x = stage.stageWidth / 2;
tc.y = stage.stageHeight / 2;
addChild(napeDebugSprite);
debug.drawConstraints=true;
napeDebugSprite.addChild(debug.display);
addEventListener(Event.ENTER_FRAME, update);
}
private function update(e:Event):void {
world_db.step(1/stage.frameRate, 10, 10);
debug.clear();
debug.draw(world_db);
debug.flush();
labels.text = sphere.position.x + " - " + sphere.position.y +
"\n" + stage.stageWidth + " - " + stage.stageHeight +
"\n" + napeDebugSprite.width + " - " + napeDebugSprite.height +
"\n" + debug.display.width + " - " + debug.display.height;
}
}
}
Plese note:
- sphere is a Circle with radius=10 placed at StageWidth/4 and StageHeight/4;
- test_circle is a Movieclip of a circle with radius=10 placed at StageWidth/2 and StageHeight/2;
When i compile this script i get ... http://i.imgur.com/MAYF3j9.png?1
The two circles are centered and sphere has a doubled radius.
Am i doing something wrong?
Thank you.
You set up the Body to have position (stageWidth/4, stageHeight/4), you then added a Circle shape, whose local offset is also (stageWidth/4, stageHeight/4), so when the body is un-rotated the circle will end up being at (stageWidth/2, stageHeight/2).
As to the graphical size difference, I can only assume that your graphic is not actually 'radius 10' but 'width/height 10' which is half the width/height of a radius 10 circle (whose width/height is 20)
A temporary solution is to scale debug:ShapeDebug, so code becomes...
....
addChild(napeDebugSprite);
debug.drawConstraints=true;
//Scaling
debug.display.scaleY = 0.5;
debug.display.scaleX = 0.5;
napeDebugSprite.addChild(debug.display);
....
This fixes the problem, but it is just a workaround.

Shaking effect - Flash CS6 ActionScript3.0

This question is related to ActionScript 3.0 and Flash CS6
I am trying to make an object shake a bit in a certain for some seconds. I made it a "movieclip" and made this code:
import flash.events.TimerEvent;
var Machine_mc:Array = new Array();
var fl_machineshaking:Timer = new Timer(1000, 10);
fl_machineshaking.addEventListener (TimerEvent.TIMER, fl_shakemachine);
fl_machineshaking.start ();
function fl_shakemachine (event:TimerEvent):void {
for (var i = 0; i < 20; i++) {
Machine.x += Math.random() * 6 - 4;
Machine.y += Math.random() * 6 - 4;
}
}
When testing the movie I get multiple errors looking exactly like this one:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Historieoppgave_fla::MainTimeline/fl_shakemachine()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
Also, the object doesnt shake, but it moves steadily upwards to the left a bit every tick.
To the point:
I wish to know how I stop the script after the object is not in the stage/scene anymore and also how to make it shake around, as I do not see what is wrong with my script, please help, thank you ^_^
AStupidNube brought up a great point about the original position. So adding that to shaking that should be a back and forth motion, so don't rely on random values that may or may not get you what you want. Shaking also has a dampening effect over time, so try something like this:
Link to working code
• http://wonderfl.net/c/eB1E - Event.ENTER_FRAME based
• http://wonderfl.net/c/hJJl - Timer Based
• http://wonderfl.net/c/chYC - Event.ENTER_FRAME based with extra randomness
**1 to 20 shaking items Timer Based code - see link above for ENTER_FRAME code••
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.text.TextField;
import flash.utils.Timer;
public class testing extends Sprite {
private var shakeButton:Sprite;
private var graphic:Sprite;
private var shakerPos:Array;
private var shakers:Array;
private var numShakers:int = 20;
private var dir:int = 1;
private var displacement:Number = 10;
private var shakeTimer:Timer;
public function testing() {
this.shakers = new Array();
this.shakerPos = new Array();
this.addEventListener(Event.ADDED_TO_STAGE, this.init);
}
private function init(e:Event):void {
this.stage.frameRate = 30;
this.shakeTimer = new Timer(33, 20);
this.shakeTimer.addEventListener(TimerEvent.TIMER, this.shake);
this.graphics.beginFill(0x333333);
this.graphics.drawRect(0,0,this.stage.stageWidth, this.stage.stageHeight);
this.graphics.endFill();
this.createShakers();
this.shakeButton = this.createSpriteButton("Shake ");
this.addChild(this.shakeButton);
this.shakeButton.x = 10;
this.shakeButton.y = 10;
this.shakeButton.addEventListener(MouseEvent.CLICK, this.shakeCallback);
}
private function createSpriteButton(btnName:String):Sprite {
var sBtn:Sprite = new Sprite();
sBtn.name = btnName;
sBtn.graphics.beginFill(0xFFFFFF);
sBtn.graphics.drawRoundRect(0,0,80,20,5);
var sBtnTF:TextField = new TextField();
sBtn.addChild(sBtnTF);
sBtnTF.text = btnName;
sBtnTF.x = 5;
sBtnTF.y = 3;
sBtnTF.selectable = false;
sBtn.alpha = .5;
sBtn.addEventListener(MouseEvent.MOUSE_OVER, function(e:Event):void { sBtn.alpha = 1 });
sBtn.addEventListener(MouseEvent.MOUSE_OUT, function(e:Event):void { sBtn.alpha = .5 });
return sBtn;
}
private function createShakers():void {
var graphic:Sprite;
for(var i:int = 0;i < this.numShakers;i++) {
graphic = new Sprite();
this.addChild(graphic);
graphic.graphics.beginFill(0xFFFFFF);
graphic.graphics.drawRect(0,0,10,10);
graphic.graphics.endFill();
// add a 30 pixel margin for the graphic
graphic.x = (this.stage.stageWidth-60)*Math.random()+30;
graphic.y = (this.stage.stageWidth-60)*Math.random()+30;
this.shakers[i] = graphic;
this.shakerPos[i] = new Point(graphic.x, graphic.y);
}
}
private function shakeCallback(e:Event):void {
this.shakeTimer.reset();
this.shakeTimer.start();
}
private function shake(e:TimerEvent):void {
this.dir *= -1;
var dampening:Number = (20 - e.target.currentCount)/20;
for(var i:int = 0;i < this.numShakers;i++) {
this.shakers[i].x = this.shakerPos[i].x + Math.random()*10*dir*dampening;
this.shakers[i].y = this.shakerPos[i].y + Math.random()*10*dir*dampening;
}
}
}
}
Now this is a linear dampening, you can adjust as you see fit by squaring or cubing the values.
You have to remember the original start position and calculate the shake effect from that point. This is my shake effect for MovieClips. It dynamically adds 3 variables (startPosition, shakeTime, maxShakeAmount) to it. If you use classes, you would add them to your clips.
import flash.display.MovieClip;
import flash.geom.Point;
function shake(mc:MovieClip, frames:int = 10, maxShakeAmount:int = 30) : void
{
if (!mc._shakeTime || mc._shakeTime <= 0)
{
mc.startPosition = new Point(mc.x, mc.y);
mc._shakeTime = frames;
mc._maxShakeAmount = maxShakeAmount;
mc.addEventListener(Event.ENTER_FRAME, handleShakeEnterFrame);
}
else
{
mc.startPosition = new Point(mc.x, mc.y);
mc._shakeTime += frames;
mc._maxShakeAmount = maxShakeAmount;
}
}
function handleShakeEnterFrame(event:Event):void
{
var mc:MovieClip = MovieClip(event.currentTarget);
var shakeAmount:Number = Math.min(mc._maxShakeAmount, mc._shakeTime);
mc.x = mc.startPosition.x + (-shakeAmount / 2 + Math.random() * shakeAmount);
mc.y = mc.startPosition.y + (-shakeAmount / 2 + Math.random() * shakeAmount);
mc._shakeTime--;
if (mc._shakeTime <= 0)
{
mc._shakeTime = 0;
mc.removeEventListener(Event.ENTER_FRAME, handleShakeEnterFrame);
}
}
You can use it like this:
// shake for 100 frames, with max distance of 15px
this.shake(myMc, 100, 15);
BTW: In Flash, you should enable 'permit debugging' in your 'publish settings' to have more detailed errors. This also gives back the line numbers where your code is breaking.
update:
Code now with time / maximum distance separated.
Here is a forked version of the chosen answer, but is a bit more flexible in that it allows you to set the frequency as well. It's also based on time as opposed to frames so you can think in terms of time(ms) as opposed to frames when setting the duration and interval.
The usage is similar to the chosen answer :
shake (clipToShake, durationInMilliseconds, frequencyInMilliseconds, maxShakeRange);
This is just an example of what I meant by using a TimerEvent as opposed to a ENTER_FRAME. It also doesn't require adding dynamic variables to the MovieClips you are shaking to track time, shakeAmount, and starting position.
public function shake(shakeClip:MovieClip, duration:Number = 3000, frequency:Number = 30, distance:Number = 30):void
{
var shakes:int = duration / frequency;
var shakeTimer:Timer = new Timer(frequency, shakes);
var startX:Number = shakeClip.x;
var startY:Number = shakeClip.y;
var shakeUpdate:Function = function(e:TimerEvent):void
{
shakeClip.x = startX + ( -distance / 2 + Math.random() * distance);
shakeClip.y = startY + ( -distance / 2 + Math.random() * distance);
}
var shakeComplete:Function = function(e:TimerEvent):void
{
shakeClip.x = startX;
shakeClip.y = startY;
e.target.removeEventListener(TimerEvent.TIMER, shakeUpdate);
e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, shakeComplete);
}
shakeTimer.addEventListener(TimerEvent.TIMER, shakeUpdate);
shakeTimer.addEventListener(TimerEvent.TIMER_COMPLETE, shakeComplete);
shakeTimer.start();
}
-4 <= Math.random() * 6 - 4 < 2
You add this offset to Machine.x 20 times, so chances for moving to the left is greater, than to the right.
It seems that you looking for something like this:
for each (var currentMachine:MovieClip in Machine_mc)
{
currentMachine.x += Math.random() * 6 - 3;
currentMachine.y += Math.random() * 6 - 3;
}

Getting from getCharBoundaries to BitMapData

I'm trying to convert all letters in a textfield to bitmap data. I then want to animate each of them. I'm able to return an array of rectangles using getCharBoundaries. But then how do I convert each letter to BitMapData?
package
{
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
public class LetterBitmapData extends Sprite
{
private var tf:TextField;
private var letterSprite:Sprite;
public function LetterBitmapData()
{
makeTF();
getRectangles();
};
private function makeTF():void
{
tf = new TextField();
tf.width = 400;
tf.height = 100;
tf.selectable = false;
tf.multiline = true;
tf.wordWrap = true;
tf.text = "Now is the winter of our discontent made glorious summer by this sun of York.";
tf.setTextFormat(new TextFormat("_sans", 16, 0));
addChild(tf);
}
private function getRectangles():Array
{
var result:Array = [];
var rectangle:Rectangle;
for (var i:int = 0; i < tf.text.length; i++)
{
rectangle = tf.getCharBoundaries(i);
result.push(rectangle); //create an array of CharBoundary rectangles
//trace("RECTANGLE x: " + rectangle.x + " y: " + rectangle.y + " width: " + rectangle.width + " height: " + rectangle.height );
}
return result;
}
}
}
You could animate your letters without turning them into Bitmaps as long as you're using embed fonts that is...
Instead of creating an array of rectangles, you could create an array of TextFields , associated to their specific rectangle in order to keep the coordinates of each letter. After that it should be possible to animate each TextField.