Multiple cubes - Papervision3D - papervision3d

I found an example of adding texture to a cube
What I want is to have 3 cubes in a row and also to be able to place them further at the back(x axis) but I really do not know much about papervision3d. I just changed the textures and that was it. Here is the code:
http://www.kelvinluck.com/assets/papervision3d/cube_tweaks/
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import org.papervision3d.cameras.Camera3D;
import org.papervision3d.materials.BitmapMaterial;
import org.papervision3d.materials.BitmapFileMaterial;
import org.papervision3d.materials.MaterialsList;
import org.papervision3d.objects.DisplayObject3D;
import org.papervision3d.scenes.Scene3D;
import org.papervision3d.objects.Collada;
import org.papervision3d.core.proto.DisplayObjectContainer3D;
import org.papervision3d.objects.Cube;
import org.papervision3d.materials.ColorMaterial;
public class PapervisionCubeSides extends Sprite
{
private var container:Sprite;
private var scene:Scene3D;
private var camera:Camera3D;
private var rootNode:DisplayObject3D;
private var ml:MaterialsList = new MaterialsList();
private var customcube:Cube;
public function PapervisionCubeSides()
{
init3D();
addEventListener(Event.ENTER_FRAME, Timeline);
}
private function init3D():void {
container = new Sprite();
addChild( container );
container.x = stage.stageWidth * .5;
container.y = stage.stageHeight * .5;
scene = new Scene3D( container );
camera = new Camera3D();
camera.zoom = 10;
rootNode = scene.addChild( new DisplayObject3D("rootNode") );
var ml:MaterialsList = new MaterialsList();
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face1');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face2');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face3');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face4');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face5');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face6');
customcube = new Cube( ml, 280, 280, 280, 1, 1, 1 );
rootNode.addChild( customcube, "myCube01" );
}
private function Timeline( event:Event ):void {
var screen:DisplayObject3D = this.scene.getChildByName("rootNode");
var rotationY:Number = -(this.mouseX / this.stage.stageWidth * 275);
var rotationX:Number = -(this.mouseY / this.stage.stageHeight * 275);
screen.rotationY += (rotationY - screen.rotationY) / 12;
screen.rotationX += (rotationX - screen.rotationX) / 12;
this.scene.renderCamera(this.camera);
}
}
}
thanks for the help

you would add 3 cubes the same way you add 1 cube to be honest. You can do a basic for loop and use the iterator to increment the position:
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import org.papervision3d.cameras.Camera3D;
import org.papervision3d.materials.BitmapMaterial;
import org.papervision3d.materials.BitmapFileMaterial;
import org.papervision3d.materials.MaterialsList;
import org.papervision3d.objects.DisplayObject3D;
import org.papervision3d.scenes.Scene3D;
import org.papervision3d.objects.Collada;
import org.papervision3d.core.proto.DisplayObjectContainer3D;
import org.papervision3d.objects.Cube;
import org.papervision3d.materials.ColorMaterial;
public class PapervisionCubeSides extends Sprite
{
private var container:Sprite;
private var scene:Scene3D;
private var camera:Camera3D;
private var rootNode:DisplayObject3D;
private var ml:MaterialsList = new MaterialsList();
private var customcube:Cube;
public function PapervisionCubeSides()
{
init3D();
addEventListener(Event.ENTER_FRAME, Timeline);
}
private function init3D():void {
container = new Sprite();
addChild( container );
container.x = stage.stageWidth * .5;
container.y = stage.stageHeight * .5;
scene = new Scene3D( container );
camera = new Camera3D();
camera.zoom = 10;
rootNode = scene.addChild( new DisplayObject3D("rootNode") );
var ml:MaterialsList = new MaterialsList();
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face1');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face2');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face3');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face4');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face5');
ml.addMaterial(new BitmapFileMaterial("ski.jpg"), 'face6');
for(var i:int = 0 ; i < 3 ; i++){
customcube = new Cube( ml, 280, 280, 280, 1, 1, 1 );
customcube.x = (280 + 10) * i
rootNode.addChild( customcube, "myCube"+i );
}
}
private function Timeline( event:Event ):void {
var screen:DisplayObject3D = this.scene.getChildByName("rootNode");
var rotationY:Number = -(this.mouseX / this.stage.stageWidth * 275);
var rotationX:Number = -(this.mouseY / this.stage.stageHeight * 275);
screen.rotationY += (rotationY - screen.rotationY) / 12;
screen.rotationX += (rotationX - screen.rotationX) / 12;
this.scene.renderCamera(this.camera);
}
}
}

