AS3: graphics API not working as expected - actionscript-3

I've been working on an AS3 project, but since I usually work in php/javascript, this language is new to me and I have come across a problem that I can't figure out how to solve. I thought i'd ask it here because it's probably super simple and i just missed something (really) basic.
Here's my code in my external AS3 file:
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.Shape;
import flash.display.Graphics;
public class lightstage_debug extends MovieClip {
//create drag functions for tools
public function dragMirror1(event:MouseEvent):void
{
if (stage.contains(mirror1))
{
mirror1.startDrag();
}
}
public function releaseMirror1(event:MouseEvent):void
{
if (stage.contains(mirror1))
{
mirror1.stopDrag();
}
}
/*********************************************************************************************
TODO: make mirror2, mirror3 etc drag function exist in code even when those mirrors don't exist
**********************************************************************************************/
public function reCheck(event:Event):void
{
//BEGIN LEVEL 1 RECHECK//
if (level.number == 1)
{
//check if mirror1 is touching line1
if (mirror1.hitTestObject(line1))
{
//redraw line 1 to stop at mirror1
/*************************************************************************************
TODO: MAKE LINE1 END **EXACTLY** WHERE MIRROR1 TOUCHES IT
**************************************************************************************/
line1.graphics.clear();
line1.graphics.lineStyle(2,0x000000,1);
line1.graphics.moveTo(0,200);
line1.graphics.lineTo((mirror1.x + (mirror1.width/2)),200);
//redraw line 2 to start at mirror1
line2.graphics.clear();
line2.graphics.lineStyle(2,0x000000,1);
line2.graphics.moveTo((mirror1.x + (mirror1.width/2)),200);
line2.graphics.lineTo(0,200);
lines.addChild(line2);
//show line2
//line2.visible = true;
//line2.alpha = 100;
trace('line didnt appear');
}
//run this if line1 is not touching mirror1
else
{
//redraw line 1 to reach the end of the stage
line1.graphics.clear();
line1.graphics.lineStyle(2,0x000000,1);
line1.graphics.moveTo(0,200);
line1.graphics.lineTo(550,200);
//hide line2
//line2.alpha = 0;
}
}
//END LEVEL 1 RECHECK//
}
}
}
Here is the code in my .FLA file:
//import libraries
import flash.display.Shape;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.Graphics;
//create variables
var globe1:MovieClip = new globe;
var mirror1:MovieClip = new mirror;
//create display containers
var lines:MovieClip = new MovieClip;
var mirrors:MovieClip = new MovieClip;
var concaves:MovieClip = new MovieClip;
var convexes:MovieClip = new MovieClip;
var globes:MovieClip = new MovieClip;
//create shapes for this level
var line1:Shape = new Shape;
var line2:Shape = new Shape;
//add display containers to the stage
addChild(lines);
addChild(mirrors);
addChild(concaves);
addChild(convexes);
addChild(globes);
//create level object to store level properties
var level:Object = new Object;
//create scene properties
level.mirrors = 1;
level.concaves = 0;
level.convexes = 0;
level.globes = 1;
level.number = 1;
//add all lines to the stage
lines.addChild(line1);
lines.addChild(line2);
//draw line1
line1.graphics.clear();
line1.graphics.lineStyle(2, 0x000000, 1);
line1.graphics.moveTo(0,200);
line1.graphics.lineTo(550, 200);
//4DEBUG: testing to see why line2 dosent appear
line2.graphics.clear();
//add mirrors
mirrors.addChild(mirror1);
//add concaves
//add convexes
//add globes
globes.addChild(globe1);
//position mirrors
mirror1.x = 340;
mirror1.y = 300;
//position globes
globe1.x = 125;
globe1.y = 50;
//create listeners
mirror1.addEventListener(MouseEvent.MOUSE_DOWN, dragMirror1);
mirror1.addEventListener(MouseEvent.MOUSE_UP, releaseMirror1);
stage.addEventListener(Event.ENTER_FRAME, reCheck);
My stage is empty and I only have one frame at the moment. The globe and mirror movieclips are in my library with the AS3 linkage names I used to create them in the code.
I'm trying to create something like described at http://raphaelhennessy.com/misc/Explanation.png (ignore everything below the text 'LightStage Explanation') - but my problem is that although i can get the initial line (line1) to 'shrink' and stop at the mirror when the mirror is placed on top of the line, line2 does not appear and start at the mirror, going upwards to the top of the stage like intended.
Thanks in advance,
-Raph