Related

create custom IfcPolygonalFaceSet wall using xbim library

I want to create polygonfaceset wall using xbim toolkit library. Please let me know what I am doing wrong. It will be great help to me if anybody can provide sample code or some approach regarding polygonfaceset wall.
Below I provide scrennshot and samplecode.
static private IfcWallStandardCase CreateWall(IfcStore model, double length, double width, double height)
{
//
//begin a transaction
using (var txn = model.BeginTransaction("Create Wall"))
{
var wall = model.Instances.New();
wall.Name = "A Standard rectangular wall";
//represent wall as a rectangular profile
var rectProf = model.Instances.New<IfcRectangleProfileDef>();
rectProf.ProfileType = IfcProfileTypeEnum.AREA;
rectProf.XDim = width;
rectProf.YDim = length;
var insertPoint = model.Instances.New<IfcCartesianPoint>();
insertPoint.SetXY(0, 400); //insert at arbitrary position
rectProf.Position = model.Instances.New<IfcAxis2Placement2D>();
rectProf.Position.Location = insertPoint;
var polyfaceset = model.Instances.New<IfcPolygonalFaceSet>();
var coordinates2 = model.Instances.New<IfcIndexedPolygonalFace>();
//var coordinates = model.Instances.New<IfcCartesianPointList3D>(pl => {
// pl.CoordList.GetAt(0).AddRange(new IfcLengthMeasure[] { 0, 0, 0 });
// pl.CoordList.GetAt(1).AddRange(new IfcLengthMeasure[] { 1, 0, 0 });
// pl.CoordList.GetAt(2).AddRange(new IfcLengthMeasure[] { 0, 1, 0 });
// pl.CoordList.GetAt(3).AddRange(new IfcLengthMeasure[] { 0, 0, 1 });
//});
polyfaceset.Closed = true;
polyfaceset.Coordinates = model.Instances.New<IfcCartesianPointList3D>(pl => {
pl.CoordList.GetAt(0).AddRange(new IfcLengthMeasure[] { 0, 0, 1000 });
pl.CoordList.GetAt(1).AddRange(new IfcLengthMeasure[] { 3000, 0, 1000 });
pl.CoordList.GetAt(2).AddRange(new IfcLengthMeasure[] { 3000, 2000, 10000 });
pl.CoordList.GetAt(3).AddRange(new IfcLengthMeasure[] { 1000, 3000, 1000 });
pl.CoordList.GetAt(4).AddRange(new IfcLengthMeasure[] { 0, 2000, 1000 });
});
//model as a swept area solid
var body = model.Instances.New<IfcExtrudedAreaSolid>();
body.Depth = height;
body.SweptArea = rectProf;
body.ExtrudedDirection = model.Instances.New<IfcDirection>();
body.ExtrudedDirection.SetXYZ(0, 0, 1);
//parameters to insert the geometry in the model
var origin = model.Instances.New<IfcCartesianPoint>();
origin.SetXYZ(0, 0, 0);
body.Position = model.Instances.New<IfcAxis2Placement3D>();
body.Position.Location = origin;
//Create a Definition shape to hold the geometry
var shape = model.Instances.New<IfcShapeRepresentation>();
var modelContext = model.Instances.OfType<IfcGeometricRepresentationContext>().FirstOrDefault();
shape.ContextOfItems = modelContext;
shape.RepresentationType = "SweptSolid";
shape.RepresentationIdentifier = "Body";
shape.Items.Add(body);
//create visual style
model.Instances.New<IfcStyledItem> (styleItem => {
styleItem.Item = body;
styleItem.Styles.Add(model.Instances.New<IfcSurfaceStyle>(style => {
style.Side = IfcSurfaceSide.BOTH;
style.Styles.Add(model.Instances.New<IfcSurfaceStyleRendering>(rendering => {
rendering.SurfaceColour = model.Instances.New<IfcColourRgb>(colour => {
colour.Name = "Orange";
colour.Red = 1.0;
colour.Green = 0.5;
colour.Blue = 0.0;
});
}));
}));
});
//Create a Product Definition and add the model geometry to the wall
var rep = model.Instances.New<IfcProductDefinitionShape>();
rep.Representations.Add(shape);
wall.Representation = rep;
//now place the wall into the model
var lp = model.Instances.New<IfcLocalPlacement>();
var ax3D = model.Instances.New<IfcAxis2Placement3D>();
ax3D.Location = origin;
ax3D.RefDirection = model.Instances.New<IfcDirection>();
ax3D.RefDirection.SetXYZ(0, 1, 0);
ax3D.Axis = model.Instances.New<IfcDirection>();
ax3D.Axis.SetXYZ(0, 0, 1);
lp.RelativePlacement = ax3D;
wall.ObjectPlacement = lp;
// Where Clause: The IfcWallStandard relies on the provision of an IfcMaterialLayerSetUsage
var ifcMaterialLayerSetUsage = model.Instances.New<IfcMaterialLayerSetUsage>();
var ifcMaterialLayerSet = model.Instances.New<IfcMaterialLayerSet>();
var ifcMaterialLayer = model.Instances.New<IfcMaterialLayer>();
ifcMaterialLayer.LayerThickness = 10;
ifcMaterialLayerSet.MaterialLayers.Add(ifcMaterialLayer);
ifcMaterialLayerSetUsage.ForLayerSet = ifcMaterialLayerSet;
ifcMaterialLayerSetUsage.LayerSetDirection = IfcLayerSetDirectionEnum.AXIS2;
ifcMaterialLayerSetUsage.DirectionSense = IfcDirectionSenseEnum.NEGATIVE;
ifcMaterialLayerSetUsage.OffsetFromReferenceLine = 150;
// Add material to wall
var material = model.Instances.New<IfcMaterial>();
material.Name = "some material";
var ifcRelAssociatesMaterial = model.Instances.New<IfcRelAssociatesMaterial>();
ifcRelAssociatesMaterial.RelatingMaterial = material;
ifcRelAssociatesMaterial.RelatedObjects.Add(wall);
ifcRelAssociatesMaterial.RelatingMaterial = ifcMaterialLayerSetUsage;
// IfcPresentationLayerAssignment is required for CAD presentation in IfcWall or IfcWallStandardCase
var ifcPresentationLayerAssignment = model.Instances.New<IfcPresentationLayerAssignment>();
ifcPresentationLayerAssignment.Name = "some ifcPresentationLayerAssignment";
ifcPresentationLayerAssignment.AssignedItems.Add(shape);
// linear segment as IfcPolyline with two points is required for IfcWall
var ifcPolyline = model.Instances.New<IfcPolyline>();
var startPoint = model.Instances.New<IfcCartesianPoint>();
var midpoint = model.Instances.New<IfcCartesianPoint>();
var midpoint2 = model.Instances.New<IfcCartesianPoint>();
startPoint.SetXYZ(3000, 0, 1000);
midpoint.SetXYZ(3000, 2000, 1000);
midpoint2.SetXYZ(1000, 3000, 1000);
var endPoint = model.Instances.New<IfcCartesianPoint>();
endPoint.SetXYZ(0, 2000, 1000);
ifcPolyline.Points.Add(startPoint);
ifcPolyline.Points.Add(midpoint);
ifcPolyline.Points.Add(midpoint2);
ifcPolyline.Points.Add(endPoint);
var shape2D = model.Instances.New<IfcShapeRepresentation>();
shape2D.ContextOfItems = modelContext;
shape2D.RepresentationIdentifier = "Axis";
shape2D.RepresentationType = "Curve2D";
shape2D.Items.Add(ifcPolyline);
rep.Representations.Add(shape2D);
txn.Commit();
return wall;
}
}
This CreateWall function create Ifc wall. Please go throw it above code.

chartjs how to apply after animation

trying to extend a chart, so that i can draw lines up to the data point, but this is happening before the default animation. it would look smoother if it applied after.
i have got most of it to work.. but how do i get this to apply after chart animation.
var originalLineDraw = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
draw: function () {
originalLineDraw.apply(this, arguments);
var chart = this.chart;
var ctx = chart.chart.ctx;
var index = chart.config.data.lineAtIndex;
if (index) {
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-1']
var points = this.chart.getDatasetMeta(this.index).data;
for (var i = 0; i < points.length; i++) {
// var point_x = points[i]._model.x;
var point_y = points[i]._model.y;
ctx.beginPath();
ctx.setLineDash([5, 5]);/*dashes are 5px and spaces are 3px*/
ctx.moveTo(xaxis.getPixelForValue(undefined, i), point_y);
ctx.strokeStyle = '#fff';
ctx.lineTo(xaxis.getPixelForValue(undefined, i), yaxis.bottom);
ctx.stroke();
}
}
}
});
Update...
altho the darw is incorrect it still is playing after animation
var verticalLinePlugin = {
renderVerticalLine: function (chartInstance) {
var chart = chartInstance;
var ctx = chart.chart.ctx;
var maxpoint = [];
//loop the datasets
for (var y = 0; y < chart.config.data.datasets.length; y++) {
var dataset = chart.config.data.datasets[y];
if (dataset.hidden)
continue;
var points = chart.getDatasetMeta(y).data;
for (var i = 0; i < points.length; i++) {
var point_y = points[i]._model.y;
if (point_y < 0)
continue;
var point = maxpoint[i];
if (point == undefined) {
maxpoint.push({ id: i, y: point_y });
} else {
if (point.y > point_y) {
point.y = point_y;
}
}
}
}
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-1']
chart.data.datasets.forEach(function (dataset, i) {
var ds = dataset;
var meta = chart.getDatasetMeta(i);
meta.data.forEach(function (element, index) {
var value = maxpoint[i];
ctx.beginPath();
ctx.setLineDash([5, 5]);
ctx.moveTo(xaxis.getPixelForValue(undefined, i), value.y);
ctx.strokeStyle = '#fff';
ctx.lineTo(xaxis.getPixelForValue(undefined, i), yaxis.bottom);
ctx.stroke();
});
});
},
afterRender: function (chart) {
this.renderVerticalLine(chart);
}
};
Chart.plugins.register(verticalLinePlugin);
I made some small changes (non-intuitive!), and the vertical lines now appear after the animation.
Get the x values from the metadata instead of the data.
Either:
var x_point = element._model.x;
or:
var position = element.tooltipPosition();
var x_point = position.x;
Wrap the drawing in if(!hidden){}, then the vertical lines will disapear and reappear with the data. (The ternary assignment fixes a clash if the data starts hidden)
Do you need the value=max[i]? If just drawing the line up to the points, can get the y_point the same as for x.
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-1'];
chart.data.datasets.forEach(function (dataset, i) {
var meta = chart.getDatasetMeta(i);
var hidden = (meta.hidden != undefined) ? meta.hidden : dataset.hidden
if(!hidden){
meta.data.forEach(function (element, index) {
//var value = maxpoint[i];
var x_point = element._model.x;
var y_point = element._model.y;
ctx.beginPath();
ctx.save();
ctx.setLineDash([5, 5])
ctx.strokeStyle = '#fff';
ctx.moveTo(x_point, y_point); // or value.y
ctx.lineTo(x_point, yaxis.bottom)
ctx.stroke();
ctx.restore();
});
}
});