It looks like you want line2.graphics.lineTo(0,200); to be line2.graphics.lineTo((mirror1.x + (mirror1.width/2)), 0);. Right now you're just drawing the lines on top of each other, in opposite directions.

Related

Test collision between two movie clips in two different classes AS3

I need to test the collision between 2 movie clips, using air for android action script 3.
Its a collision between an object and several obstacles.
My structure is the following :
The base FLA file, is linked to Action Script file called baseCode.as.
In this AS file, i create the obsctacles, using the following code :
baseCode.as :
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.geom.Point;
import Mc_MC; // Not strictly needed
public class baseCode extends flash.display.MovieClip
{
//private static var SYMBOLS:Array = new Array(MySymbol1, MySymbol2);
public var t:int = 0;
public function baseCode()
{
// Create five symbols:
for (var i:int = 0; i < 5; i++) {
trace(i);
makeSymbol();
}
}
function randomRange(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
public function makeSymbol():void
{
trace("IT entered makeSymbol");
// Pick a random symbol from the array:
// var symType:Class = SYMBOLS[0];
//trace(SYMBOLS[Math.random() * SYMBOLS.length]);
// Construct the new symbol:
//var Positi : Number = new Number(Math.random);
var loc:Point = new Point(randomRange(100,stage.stage.height),0);
var loc2:Point = new Point(randomRange(110,stage.stage.height),0);
//var loc:Point = new Point(10*randomRange(15, stage.width),100*randomRange(10 , stage.width));
trace("this is the starting point" , loc);
var sym:Mc_MC = new Mc_MC(1 + Math.random() *10, loc);
if( t % 2 == 0 ){
var sym2:Mc_MC2 = new Mc_MC2(15 + Math.random() *10, loc);
// Listen for the object hitting the left edge:
//sym2.addEventListener(Event.COMPLETE, remakeObject);
this.addChild(sym2);
}
sym.addEventListener(Event.COMPLETE, remakeObject);
this.addChild(sym);
t ++;
}
public function remakeObject(e:Event):void
{
e.target.removeEventListener(Event.COMPLETE, remakeObject);
//e.removeChild(sym);
//e.parent.removeChild(this.child);
// removeChild(this);
// this.removeChild(sym);
// Replace the dead symbol:
makeSymbol();
}
}
}
Mc_MC and Mc_MC2 are two Action Script file in which the obstacles are called :
Mc_MC.as :
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.geom.*;
import flash.display.Screen;
import flash.system.Capabilities;
public class Mc_MC extends MovieClip
{
public var speed:Number; // Pixels moved per frame
var valuee:baseCode;
public function Mc_MC(speed:Number, startPosition:Point)
{
this.speed = speed;
this.addEventListener(Event.ENTER_FRAME, update);
this.x = startPosition.x;
this.y = startPosition.y;
}
public function update(speed:Number)
{
var screenWidth:Number = Capabilities.screenResolutionX;
var screenHeight:Number = Capabilities.screenResolutionY;
trace("this.y" , this.y);
trace("this is the stage height" , screenHeight);
trace("this.speed" , this.speed);
if (this.y >= screenHeight - 100) { // We're at the left edge
trace("Entered if");
trace("new Starting Pos" , this.y);
this.y = stage.height;
parent.removeChild(this);
this.removeEventListener(Event.ENTER_FRAME, update);
this.dispatchEvent(new Event(Event.COMPLETE));
}
else this.y += this.speed;
}
}
}
In the base FLA file, i create the main object that will collide with all the obstacles created using Mc_MC and Mc_MC2. I create it using the following code :
Home.fla
import flash.events.*
//import flash.events.EventDispatcher.addEventListener()
import flash.display.DisplayObject;
//import flash.events.MouseEvent;
import flashx.textLayout.events.UpdateCompleteEvent;
import flash.display.MovieClip;
var offsetX:Number;
var offsetY:Number;
//var draggedObject:DisplayObject;
var my_obj:OriginalObject = new OriginalObject();
//left.addEventListener(MouseEvent.MOUSE_MOVE, drag);
//The speed of the scroll movement.
var scrollSpeed:uint = 2;
//This adds two instances of the movie clip onto the stage.
var s1:ScrollBg = new ScrollBg();
var s2:ScrollBg = new ScrollBg();
left.addEventListener(MouseEvent.MOUSE_DOWN,mouseDown);
function mouseDown(e:MouseEvent):void {
stage.addEventListener(MouseEvent.MOUSE_UP,mouseUp); //listen for mouse up on the stage, in case the finger/mouse moved off of the button accidentally when they release.
addEventListener(Event.ENTER_FRAME,myButtonClick); //while the mouse is down, run the tick function once every frame as per the project frame rate
}
function mouseUp(e:MouseEvent):void {
removeEventListener(Event.ENTER_FRAME,myButtonClick); //stop running the tick function every frame now that the mouse is up
stage.removeEventListener(MouseEvent.MOUSE_UP,mouseUp); //remove the listener for mouse up
}
right.addEventListener(MouseEvent.MOUSE_DOWN,mouseDown2);
function mouseDown2(e:MouseEvent):void {
stage.addEventListener(MouseEvent.MOUSE_UP,mouseUp2); //listen for mouse up on the stage, in case the finger/mouse moved off of the button accidentally when they release.
addEventListener(Event.ENTER_FRAME,stopDragging); //while the mouse is down, run the tick function once every frame as per the project frame rate
}
function mouseUp2(e:MouseEvent):void {
removeEventListener(Event.ENTER_FRAME,stopDragging); //stop running the tick function every frame now that the mouse is up
stage.removeEventListener(MouseEvent.MOUSE_UP,mouseUp2); //remove the listener for mouse up
}
my_obj.x = stage.width / 2;
my_obj.y = stage.height - (stage.height / 3 );
stage.addChild(my_obj);
function myButtonClick(ev:Event):void
{
trace("UPPP");
if(my_obj.x > (my_obj.width*2)){
my_obj.x = my_obj.x - 10;
trace("In the limit");
}
else {
trace("out of bounds");
}
trace("myButton has been clicked.");
}
//// This function is called when the mouse button is released.
function stopDragging(ev2:Event):void
{
trace("Down");
if(my_obj.x <= right.x){
my_obj.x = my_obj.x + 10;
}
}
How can I test the collision of the moving Mc_MC / Mc_MC2 with my_obj considering that the come from different AS files?
I am new to AS, so any help would be appreciated!
If you want to be able to collision test objects from different classes / parentage, then you need to set up your project in a way that you can gain a reference to said objects.
From the looks of it, your two objects are actually in the same class already (as your main timeline code and document class code share the same scope, so what you declare in one should be available in the other).
The only thing you are missing, is a top-level reference to your obstacle/Mc_MC. As currently you assign it to a var that is scoped to the makeSymbol function (so you only have a reference to it inside that function).
Solution
In your document class (baseCode.as) , create a top-level var to hold a reference to that obstacle: (for reference, you have a top level var called t, put this line above or below that)
private var obstacle:Mc_MC;
later in your function that instantiates the new Mc_MC (makeSymbol), assign the instance to that top level var:
obstacle = new Mc_MC(1 + Math.random() *10, loc);
addChild(obstacle);
Now you can access that obstacle var anywhere else in the main timeline or document class.
if(my_obj.hitTest(obstacle)){
}
As an aside, if you have a document class, there is no point in having code on the first frame of your main timeline as that code would work the same in your document class (though it has to be contained in a function). Here is an example of where to move main timeline code:
public class Main extends MovieClip {
public function Main():void {
//listen for the added to stage event prior to do anything display oriented
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void {
//this is the best place to put the equivalent of timeline code (not including vars or functions, put those in the class root NOT nested here)
}
}

How to get symbols to revert back to starting position in AS3 flash

Hi im trying to create a very simple drag and drop game in flash and I the scene to just loop round itself so say, if ( user does this) then go back to the beginning of the scene. but when I try this the symbols that the user has moved stay to where they have moved them too rather than returning to the position they were in at the start of the scene.
Can anyone explain a way to get the symbols to return to where they were at the begining of the scene once the if statement has completed?
The following example will traverse the display list, storing symbols along with their initial positions in a Dictionary. When it's time to reset, just call the resetToOriginalPositions method, passing it the Dictionary that was created.
import flash.utils.Dictionary;
import flash.display.DisplayObject;
import flash.geom.Point;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.MovieClip;
var originalPositions:Dictionary;
if(!originalPositions)
{
originalPositions = collectPositions(this);
}
function collectPositions(container:DisplayObjectContainer):Dictionary
{
var positions:Dictionary = new Dictionary(true);
for(var i:int = 0; i < container.numChildren; i++)
{
var currentSymbol:DisplayObject = container.getChildAt(i);
positions[currentSymbol] = new Point(currentSymbol.x, currentSymbol.y);
// this will allow the symbols to be dragged/dropped
currentSymbol.addEventListener(MouseEvent.MOUSE_DOWN, clickHandler);
currentSymbol.addEventListener(MouseEvent.MOUSE_UP, clickHandler);
}
return positions;
}
function clickHandler(e:MouseEvent):void
{
var target:MovieClip = e.target as MovieClip;
if(e.type == MouseEvent.MOUSE_DOWN)
{
target.startDrag();
}
else
{
target.stopDrag();
}
}
function resetToOriginalPositions(positions:Dictionary):void
{
for(var currentSymbol:Object in positions)
{
var position:Point = positions[currentSymbol];
DisplayObject(currentSymbol).x = position.x;
DisplayObject(currentSymbol).y = position.y;
}
}
// this line should be called in your if statement that you already have set up
resetToOriginalPositions(originalPositions);
Marcela's answer may work for you, but just in case you would like something a little simpler...you can store the original positions on a dynamic property of each object. When the condition you require is met to go back to the original positions you can call a function that resets the current x and y positions to the original ones.
//place in frame 1
dragObject1.originalY = dragObject1.y;
dragObject1.originalX = dragObject1.x;
dragObject2.originalY = dragObject2.y;
dragObject2.originalX = dragObject2.x;
//...rest of object posisitions
function resetObjectPositions()
{
dragObject1.y = dragObject1.originalY;
dragObject1.x = dragObject1.originalX;
dragObject2.y = dragObject2.originalY;
dragObject2.x = dragObject2.originalX;
//...rest of object positions
}
//later in scene
if(condition)
{
resetObjectPositions();//make sure to run this code before going back to frame one in the scene to use the original values;
}

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.

PaperVision3D and Flash CS4

I need to develop a cube that contain 10 little cubes and manipulate everyone like an object..Somebody have any idea or some tutorial for do this on PaperVision3d and Flash CS4..Thanks Folks!!
I think what you actually want is Papervision3d as I know of nothing called "PaperViewer". If that is the case, please update your question.
This should give you an idea of how to start. It creates 10 cubes and stores them in an array. You can access them using boxes[index] to alter their scale, postion and rotation.
package
{
import flash.display.Sprite;
import flash.events.Event;
import org.papervision3d.cameras.Camera3D;
import org.papervision3d.materials.ColorMaterial;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.objects.primitives.Cube;
import org.papervision3d.view.BasicView;
public class Boxes3d extends Sprite
{
private static const NUM_BOXES:int = 10;
private var world:BasicView;
private var boxes:Array;
public function Boxes3d()
{
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
}
private function addedToStage(event:Event):void
{
// create the world and add it to the stage
world = new BasicView();
addChild(world);
// create a set of boxes
boxes = [];
var box:Cube;
var materials:MaterialsList;
for(var boxIndex:int = 0; boxIndex < NUM_BOXES; boxIndex++)
{
// create a material to cover the cube
materials = new MaterialsList({
all: new ColorMaterial(Math.random()*0xFFFFFF) });
// make a cube
box = new Cube(materials, 100, 100, 100);
// spread it out in space
box.x = Math.random()*500 - 250;
box.y = Math.random()*500 - 250;
box.z = Math.random()*500 - 250;
// add it to the scene
world.scene.addChild(box);
}
// get the world to render each frame
world.startRendering();
addEventListener(Event.ENTER_FRAME, positionCamera);
}
private function positionCamera(event:Event):void
{
var camera:Camera3D = world.cameraAsCamera3D;
camera.x = -(stage.width/2 - mouseX) * 2;
camera.y = (stage.height/2 - mouseY) * 2;
}
}
}

Box2D Walls - same code: the left one works, the right one doesn't

I'm making a simple Box2D game ( http://iwanttobeacircle.com ), where you start off as a triangle and bounce off bigger shapes to gain sides.
I'm having a bizarre bug with my walls... both are created from the same class, yet the left one works and the right doesn't. If I only add the right one, then it works, but for some reason adding them both seems to be causing a problem somewhere.
The WallSegment class is below:
package com.carmstrong.iwanttobeacircle {
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.display.Shape;
import Box2D.Collision.Shapes.*;
import Box2D.Dynamics.*;
import Box2D.Common.Math.b2Vec2;
import com.carmstrong.iwanttobeacircle.Config;
public class WallSegment extends Actor {
private var _shape:Sprite;
private var _shapeBody:b2Body;
private var _colour:uint = 0x666666;
private var prevEdge:int;
private var thisEdge:int;
private var side:Number;
private var name:String;
private var _pathWidth:int;
private var _parent:DisplayObjectContainer;
public function WallSegment(Width:int, Position:String, Parent:DisplayObjectContainer) {
name = "Wall";
_pathWidth = Width;
_parent = Parent;
if(Position == "left") {
side = 1;
prevEdge = (Config.WIDTH - Config.PREV_WIDTH)/2;
thisEdge = (Config.WIDTH-_pathWidth)/2;
} else {
side = -1;
prevEdge = Config.WIDTH-(Config.WIDTH - Config.PREV_WIDTH)/2;
thisEdge = Config.WIDTH-(Config.WIDTH-_pathWidth)/2;
}// check if its left or right wall
//Create the costume
drawShape();
drawBody();
super(_shapeBody, _shape);
}//DynamicWall
private function drawShape():void {
//Draw visual
_shape = new Sprite();
var left:Sprite = new Sprite();
left.graphics.beginFill(_colour, 0.5);
left.graphics.moveTo(prevEdge, Config.HEIGHT/2);
left.graphics.lineTo(prevEdge-Config.WIDTH*side, Config.HEIGHT/2);
left.graphics.lineTo(thisEdge-Config.WIDTH*side, -Config.HEIGHT/2);
left.graphics.lineTo(thisEdge, -Config.HEIGHT/2);
left.graphics.endFill();
_shape.addChild(left);
_parent.addChild(_shape);
}//drawShape
private function drawBody():void {
//Create the shape definition
var shapeDef:b2PolygonDef = new b2PolygonDef();
shapeDef.vertexCount = 4;
b2Vec2(shapeDef.vertices[0]).Set(prevEdge/Config.RATIO, Config.HEIGHT/2/Config.RATIO);
b2Vec2(shapeDef.vertices[1]).Set((prevEdge-Config.WIDTH*side)/Config.RATIO, Config.HEIGHT/2/Config.RATIO);
b2Vec2(shapeDef.vertices[2]).Set((thisEdge-Config.WIDTH*side)/Config.RATIO, -Config.HEIGHT/2/Config.RATIO);
b2Vec2(shapeDef.vertices[3]).Set(thisEdge/Config.RATIO, -Config.HEIGHT/2/Config.RATIO);
shapeDef.density = 0;
shapeDef.friction = 10;
shapeDef.restitution = 0.45;
//Create the body definition (specify location here)
var shapeBodyDef:b2BodyDef = new b2BodyDef();
shapeBodyDef.position.Set(0, -Config.HEIGHT*(Config.CURRENT_SEGMENT+1)/Config.RATIO);
//Create the body
_shapeBody = Config.world.CreateBody(shapeBodyDef);
//Create the shape
_shapeBody.CreateShape(shapeDef);
}//drawBody
}//class
}//package
To keep the level dynamic, the walls are drawn just ahead of the player object each time in the main class, using the following code:
private function addWall(Width:int) {
Config.CURRENT_SEGMENT++;
//addWalls
var leftWall:WallSegment = new WallSegment(Width, "left",camera);
var rightWall:WallSegment = new WallSegment(Width, "right",camera);
Config.PREV_WIDTH = Width;
}//addWall
I'm getting this error:
TypeError: Error #1010: A term is
undefined and has no properties. at
com.carmstrong.iwanttobeacircle::GameContactListener/Add()
at
Box2D.Dynamics.Contacts::b2CircleContact/Evaluate()
at
Box2D.Dynamics.Contacts::b2Contact/Update()
at
Box2D.Dynamics::b2ContactManager/Collide()
at Box2D.Dynamics::b2World/Step() at
com.carmstrong.iwanttobeacircle::IWantToBeACircle/everyFrame()
Which refers to the GameContactListener class, shown below (the add function is at the bottom):
package com.carmstrong.iwanttobeacircle {
import Box2D.Collision.b2ContactPoint;
import Box2D.Dynamics.b2ContactListener;
public class GameContactListener extends b2ContactListener {
public function GameContactListener() {
}//GameContactListener
override public function Add(point:b2ContactPoint):void {
if (point.shape1.GetBody().GetUserData() is ShapeActor && point.shape2.GetBody().GetUserData() is ShapeActor) {
//trace("Two shapes collided: Shape 1 has "+ point.shape1.GetBody().GetUserData().sides + " sides and Shape 2 has " + point.shape2.GetBody().GetUserData().sides + " sides");
if (point.shape1.GetBody().GetUserData().sides > point.shape2.GetBody().GetUserData().sides) {
//remove side from shape 1 and add side to shape 2
point.shape1.GetBody().GetUserData().sides--;
point.shape2.GetBody().GetUserData().sides++;
//point.shape2.GetBody().GetUserData().updateColour;
} else if (point.shape1.GetBody().GetUserData().sides < point.shape2.GetBody().GetUserData().sides) {
//remove side from shape 2 and add side to shape 1
point.shape1.GetBody().GetUserData().sides++;
point.shape2.GetBody().GetUserData().sides--;
//point.shape2.GetBody().GetUserData().updateColour;
}// add side to smaller shape and take away from larger shape
if(point.shape1.GetBody().GetUserData().name == "player" || point.shape2.GetBody().GetUserData().name == "player") {
if(point.shape1.GetBody().GetUserData().name == "player" && point.shape2.GetBody().GetUserData().sides <= point.shape1.GetBody().GetUserData().sides) {
Config.FULFILLMENT++;
Config.SOUNDS[3+Math.ceil(Math.random()*5)][1].play();
trace(Config.FULFILLMENT);
} else if (point.shape2.GetBody().GetUserData().name == "player" && point.shape1.GetBody().GetUserData().sides <= point.shape2.GetBody().GetUserData().sides) {
Config.FULFILLMENT++;
Config.SOUNDS[Math.ceil(Math.random()*5)][1].play();
trace(Config.FULFILLMENT);
} else {
Config.SOUNDS[Math.ceil(Math.random()*3)][1].play();
Config.FULFILLMENT = int(Config.FULFILLMENT - 5);
trace(Config.FULFILLMENT);
}//if other shape is less than or equal to player
}//if one of the shapes is player
}// if both collider objects are shapes
super.Add(point);
}// override Add
}//class
}//package
I would appreciate any thoughts or ideas. Also, this is my first go at Box2D so would appreciate any tips on how to make my code more efficient.
Thanks in advance
You're asking two questions here
Why is the left and right wall collision detection not working?
Why is there an error on the GameContactListener/Add() method?
It looks like they may have the same root problem. I'm seeing you're adding the wall segments as children of the "camera" (had to trace where this add was happening... you pass a reference of "camera" into the constructor of the object.)
i.e. var leftWall:WallSegment = new WallSegment(Width, "left",camera);
Within there, you add the leftWall as a child of that object. But I'm not sure what "camera" is... Is this part of your game world object?
Also, what are your trace statements for point.shape1 and point.shape2?
What 2 objects are colliding?