Famous Engine Physics Collisions

I am building a site which requires a physics engine.
Having worked with a number of SPA apps i feel pretty confident with.
Unfortunately I am having trouble applying collision detection & walls to a physics simulation that famous has created.
You can see the editable example here.
https://staging.famous.org/examples/index.html?block=gravity3d&detail=false&header=false
What I would like to know is it possible to add collisions to the particles? I have tried this but it appears the collisions are not setup correctly. I was hoping someone has managed to do it successfully.
Thanks!
var FamousEngine = famous.core.FamousEngine;
var Camera = famous.components.Camera;
var DOMElement = famous.domRenderables.DOMElement;
var Gravity3D = famous.physics.Gravity3D;
var Gravity1D = famous.physics.Gravity1D;
var MountPoint = famous.components.MountPoint;
var PhysicsEngine = famous.physics.PhysicsEngine;
var Physics = famous.physics;
var Wall = famous.physics.Wall;
var Position = famous.components.Position;
var Size = famous.components.Size;
var Sphere = famous.physics.Sphere;
var Vec3 = famous.math.Vec3;
var Collision = famous.physics.Collision;
function Demo() {
this.scene = FamousEngine.createScene('#socialInteractive');
this.camera = new Camera(this.scene);
this.camera.setDepth(1000);
this.simulation = new PhysicsEngine();
this.items = [];
this.collision = new Collision();
var Wall = famous.physics.Wall;
var rightWall = new Wall({
direction: Wall.LEFT
}); // bodies coming from the left will collide with the wall
rightWall.setPosition(1000, 0, 0);
var ceiling = new Wall({
normal: [0, 1, 0],
distance: 300,
restitution: 0
});
var floor = new Wall({
normal: [0, -1, 0],
distance: 300,
restitution: 0
});
var left = new Wall({
normal: [1, 0, 0],
distance: 350,
restitution: 0
});
var right = new Wall({
normal: [-1, 0, 0],
distance: 350,
restitution: 0
});
var node = this.scene.addChild();
var position = new Position(node);
// this.simulation.attach([right, left, floor, ceiling])
// this.items.push([ceiling,position]);
for (var i = 0; i < 10; i++) {
var node = this.scene.addChild();
var size = new Size(node).setMode(1, 1);
var position = new Position(node);
if (i === 0) {
createLogo.call(this, node, size, position);
}
if (i !== 0) {
node.id = i;
createSatellites.call(this, node, size, position);
}
}
FamousEngine.requestUpdateOnNextTick(this);
console.log(this.collision)
for (var i = 0; i < this.collision.length; i++) {
this.simulation.attach(collision, balls, balls[i]);
}
this.simulation.addConstraint(this.collision);
}
Demo.prototype.onUpdate = function(time) {
this.simulation.update(time);
this.collision.update(time, 60);
if (this.items.length > 0) {
for (var i = 0; i < this.items.length; i++) {
var itemPosition = this.simulation.getTransform(this.items[i][0]).position;
this.items[i][1].set(itemPosition[0], itemPosition[1], 0);
}
}
FamousEngine.requestUpdateOnNextTick(this);
};
function createLogo(node, size, position) {
size.setAbsolute(50, 50);
var mp = new MountPoint(node).set(0.5, 0.5);
var el = new DOMElement(node, {
tagName: 'img',
attributes: {
src: './images/famous-logo.svg'
}
});
var sphere = new Sphere({
radius: 100,
mass: 10000,
restrictions: ['xy'],
position: new Vec3(window.innerWidth / 2, window.innerHeight / 2, 5)
});
this.gravity = new Gravity3D(sphere);
this.simulation.add(sphere, this.gravity);
this.items.push([sphere, position]);
}
function createSatellites(node, size, position, i) {
size.setAbsolute(20, 20);
var radius = 200;
var x = Math.floor(Math.random() * radius * 2) - radius;
var y = (Math.round(Math.random()) * 2 - 1) * Math.sqrt(radius * radius - x * x);
var color = 'rgb(' + Math.abs(x) + ',' + Math.abs(Math.round(y)) + ',' + (255 - node.id) + ')';
var el = new DOMElement(node, {
properties: {
'background-color': color,
'border-radius': '50%'
}
});
var satellite = new Sphere({
radius: 20,
mass: 5,
position: new Vec3(x + window.innerWidth / 2, y + window.innerHeight / 2, 0)
});
satellite.setVelocity(-y / Math.PI, -x / Math.PI / 2, y / 2);
this.gravity.addTarget(satellite);
this.simulation.add(satellite);
this.items.push([satellite, position]);
this.collision.addTarget(satellite);
}
// Boilerplate
FamousEngine.init();
// App Code
var demo = new Demo();
Thanks for your help Talves, I think i found a solution that works with physics Spring instead of gravity3d. This also has the 4 walls included which seems to work well.
var famous = famous;
var FamousEngine = famous.core.FamousEngine;
var Camera = famous.components.Camera;
var DOMElement = famous.domRenderables.DOMElement;
var Gravity3D = famous.physics.Gravity3D;
var MountPoint = famous.components.MountPoint;
var PhysicsEngine = famous.physics.PhysicsEngine;
var Position = famous.components.Position;
var Size = famous.components.Size;
var Wall = famous.physics.Wall;
var Sphere = famous.physics.Sphere;
var Vec3 = famous.math.Vec3;
var math = famous.math;
var physics = famous.physics;
var collision = famous.physics.Collision;
var gestures = famous.components.GestureHandler;
var Spring = famous.physics.Spring;
console.log(famous)
var anchor = new Vec3(window.innerWidth / 2, window.innerHeight / 2, 0);
//Create Walls
var rightWall = new Wall({
direction: Wall.LEFT
}).setPosition(window.innerWidth - 20, 0, 0);
var leftWall = new Wall({
direction: Wall.RIGHT
}).setPosition(window.innerWidth + 20, 0, 0);
var topWall = new Wall({
direction: Wall.DOWN
}).setPosition(0, 20, 0);
var bottomWall = new Wall({
direction: Wall.UP
}).setPosition(0, window.innerHeight - 20, 0);
function Demo() {
this.scene = FamousEngine.createScene('body');
this.camera = new Camera(this.scene);
this.camera.setDepth(1000);
this.collision = new collision([rightWall, leftWall, topWall, bottomWall]);
this.simulation = new PhysicsEngine();
this.simulation.setOrigin(0.5, 0.5);
this.simulation.addConstraint(this.collision);
this.items = [];
this.walls = [];
//Create Items
for (var i = 0; i < 30; i++) {
var node = this.scene.addChild();
node.setMountPoint(0.5, 0.5);
var size = new Size(node).setMode(1, 1);
var position = new Position(node);
if (i === 0) {
createLogo.call(this, node, size, position);
}
if (i !== 0) {
node.id = i;
createSatellites.call(this, node, size, position);
}
}
//Create Walls
var node = this.scene.addChild();
createWalls(node);
FamousEngine.requestUpdateOnNextTick(this);
Demo.prototype.onUpdate = function(time) {
this.simulation.update(time);
//Postition walls
var wallPosition = topWall.getPosition();
node.setPosition(wallPosition.x, wallPosition.y);
//Position elements
if (this.items.length > 0) {
for (var i = 0; i < this.items.length; i++) {
var itemPosition = this.simulation.getTransform(this.items[i][0]).position;
this.items[i][1].set(itemPosition[0], itemPosition[1], 0);
}
}
FamousEngine.requestUpdateOnNextTick(this);
};
}
function createWalls(wallNode) {
wallNode.setSizeMode('absolute', 'absolute', 'absolute').setAbsoluteSize(window.innerWidth, 10, 0);
var wallDOMElement = new DOMElement(wallNode, {
tagName: 'div'
}).setProperty('background-color', 'lightblue');
}
function createLogo(node, size, position) {
size.setAbsolute(50, 50);
var mp = new MountPoint(node).set(0.5, 0.5);
var el = new DOMElement(node, {
tagName: 'img',
attributes: {
src: './images/famous_logo.png'
}
});
var sphere = new Sphere({
radius: 100,
mass: 10000,
restrictions: ['xy'],
position: new Vec3(window.innerWidth / 2, window.innerHeight / 2, 5)
});
// this.gravity = new Gravity3D(sphere);
// this.simulation.add(sphere, this.gravity);
this.simulation.add(sphere);
this.items.push([sphere, position]);
}
function createSatellites(node, size, position, i) {
size.setAbsolute(50, 50);
var radius = 100;
var x = Math.floor(Math.random() * radius * 2) - radius;
var y = (Math.round(Math.random()) * 2 - 1) * Math.sqrt(radius * radius - x * x);
var color = 'rgb(' + Math.abs(x) + ',' + Math.abs(Math.round(y)) + ',' + (255 - node.id) + ')';
var el = new DOMElement(node, {
properties: {
'background-color': color,
'border-radius': '50%'
}
});
var satellite = new Sphere({
radius: 25,
mass: 10,
position: new Vec3(x + window.innerWidth / 2, y + window.innerHeight / 2, 0)
});
// Attach the box to the anchor with a `Spring` force
var spring = new Spring(null, satellite, {
stiffness: 95,
period: 0.6,
dampingRatio: 1.0,
anchor: anchor
});
//console.log(color);
// satellite.setVelocity(-y / Math.PI, -x / Math.PI / 2, y / 2);
satellite.setVelocity(0.5, 0.5, 0);
// this.gravity.addTarget(satellite);
this.simulation.add(satellite, spring);
this.items.push([satellite, position]);
this.collision.addTarget(satellite);
}
// Boilerplate
FamousEngine.init();
// App Code
var demo = new Demo();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Famous :: Seed Project</title>
<link rel="icon" href="favicon.ico?v=1" type="image/x-icon">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
body {
position: absolute;
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
-webkit-font-smoothing: antialiased;
-webkit-tap-highlight-color: transparent;
-webkit-perspective: 0;
perspective: none;
overflow: hidden;
}
</style>
</head>
<body>
<script src="http://code.famo.us/famous/0.6.2/famous.min.js"></script>
</body>
</html>

How to Load movie clip with a conditional dynamic text. IF...else

I have two dynamic texts, both of them are going to generate numbers. If one has a greater value then the other one, a movie clip must be loaded, else, another movie clip must be loaded.
It's also important to note that I need to choose exactly the place that this movie clip will be load.
I create this code, but it's not working.
btn01.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_27);
function fl_ClickToGoToAndStopAtFrame_27(event:MouseEvent):void
{
var texto.text;
function testGuess():void{
if (parseInt(texto.text) == 8)
var fl_MyInstance_3:greenlight = new greenlight();
addChild(fl_MyInstance_3);
}}}
stop();
// timer loading
var timer:Timer = new Timer(2500);
timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.start();
function onTimer(evt:TimerEvent):void {
//primeiro indicador parte
var loader:URLLoader = new URLLoader(new URLRequest("bdaily.txt"));
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void {
var loadedText:URLLoader = URLLoader(event.target);
bdaily.text = loadedText.data;
}
// segundo indicador.
var loader1:URLLoader = new URLLoader(new URLRequest("bmtd.txt"));
loader1.addEventListener(Event.COMPLETE, completeHandler1);
function completeHandler1(event:Event):void {
var loadedText1:URLLoader = URLLoader(event.target);
bmtd.text = loadedText1.data;
}
//terceiro indicador
var loader2:URLLoader = new URLLoader(new URLRequest("bwtd.txt"));
loader2.addEventListener(Event.COMPLETE, completeHandler2);
function completeHandler2(event:Event):void {
var loadedText2:URLLoader = URLLoader(event.target);
bwtd.text = loadedText2.data;
}
//terceiro indicador
var loader3:URLLoader = new URLLoader(new URLRequest("basketdtarget.txt"));
loader3.addEventListener(Event.COMPLETE, completeHandler3);
function completeHandler3(event:Event):void {
var loadedText3:URLLoader = URLLoader(event.target);
basketdtarget.text = loadedText3.data;
}
var loader4:URLLoader = new URLLoader(new URLRequest("basketwtdtarget.txt"));
loader4.addEventListener(Event.COMPLETE, completeHandler4);
function completeHandler4(event:Event):void {
var loadedText4:URLLoader = URLLoader(event.target);
basketwtdtarget.text = loadedText4.data;
}
var loader5:URLLoader = new URLLoader(new URLRequest("basketmtdtarget.txt"));
loader5.addEventListener(Event.COMPLETE, completeHandler5);
function completeHandler5(event:Event):void {
var loadedText5:URLLoader = URLLoader(event.target);
basketmtdtarget.text = loadedText5.data;
}
//condicionais para gerar movieclip condicional
var clp_index = parseInt(bdaily.text) >= parseInt(basketdtarget.text) ? 1 : 2
var new_clp = clp_index == 1 ? new clp_01() : new clp_02()
addChild(new_clp)
var clp_index2 = parseInt(bwtd.text) >= parseInt(basketwtdtarget.text) ? 1 : 2
var new_clp2 = clp_index2 == 1 ? new clp_03() : new clp_04()
addChild(new_clp2)
var clp_index3 = parseInt(bmtd.text) >= parseInt(basketmtdtarget.text) ? 1 : 2
var new_clp3 = clp_index3 == 1 ? new clp_05() : new clp_06()
addChild(new_clp3)
}
try this :
btn.addEventListener(MouseEvent.CLICK, btn_on_Press);
function btn_on_Press(e:MouseEvent):void {
var clp_index = parseInt(txt_01.text) > parseInt(txt_02.text) ? 1 : 2
var new_clp = clp_index == 1 ? new clp_01() : new clp_02()
// to set the new_clp position
new_clp.x = 250 // left position
new_clp.y = 50 // top position
addChild(new_clp)
}
Last Edit :
stop()
var new_clp, new_clp2, new_clp3
var timer:Timer = new Timer(3000)
timer.addEventListener(TimerEvent.TIMER, onTimer)
timer.start()
function onTimer(evt:TimerEvent):void {
var loader:URLLoader = new URLLoader(new URLRequest('bdaily.txt'))
loader.addEventListener(Event.COMPLETE, function(e:Event){
bdaily.text = loader.data
})
var loader1:URLLoader = new URLLoader(new URLRequest('bmtd.txt'))
loader1.addEventListener(Event.COMPLETE, function(e:Event){
bmtd.text = loader1.data
})
var loader2:URLLoader = new URLLoader(new URLRequest('bwtd.txt'))
loader2.addEventListener(Event.COMPLETE, function(e:Event){
bwtd.text = loader2.data
})
var loader3:URLLoader = new URLLoader(new URLRequest('basketdtarget.txt'))
loader3.addEventListener(Event.COMPLETE, function(e:Event){
basketdtarget.text = loader3.data
})
var loader4:URLLoader = new URLLoader(new URLRequest('basketwtdtarget.txt'))
loader4.addEventListener(Event.COMPLETE, function(e:Event){
basketwtdtarget.text = loader4.data
})
var loader5:URLLoader = new URLLoader(new URLRequest('basketmtdtarget.txt'))
loader5.addEventListener(Event.COMPLETE, function(e:Event){
basketmtdtarget.text = loader5.data
})
if(new_clp){
new_clp.parent.removeChild(new_clp)
new_clp = null
}
if(new_clp2){
new_clp2.parent.removeChild(new_clp2)
new_clp2 = null
}
if(new_clp3){
new_clp3.parent.removeChild(new_clp3)
new_clp3 = null
}
trace('new_clp : '+new_clp)
trace('new_clp2 : '+new_clp2)
trace('new_clp3 : '+new_clp3)
var clp_index = parseInt(bdaily.text) >= parseInt(basketdtarget.text) ? 1 : 2
new_clp = clp_index == 1 ? new clp_01() : new clp_02()
addChild(new_clp)
var clp_index2 = parseInt(bwtd.text) >= parseInt(basketwtdtarget.text) ? 1 : 2
new_clp2 = clp_index2 == 1 ? new clp_03() : new clp_04()
addChild(new_clp2)
var clp_index3 = parseInt(bmtd.text) >= parseInt(basketmtdtarget.text) ? 1 : 2
new_clp3 = clp_index3 == 1 ? new clp_05() : new clp_06()
addChild(new_clp3)
}
This is the simplest way, you can optimize it later.

Friction in famo.us?

If I have some bodies that are repulsed and also have a distance. Right now they bounce back and forth endlessly. Is there a way to add a resistance to the physics engine so that they may come to rest?
var context = Engine.createContext();
var contextSize = context.getSize();
var handler = new EventHandler();
var physicsEngine = new PhysicsEngine();
function addBall(color, i) {
var ball = new Surface ({
size: [50,50],
properties: {
backgroundColor: color,
borderRadius: '100px'
}
});
ball.state = new StateModifier({origin:[0.5,0.5]});
ball.particle = new Circle({radius:50, mass: 20 + i * 1});
return ball;
}
var leftWall = new Wall({normal : [1,0,0], distance : contextSize[0]/2.0, restitution : 0.7});
var rightWall = new Wall({normal : [-1,0,0], distance : contextSize[0]/2.0, restitution : 0.7});
var topWall = new Wall({normal : [0,1,0], distance : contextSize[1]/2.0, restitution : 0.7});
var bottomWall = new Wall({normal : [0,-1,0], distance : contextSize[1]/2.0, restitution : 0.7});
var walls = [leftWall,rightWall,bottomWall,topWall];
var bodies = [];
_.each(['yellow', 'blue','green', 'red', 'orange', 'purple','gray', 'black'],function(color, index) {
var body = addBall(color, index);
bodies.push(body);
});
_.each(bodies, function (body) {
physicsEngine.addBody(body.particle);
context.add(body.state).add(body);
});
var particles = _.map(bodies, function(body){
return body.particle;
});
_.each(particles, function(particle, index){
var r = new Repulsion({strength: 61});
var d = new Distance({length: 80, minLength: 0});
physicsEngine.attach(r, [particles[(index + 4) % 8]], particle);
physicsEngine.attach(r, [particle], particles[(index + 4) % 8]);
physicsEngine.attach(d, [particles[(index + 1) % 8]], particle);
if (index == 0) {
physicsEngine.attach(d, [particle], particles[7]);
} else {
physicsEngine.attach(d, [particle], particles[(index - 1) % 8]);
}
particle.setVelocity([0.004101*index,0.004101*index,0 ]);
});
_.each(walls, function(wall) {
physicsEngine.attach(wall);
});
Engine.on('prerender', function(){
_.each(bodies, function(body) {
body.state.setTransform(body.particle.getTransform());
});
});
I was looking for Drag!
var drag = new Drag({strength: 0.1})
physicsEngine.attach(drag, [particle]);