Search Results

Search found 86 results on 4 pages for 'mousey'.

Page 4/4 | < Previous Page | 1 2 3 4 

  • FloodFill Algorithm for Game of Go

    - by Jackson Borghi
    I'm having a hell of a time trying to figure out how to make captured stones disappear. I've read everywhere that I should use the FloodFill algorithm, but I havent had any luck with that so far. Any help would be amazing! Here is my code: package Go; import static java.lang.Math.; import static stdlib.StdDraw.; import java.awt.Color; public class Go2 { public static Color opposite(Color player) { if (player == WHITE) { return BLACK; } return WHITE; } public static void drawGame(Color[][] board) { Color[][][] unit = new Color[400][19][19]; for (int h = 0; h < 400; h++) { for (int x = 0; x < 19; x++) { for (int y = 0; y < 19; y++) { unit[h][x][y] = YELLOW; } } } setXscale(0, 19); setYscale(0, 19); clear(YELLOW); setPenColor(BLACK); line(0, 0, 0, 19); line(19, 19, 19, 0); line(0, 19, 19, 19); line(0, 0, 19, 0); for (double i = 0; i < 19; i++) { line(0.0, i, 19, i); line(i, 0.0, i, 19); } for (int x = 0; x < 19; x++) { for (int y = 0; y < 19; y++) { if (board[x][y] != YELLOW) { setPenColor(board[x][y]); filledCircle(x, y, 0.47); setPenColor(GRAY); circle(x, y, 0.47); } } } int h = 0; } public static void main(String[] args) { int px; int py; Color[][] temp = new Color[19][19]; Color[][] board = new Color[19][19]; Color player = WHITE; for (int i = 0; i < 19; i++) { for (int h = 0; h < 19; h++) { board[i][h] = YELLOW; temp[i][h] = YELLOW; } } while (true) { drawGame(board); while (!mousePressed()) { } px = (int) round(mouseX()); py = (int) round(mouseY()); board[px][py] = player; while (mousePressed()) { } floodFill(px, py, player, board, temp); System.out.print("XXXXX = "+ temp[px][py]); if (checkTemp(temp, board, px, py)) { for (int x = 0; x < 19; x++) { for (int y = 0; y < 19; y++) { if (temp[x][y] == GRAY) { board[x][y] = YELLOW; } } } } player = opposite(player); } } private static boolean checkTemp(Color[][] temp, Color[][] board, int x, int y) { if (x < 19 && x > -1 && y < 19 && y > -1) { if (temp[x + 1][y] == YELLOW || temp[x - 1][y] == YELLOW || temp[x][y - 1] == YELLOW || temp[x][y + 1] == YELLOW) { return false; } } if (x == 18) { if (temp[x - 1][y] == YELLOW || temp[x][y - 1] == YELLOW || temp[x][y + 1] == YELLOW) { return false; } } if (y == 18) { if (temp[x + 1][y] == YELLOW || temp[x - 1][y] == YELLOW || temp[x][y - 1] == YELLOW) { return false; } } if (y == 0) { if (temp[x + 1][y] == YELLOW || temp[x - 1][y] == YELLOW || temp[x][y + 1] == YELLOW) { return false; } } if (x == 0) { if (temp[x + 1][y] == YELLOW || temp[x][y - 1] == YELLOW || temp[x][y + 1] == YELLOW) { return false; } } else { if (x < 19) { if (temp[x + 1][y] == GRAY) { checkTemp(temp, board, x + 1, y); } } if (x >= 0) { if (temp[x - 1][y] == GRAY) { checkTemp(temp, board, x - 1, y); } } if (y < 19) { if (temp[x][y + 1] == GRAY) { checkTemp(temp, board, x, y + 1); } } if (y >= 0) { if (temp[x][y - 1] == GRAY) { checkTemp(temp, board, x, y - 1); } } } return true; } private static void floodFill(int x, int y, Color player, Color[][] board, Color[][] temp) { if (board[x][y] != player) { return; } else { temp[x][y] = GRAY; System.out.println("x = " + x + " y = " + y); if (x < 19) { floodFill(x + 1, y, player, board, temp); } if (x >= 0) { floodFill(x - 1, y, player, board, temp); } if (y < 19) { floodFill(x, y + 1, player, board, temp); } if (y >= 0) { floodFill(x, y - 1, player, board, temp); } } } }

    Read the article

  • Finding the closest object in proxmity to the mouse Coordinates

    - by Cam
    Hey there, i've been working on a problem for a while now, which involves targeting the closest movieClip in relation to the x y coords of the mouse, I've attached a nice little acompanying graphic. Each mc added to the stage has it's own sub-class (HotSpots) which uses Pythag to measure distance from mouse. At this stage i can determine the closest value from my Main class but can't figure out how to reference it back to the movieclip... hope this makes sense. Below are the two Classes. My Main Class which attachs the mcs, and monitors mouse movement and traces closest value package { import flash.display.*; import flash.text.*; import flash.events.*; public class Main extends MovieClip { var pos:Number = 50; var nodeArray:Array; public function Main(){ nodeArray = []; for(var i:int = 0; i < 4; i++) { var hotSpot_mc:HotSpots = new HotSpots; hotSpot_mc.x += pos; hotSpot_mc.y += pos; addChild(hotSpot_mc); nodeArray.push(hotSpot_mc); // set some pos pos += 70; } stage.addEventListener(MouseEvent.MOUSE_MOVE,updateProxmity) } public function updateProxmity(e:MouseEvent):void { var tempArray:Array = new Array(); for(var i:int = 0; i < 4; i++) { this['tf'+[i]].text = String(nodeArray[i].dist); tempArray.push(nodeArray[i].dist); } tempArray.sort(Array.NUMERIC); var minValue:int = tempArray[0]; trace(minValue) } } } My HotSpots Class package { import flash.display.MovieClip; import flash.events.Event; import flash.text.TextField; public class HotSpots extends MovieClip { public var XSide:Number; public var YSide:Number; public var dist:Number = 0; public function HotSpots() { addEventListener(Event.ENTER_FRAME, textUp); } public function textUp(event:Event):void { XSide = this.x - MovieClip(root).mouseX; YSide = this.y - MovieClip(root).mouseY; dist = Math.round((Math.sqrt(XSide*XSide + YSide*YSide))); } } } thanks in advance

    Read the article

  • Gamepad Control for Processing + Android to Control Arduino Robot

    - by Iker
    I would like to create a Multitouch Gamepad control for Processing and use it to control a remote Arduino Robot. I would like to make the GUI on Processing and compile it for Android. Here is the GUI Gamepad for Processing I have created so far: float easing = 0.09; // start position int posX = 50; int posY = 200; // target position int targetX = 50; int targetY = 200; boolean dragging = false; void setup() { size(500,250); smooth(); } void draw() { background(255); if (!dragging) { // calculate the difference in position, apply easing and add to vx/vy float vx = (targetX - (posX)) * easing; float vy = (targetY - (posY)) * easing; // Add the velocity to the current position: make it move! posX += vx; posY += vy; } if(mousePressed) { dragging = true; posX = mouseX; posY = mouseY; } else { dragging = false; } DrawGamepad(); DrawButtons(); } void DrawGamepad() { //fill(0,155,155); //rect(0, 150, 100, 100, 15); ellipseMode(RADIUS); // Set ellipseMode to RADIUS fill(0,155,155); // Set fill to blue ellipse(50, 200, 50, 50); // Draw white ellipse using RADIUS mode ellipseMode(CENTER); // Set ellipseMode to CENTER fill(255); // Set fill to white// ellipse(posX, posY, 35, 35); // Draw gray ellipse using CENTER mode } void DrawButtons() { fill(0,155,155); // Set fill to blue ellipse(425, 225, 35, 35); ellipse(475, 225, 35, 35); fill(255,0,0); // Set fill to blue ellipse(425, 175, 35, 35); ellipse(475, 175, 35, 35); } I have realized that probably that code will not support Multitouch events on Android so I came up with another code found on this link Can Processing handle multi-touch? So the aim of this project is to create de multitouch gamepad to use to control my Arduino Robot. The gamepad should detect which key was pressed as well as the direction of the Joystick. Any help appreciated.

    Read the article

  • backbone.js - Having multiple instances of the same view

    - by TrueWheel
    I am having problems having multiple instances in of the same view in different div elements. When I try to initialize them only the second of the two elements appear no matter what order I put them in. Here is the code for my view. var BodyShapeView = Backbone.View.extend({ thingiview: null, scene: null, renderer: null, model: null, mouseX: 0, mouseY: 0, events:{ 'click button#front' : 'front', 'click button#diag' : 'diag', 'click button#in' : 'zoomIn', 'click button#out' : 'zoomOut', 'click button#on' : 'rotateOn', 'click button#off' : 'rotateOff', 'click button#wireframeOn' : 'wireOn', 'click button#wireframeOff' : 'wireOff', 'click button#distance' : 'dijkstra' }, initialize: function(name){ _.bindAll(this, 'render', 'animate'); scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 15, 400 / 700, 1, 4000 ); camera.position.z = 3; scene.add( camera ); camera.position.y = -5; var ambient = new THREE.AmbientLight( 0x202020 ); scene.add( ambient ); var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.75 ); directionalLight.position.set( 0, 0, 1 ); scene.add( directionalLight ); var pointLight = new THREE.PointLight( 0xffffff, 5, 29 ); pointLight.position.set( 0, -25, 10 ); scene.add( pointLight ); var loader = new THREE.OBJLoader(); loader.load( "img/originalMeanModel.obj", function ( object ) { object.children[0].geometry.computeFaceNormals(); var geometry = object.children[0].geometry; console.log(geometry); THREE.GeometryUtils.center(geometry); geometry.dynamic = true; var material = new THREE.MeshLambertMaterial({color: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors }); mesh = new THREE.Mesh(geometry, material); model = mesh; // model = object; scene.add( model ); } ); // RENDERER renderer = new THREE.WebGLRenderer(); renderer.setSize( 400, 700 ); $(this.el).find('.obj').append( renderer.domElement ); this.animate(); }, Here is how I create the instances var morphableBody = new BodyShapeView({ el: $("#morphable-body") }); var bodyShapeView = new BodyShapeView({ el: $("#mean-body") }); Any help would be really appreciated. Thanks in advance.

    Read the article

  • How can I scale movement physics functions to frames per second (in a game engine)?

    - by Richard
    I am working on a game in Javascript (HTML5 Canvas). I implemented a simple algorithm that allows an object to follow another object with basic physics mixed in (a force vector to drive the object in the right direction, and the velocity stacks momentum, but is slowed by a constant drag force). At the moment, I set it up as a rectangle following the mouse (x, y) coordinates. Here's the code: // rectangle x, y position var x = 400; // starting x position var y = 250; // starting y position var FPS = 60; // frames per second of the screen // physics variables: var velX = 0; // initial velocity at 0 (not moving) var velY = 0; // not moving var drag = 0.92; // drag force reduces velocity by 8% per frame var force = 0.35; // overall force applied to move the rectangle var angle = 0; // angle in which to move // called every frame (at 60 frames per second): function update(){ // calculate distance between mouse and rectangle var dx = mouseX - x; var dy = mouseY - y; // calculate angle between mouse and rectangle var angle = Math.atan(dy/dx); if(dx < 0) angle += Math.PI; else if(dy < 0) angle += 2*Math.PI; // calculate the force (on or off, depending on user input) var curForce; if(keys[32]) // SPACE bar curForce = force; // if pressed, use 0.35 as force else curForce = 0; // otherwise, force is 0 // increment velocty by the force, and scaled by drag for x and y velX += curForce * Math.cos(angle); velX *= drag; velY += curForce * Math.sin(angle); velY *= drag; // update x and y by their velocities x += velX; y += velY; And that works fine at 60 frames per second. Now, the tricky part: my question is, if I change this to a different framerate (say, 30 FPS), how can I modify the force and drag values to keep the movement constant? That is, right now my rectangle (whose position is dictated by the x and y variables) moves at a maximum speed of about 4 pixels per second, and accelerates to its max speed in about 1 second. BUT, if I change the framerate, it moves slower (e.g. 30 FPS accelerates to only 2 pixels per frame). So, how can I create an equation that takes FPS (frames per second) as input, and spits out correct "drag" and "force" values that will behave the same way in real time? I know it's a heavy question, but perhaps somebody with game design experience, or knowledge of programming physics can help. Thank you for your efforts. jsFiddle: http://jsfiddle.net/BadDB

    Read the article

  • Routes on a sphere surface - Find geodesic?

    - by CaNNaDaRk
    I'm working with some friends on a browser based game where people can move on a 2D map. It's been almost 7 years and still people play this game so we are thinking of a way to give them something new. Since then the game map was a limited plane and people could move from (0, 0) to (MAX_X, MAX_Y) in quantized X and Y increments (just imagine it as a big chessboard). We believe it's time to give it another dimension so, just a couple of weeks ago, we began to wonder how the game could look with other mappings: Unlimited plane with continous movement: this could be a step forward but still i'm not convinced. Toroidal World (continous or quantized movement): sincerely I worked with torus before but this time I want something more... Spherical world with continous movement: this would be great! What we want Users browsers are given a list of coordinates like (latitude, longitude) for each object on the spherical surface map; browsers must then show this in user's screen rendering them inside a web element (canvas maybe? this is not a problem). When people click on the plane we convert the (mouseX, mouseY) to (lat, lng) and send it to the server which has to compute a route between current user's position to the clicked point. What we have We began writing a Java library with many useful maths to work with Rotation Matrices, Quaternions, Euler Angles, Translations, etc. We put it all together and created a program that generates sphere points, renders them and show them to the user inside a JPanel. We managed to catch clicks and translate them to spherical coords and to provide some other useful features like view rotation, scale, translation etc. What we have now is like a little (very little indeed) engine that simulates client and server interaction. Client side shows points on the screen and catches other interactions, server side renders the view and does other calculus like interpolating the route between current position and clicked point. Where is the problem? Obviously we want to have the shortest path to interpolate between the two route points. We use quaternions to interpolate between two points on the surface of the sphere and this seemed to work fine until i noticed that we weren't getting the shortest path on the sphere surface: We though the problem was that the route is calculated as the sum of two rotations about X and Y axis. So we changed the way we calculate the destination quaternion: We get the third angle (the first is latitude, the second is longitude, the third is the rotation about the vector which points toward our current position) which we called orientation. Now that we have the "orientation" angle we rotate Z axis and then use the result vector as the rotation axis for the destination quaternion (you can see the rotation axis in grey): What we got is the correct route (you can see it lays on a great circle), but we get to this ONLY if the starting route point is at latitude, longitude (0, 0) which means the starting vector is (sphereRadius, 0, 0). With the previous version (image 1) we don't get a good result even when startin point is 0, 0, so i think we're moving towards a solution, but the procedure we follow to get this route is a little "strange" maybe? In the following image you get a view of the problem we get when starting point is not (0, 0), as you can see starting point is not the (sphereRadius, 0, 0) vector, and as you can see the destination point (which is correctly drawn!) is not on the route. The magenta point (the one which lays on the route) is the route's ending point rotated about the center of the sphere of (-startLatitude, 0, -startLongitude). This means that if i calculate a rotation matrix and apply it to every point on the route maybe i'll get the real route, but I start to think that there's a better way to do this. Maybe I should try to get the plane through the center of the sphere and the route points, intersect it with the sphere and get the geodesic? But how? Sorry for being way too verbose and maybe for incorrect English but this thing is blowing my mind! EDIT: This code version is related to the first image: public void setRouteStart(double lat, double lng) { EulerAngles tmp = new EulerAngles ( Math.toRadians(lat), 0, -Math.toRadians(lng)); //set route start Quaternion qtStart.setInertialToObject(tmp); //do other stuff like drawing start point... } public void impostaDestinazione(double lat, double lng) { EulerAngles tmp = new AngoliEulero( Math.toRadians(lat), 0, -Math.toRadians(lng)); qtEnd.setInertialToObject(tmp); //do other stuff like drawing dest point... } public V3D interpolate(double totalTime, double t) { double _t = t/totalTime; Quaternion q = Quaternion.Slerp(qtStart, qtEnd, _t); RotationMatrix.inertialQuatToIObject(q); V3D p = matInt.inertialToObject(V3D.Xaxis.scale(sphereRadius)); //other stuff, like drawing point ... return p; } //mostly taken from a book! public static Quaternion Slerp(Quaternion q0, Quaternion q1, double t) { double cosO = q0.dot(q1); double q1w = q1.w; double q1x = q1.x; double q1y = q1.y; double q1z = q1.z; if (cosO < 0.0f) { q1w = -q1w; q1x = -q1x; q1y = -q1y; q1z = -q1z; cosO = -cosO; } double sinO = Math.sqrt(1.0f - cosO*cosO); double O = Math.atan2(sinO, cosO); double oneOverSinO = 1.0f / senoOmega; k0 = Math.sin((1.0f - t) * O) * oneOverSinO; k1 = Math.sin(t * O) * oneOverSinO; // Interpolate return new Quaternion( k0*q0.w + k1*q1w, k0*q0.x + k1*q1x, k0*q0.y + k1*q1y, k0*q0.z + k1*q1z ); } A little dump of what i get (again check image 1): Route info: Sphere radius and center: 200,000, (0.0, 0.0, 0.0) Route start: lat 0,000 °, lng 0,000 ° @v: (200,000, 0,000, 0,000), |v| = 200,000 Route end: lat 30,000 °, lng 30,000 ° @v: (150,000, 86,603, 100,000), |v| = 200,000 Qt dump: (w, x, y, z), rot. angle°, (x, y, z) rot. axis Qt start: (1,000, 0,000, -0,000, 0,000); 0,000 °; (1,000, 0,000, 0,000) Qt end: (0,933, 0,067, -0,250, 0,250); 42,181 °; (0,186, -0,695, 0,695) Route start: lat 30,000 °, lng 10,000 ° @v: (170,574, 30,077, 100,000), |v| = 200,000 Route end: lat 80,000 °, lng -50,000 ° @v: (22,324, -26,604, 196,962), |v| = 200,000 Qt dump: (w, x, y, z), rot. angle°, (x, y, z) rot. axis Qt start: (0,962, 0,023, -0,258, 0,084); 31,586 °; (0,083, -0,947, 0,309) Qt end: (0,694, -0,272, -0,583, -0,324); 92,062 °; (-0,377, -0,809, -0,450)

    Read the article

  • Make a lives display in HUD, Flash AS3 (not text!)

    - by user40404
    I've been searching the internet all day and I can't find the answer I'm looking for. In my HUD I want to use orange dots to represent lives. The user starts off with 5 lives and every time they die, I want a dot to be removed. Pretty straight forward. So far my idea is to make a movie clip that has the five dots in a line. There would be 5 frames on the timeline (because after the last life it goes to a game over screen right away). I would have a variable set up to store the number of lives and a function to keep track of lives. So every hit of an obstacle would result in livesCounter--;. Then I would set up something like this: switch(livesCounter){ case 5: livesDisplay.gotoAndPlay(1); break; case 4: livesDisplay.gotoAndPlay(2); break; case 3: livesDisplay.gotoAndPlay(3); break; case 2: livesDisplay.gotoAndPlay(4); break; case 1: livesDisplay.gotoAndPlay(5); break; } I feel like there has to be an easier way to do this where I could just have a movie clip of a single orange dot that I could replicate across an x value based on the number of lives. Maybe the dots would be stored in an array? When the user loses a life, a dot on the right end of the line is removed. So in the end the counter would look like this: * * * * * * * * * * * * * * * (last life lost results in the end game screen) EDIT: code based on suggestions by Zhafur and Arthur Wolf White package { import flash.display.MovieClip; import flash.events.*; import flash.ui.Multitouch; import flash.ui.MultitouchInputMode; import flash.display.Sprite; import flash.text.*; import flash.utils.getTimer; public class CollisionMouse extends MovieClip{ public var mySprite:Sprite = new Sprite(); Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; public var replacement:newSprite = new newSprite; public var score:int = 0; public var obstScore:int = -50; public var targetScore:int = 200; public var startTime:uint = 0; public var gameTime:uint; public var pauseScreen:PauseScreen = new PauseScreen(); public var hitTarget:Boolean = false; public var hitObj:Boolean = false; public var currLevel:Number = 1; public var heroLives:int = 5; public var life:Sprite; public function CollisionMouse() { mySprite.graphics.beginFill(0xff0000); mySprite.graphics.drawRect(0,0,40,40); addChild(mySprite); mySprite.x = 200; mySprite.y = 200; pauseScreen.x = stage.width/2; pauseScreen.y = stage.height/2; life = new Sprite(); life.x = 210; stage.addEventListener(MouseEvent.MOUSE_MOVE,followMouse); /*mySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd);*/ //checkLevel(); timeCheck(); trackLives(); } public function timeCheck(){ addEventListener(Event.ENTER_FRAME, showTime); } public function showTime(e:Event) { gameTime = getTimer()-startTime; rm1_mc.timeDisplay.text = clockTime(gameTime); rm1_mc.livesDisplay.text = String(heroLives); } public function clockTime(ms:int) { var seconds:int = Math.floor(ms/1000); var minutes:int = Math.floor(seconds/60); seconds -= minutes*60; var timeString:String = minutes+":"+String(seconds+100).substr(1,2); return timeString; } public function trackLives(){ for(var i:int=0; i<heroLives; i++){ life.graphics.lineStyle(1, 0xff9900); life.graphics.beginFill(0xff9900, 1); life.graphics.drawCircle(i*15, 45, 6); life.graphics.endFill(); addChild(life); } } function followMouse(e:MouseEvent){ mySprite.x=mouseX; mySprite.y=mouseY; trackCollisions(); } function trackCollisions(){ if(mySprite.hitTestObject(rm1_mc.obst1) || mySprite.hitTestObject(rm1_mc.obst2)){ hitObjects(); } else if(mySprite.hitTestObject(rm1_mc.target_mc)){ hitTarg(); } } function hitObjects(){ addChild(replacement); mySprite.x ^= replacement.x; replacement.x ^= mySprite.x; mySprite.x ^= replacement.x; mySprite.y ^= replacement.y; replacement.y ^= mySprite.y; mySprite.y ^= replacement.y; stage.removeEventListener(MouseEvent.MOUSE_MOVE, followMouse); removeChild(mySprite); hitObj = true; checkScore(); } function hitTarg(){ addChild(replacement); mySprite.x ^= replacement.x; replacement.x ^= mySprite.x; mySprite.x ^= replacement.x; mySprite.y ^= replacement.y; replacement.y ^= mySprite.y; mySprite.y ^= replacement.y; stage.removeEventListener(MouseEvent.MOUSE_MOVE, followMouse); removeEventListener(Event.ENTER_FRAME, showTime); removeChild(mySprite); hitTarget = true; currLevel++; checkScore(); } function checkScore(){ if(hitObj){ score += obstScore; heroLives--; removeChild(life); } else if(hitTarget){ score += targetScore; } rm1_mc.scoreDisplay.text = String(score); rm1_mc.livesDisplay.text = String(heroLives); trackLives(); } } }

    Read the article

  • flash core engine by Dinesh [closed]

    - by hdinesh
    This post was a dump of the following code (without the highlights). No question, just a dump. Please update this q. with a real question to have it reopened. You (the asker) risk to be flagged as spammer (if not already) and a bad reputation. This is a q/a site, not a site to promote your own code libraries. package facers { import flash.display.*; import flash.events.*; import flash.geom.ColorTransform; import flash.utils.Dictionary; import org.papervision3d.cameras.*; import org.papervision3d.scenes.*; import org.papervision3d.objects.*; import org.papervision3d.objects.special.*; import org.papervision3d.objects.primitives.*; import org.papervision3d.materials.*; import org.papervision3d.events.FileLoadEvent; import org.papervision3d.materials.special.*; import org.papervision3d.materials.shaders.*; import org.papervision3d.materials.utils.*; import org.papervision3d.lights.*; import org.papervision3d.render.*; import org.papervision3d.view.*; import org.papervision3d.events.InteractiveScene3DEvent; import org.papervision3d.events.*; import org.papervision3d.core.utils.*; import org.papervision3d.core.geom.renderables.Vertex3D; import caurina.transitions.*; public class Main extends Sprite { public var viewport :BasicView; public var displayObject :DisplayObject3D; private var light :PointLight3D; private var shadowPlane :Plane; private var dataArray :Array; private var material :BitmapFileMaterial; private var planeByContainer :Dictionary = new Dictionary(); private var paperSize :Number = 0.5; private var cloudSize :Number = 1500; private var rotSize :Number = 360; private var maxAlbums :Number = 50; private var num :Number = 0; public function Main():void { trace("START APPLICATION"); viewport = new BasicView(1024, 690, true, true, CameraType.FREE); viewport.camera.zoom = 50; viewport.camera.extra = { goPosition: new DisplayObject3D(),goTarget: new DisplayObject3D() }; addChild(viewport); displayObject = new DisplayObject3D(); viewport.scene.addChild(displayObject); createAlbum(); addEventListener(Event.ENTER_FRAME, onRenderEvent); } private function createAlbum() { dataArray = new Array("images/thums/pic1.jpg", "images/thums/pic2.jpg", "images/thums/pic3.jpg", "images/thums/pic4.jpg", "images/thums/pic5.jpg", "images/thums/pic6.jpg", "images/thums/pic7.jpg", "images/thums/pic8.jpg", "images/thums/pic9.jpg", "images/thums/pic10.jpg", "images/thums/pic1.jpg", "images/thums/pic2.jpg", "images/thums/pic3.jpg", "images/thums/pic4.jpg", "images/thums/pic5.jpg", "images/thums/pic6.jpg", "images/thums/pic7.jpg", "images/thums/pic8.jpg", "images/thums/pic9.jpg", "images/thums/pic10.jpg"); for (var i:int = 0; i < dataArray.length; i++) { material = new BitmapFileMaterial(dataArray[i]); material.doubleSided = true; material.addEventListener(FileLoadEvent.LOAD_COMPLETE, loadMaterial); } } public function loadMaterial(event:Event) { var plane:Plane = new Plane(material, 300, 180); displayObject.addChild(plane); var _x:int = Math.random() * cloudSize - cloudSize/2; var _y:int = Math.random() * cloudSize - cloudSize/2; var _z:int = Math.random() * cloudSize - cloudSize/2; var _rotationX:int = Math.random() * rotSize; var _rotationY:int = Math.random() * rotSize; var _rotationZ:int = Math.random() * rotSize; Tweener.addTween(plane, { x:_x, y:_y, z:_z, rotationX:_rotationX, rotationY:_rotationY, rotationZ:_rotationZ, time:5, transition:"easeIn" } ); } protected function onRenderEvent(event:Event):void { var rotY: Number = (mouseY-(stage.stageHeight/2))/(900/2)*(1200); var rotX: Number = (mouseX-(stage.stageWidth/2))/(600/2)*(-1200); displayObject.rotationY = viewport.camera.x + (rotX - viewport.camera.x) / 50; displayObject.rotationX = viewport.camera.y + (rotY - viewport.camera.y) / 30; viewport.singleRender(); } } } package designLab.events { import flash.display.BlendMode; import flash.display.Sprite; import flash.events.Event; import flash.filters.BlurFilter; // Import designLab import designLab.layer.IntroLayer; import designLab.shadow.ShadowCaster; import designLab.utils.LayerConstant; // Import Papervision3D import org.papervision3d.cameras.*; import org.papervision3d.scenes.*; import org.papervision3d.objects.*; import org.papervision3d.objects.special.*; import org.papervision3d.objects.primitives.*; import org.papervision3d.materials.*; import org.papervision3d.materials.special.*; import org.papervision3d.materials.shaders.*; import org.papervision3d.materials.utils.*; import org.papervision3d.lights.*; import org.papervision3d.render.*; import org.papervision3d.view.*; import org.papervision3d.events.InteractiveScene3DEvent; import org.papervision3d.events.*; import org.papervision3d.core.utils.*; import org.papervision3d.core.geom.renderables.Vertex3D; public class CoreEnging extends Sprite { public var viewport :BasicView; // Create BasicView public var displayObject :DisplayObject3D; // Create DisplayObject public var shadowCaster :ShadowCaster; // Create ShadowCaster private var light :PointLight3D; // Create PointLight private var shadowPlane :Plane; // Create Plane private var layer :LayerConstant; // Create constant resource layer private static var instance :CoreEnging; // Create CoreEnging class static instance // CoreEnging class static instance mathod function public static function getinstance() { if (instance != null) return instance; else { instance = new CoreEnging(); return instance; } } // CoreEnging constrictor public function CoreEnging () { trace("INFO: Design Lab Application : Core Enging v0.1"); layer = new LayerConstant(); viewport = new BasicView(900, 600, true, true, CameraType.FREE); // pass the width, height, scaleToStage, interactive, cameraType to BasicView viewport.camera.zoom = 100; // Define the zoom level of camera addChild(viewport); createFloor(); // Create the floor displayObject = new DisplayObject3D(); // Create new instance of DisplayObject viewport.scene.addChild(displayObject); // Add the DisplayObject to the BasicView light = new PointLight3D(); // Create new instance of PointLight light.z = -50; // Position the Z of create instance light.x = 0; //Position the X of create instance light.rotationZ = 45; //Position the rotation angel of the Z of create instance light.y = 500; //Position the Y of create instance shadowCaster = new ShadowCaster("shadow", 0x000000, BlendMode.MULTIPLY, .1, [new BlurFilter(20, 20, 1)]); // pass shadowcaster name, color, blend mode, alpha and filters shadowCaster.setType(ShadowCaster.SPOTLIGHT); // Define the shadow type addEventListener(Event.ENTER_FRAME, onRenderEvent); // Add frame render event } // Start create floor public function createFloor() { var spr:Sprite = new Sprite(); // Create Sprite spr.graphics.beginFill(0xFFFFFF); // Define the fill color for sprite spr.graphics.drawRect(0, 0, 600, 600); // Define the X, Y, width, height of the sprite var sprMaterial:MovieMaterial = new MovieMaterial(spr, true, true, true); //Create a texture from an existing sprite instance shadowPlane = new Plane(sprMaterial, 2000, 2000, 1, 1); // create new instance of the Plane and pass the texture material, width, height, segmentsW and segmentsH shadowPlane.rotationX = 80; //Position the rotation angel of the X of Plane shadowPlane.y = -200; //Position the Y of Plane viewport.scene.addChild(shadowPlane); // Add the Plane to the BasicView } // switch method function of the page layer control public function addLayer(type:String) { switch (type) { case layer.INTRO: var intro:IntroLayer = new IntroLayer(); break; } } // Create get mathod function for DisplayObject public function getDisplayObject():DisplayObject3D { return displayObject; } // Create get mathod function for BasicView public function getViewport():BasicView { return viewport; } // Rendering function protected function onRenderEvent(event:Event):void { var rotY: Number = (mouseY-(stage.stageHeight/2))/(900/2)*(1200); var rotX: Number = (mouseX-(stage.stageWidth/2))/(600/2)*(-1200); displayObject.rotationY = viewport.camera.x + (rotX - viewport.camera.x) / 50; displayObject.rotationX = viewport.camera.y + (rotY - viewport.camera.y) / 30; // Remove the shadow shadowCaster.invalidate(); // create new shadow on DisplayObject move shadowCaster.castModel(displayObject, light, shadowPlane); viewport.singleRender(); } } } package designLab.layer { import flash.display.Sprite; import flash.events.Event; // Import designLab import designLab.materials.iBusinessCard; import designLab.events.CoreEnging; // Import Papervision3D import org.papervision3d.objects.primitives.Cube; import org.papervision3d.materials.ColorMaterial; import org.papervision3d.materials.MovieMaterial; public class IntroLayer { // IntroLayer constrictor public function IntroLayer() { trace("INFO: Load Intro layer"); var indexDP:DP_index = new DP_index(); //Create the library MovieClip var blackMaterial:MovieMaterial = new MovieMaterial(indexDP, true); //Create a texture from an existing library MovieClip instance blackMaterial.smooth = true; blackMaterial.doubleSided = false; var mycolor:ColorMaterial = new ColorMaterial(0x000000); //Create solid color material var mycard:iBusinessCard = new iBusinessCard(blackMaterial, blackMaterial, mycolor, 372, 10, 207); // Create custom 3D cube object to pass the Front, Back, All, CubeWidth, CubeDepth and CubeHeight CoreEnging.getinstance().getDisplayObject().addChild(mycard.create3DCube()); // Add the custom 3D cube to the DisplayObject } } } package designLab.materials { import flash.display.*; import flash.events.*; // Import Papervision3D import org.papervision3d.materials.*; import org.papervision3d.materials.utils.MaterialsList; import org.papervision3d.objects.primitives.Cube; public class iBusinessCard extends Sprite { private var materialsList :MaterialsList; private var cube :Cube; private var Front :MovieMaterial = new MovieMaterial(); private var Back :MovieMaterial = new MovieMaterial(); private var All :ColorMaterial = new ColorMaterial(); private var CubeWidth :Number; private var CubeDepth :Number; private var CubeHeight :Number; public function iBusinessCard(Front:MovieMaterial, Back:MovieMaterial, All:ColorMaterial, CubeWidth:Number, CubeDepth:Number, CubeHeight:Number) { setFront(Front); setBack(Back); setAll(All); setCubeWidth(CubeWidth); setCubeDepth(CubeDepth); setCubeHeight(CubeHeight); } public function create3DCube():Cube { materialsList = new MaterialsList(); materialsList.addMaterial(Front, "front"); materialsList.addMaterial(Back, "back"); materialsList.addMaterial(All, "left"); materialsList.addMaterial(All, "right"); materialsList.addMaterial(All, "top"); materialsList.addMaterial(All, "bottom"); cube = new Cube(materialsList, CubeWidth, CubeDepth, CubeHeight); cube.x = 0; cube.y = 0; cube.z = 0; cube.rotationY = 180; return cube; } public function setFront(Front:MovieMaterial) { this.Front = Front; } public function getFront():MovieMaterial { return Front; } public function setBack(Back:MovieMaterial) { this.Back = Back; } public function getBack():MovieMaterial { return Back; } public function setAll(All:ColorMaterial) { this.All = All; } public function getAll():ColorMaterial { return All; } public function setCubeWidth(CubeWidth:Number) { this.CubeWidth = CubeWidth; } public function getCubeWidth():Number { return CubeWidth; } public function setCubeDepth(CubeDepth:Number) { this.CubeDepth = CubeDepth; } public function getCubeDepth():Number { return CubeDepth; } public function setCubeHeight(CubeHeight:Number) { this.CubeHeight = CubeHeight; } public function getCubeHeight():Number { return CubeHeight; } } } package designLab.shadow { import flash.display.Sprite; import flash.filters.BlurFilter; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.Dictionary; import org.papervision3d.core.geom.TriangleMesh3D; import org.papervision3d.core.geom.renderables.Triangle3D; import org.papervision3d.core.geom.renderables.Vertex3D; import org.papervision3d.core.math.BoundingSphere; import org.papervision3d.core.math.Matrix3D; import org.papervision3d.core.math.Number3D; import org.papervision3d.core.math.Plane3D; import org.papervision3d.lights.PointLight3D; import org.papervision3d.materials.MovieMaterial; import org.papervision3d.objects.DisplayObject3D; import org.papervision3d.objects.primitives.Plane; public class ShadowCaster { private var vertexRefs:Dictionary; private var numberRefs:Dictionary; private var lightRay:Number3D = new Number3D() private var p3d:Plane3D = new Plane3D(); public var color:uint = 0; public var alpha:Number = 0; public var blend:String = ""; public var filters:Array; public var uid:String; private var _type:String = "point"; private var dir:Number3D; private var planeBounds:Dictionary; private var targetBounds:Dictionary; private var models:Dictionary; public static var DIRECTIONAL:String = "dir"; public static var SPOTLIGHT:String = "spot"; public function ShadowCaster(uid:String, color:uint = 0, blend:String = "multiply", alpha:Number = 1, filters:Array=null) { this.uid = uid; this.color = color; this.alpha = alpha; this.blend = blend; this.filters = filters ? filters : [new BlurFilter()]; numberRefs = new Dictionary(true); targetBounds = new Dictionary(true); planeBounds = new Dictionary(true); models = new Dictionary(true); } public function castModel(model:DisplayObject3D, light:PointLight3D, plane:Plane, faces:Boolean = true, cull:Boolean = false):void{ var ar:Array; if(models[model]) { ar = models[model]; }else{ ar = new Array(); getChildMesh(model, ar); models[model] = ar; } var reset:Boolean = true; for each(var t:TriangleMesh3D in ar){ if(faces) castFaces(light, t, plane, cull, reset); else castBoundingSphere(light, t, plane, 0.75, reset); reset = false; } } private function getChildMesh(do3d:DisplayObject3D, ar):void{ if(do3d is TriangleMesh3D) ar.push(do3d); for each(var d:DisplayObject3D in do3d.children) getChildMesh(d, ar); } public function setType(type:String="point"):void{ _type = type; } public function getType():String{ return _type; } public function castBoundingSphere(light:PointLight3D, target:TriangleMesh3D, plane:Plane, scaleRadius:Number=0.8, clear:Boolean = true):void{ var planeVertices:Array = plane.geometry.vertices; //convert to target space? var world:Matrix3D = plane.world; var inv:Matrix3D = Matrix3D.inverse(plane.transform); var lp:Number3D = new Number3D(light.x, light.y, light.z); Matrix3D.multiplyVector(inv, lp); p3d.setNormalAndPoint(plane.geometry.faces[0].faceNormal, new Number3D()); var b:BoundingSphere = target.geometry.boundingSphere; var bounds:Object = planeBounds[plane]; if(!bounds){ bounds = plane.boundingBox(); planeBounds[plane] = bounds; } var tbounds:Object = targetBounds[target]; if(!tbounds){ tbounds = target.boundingBox(); targetBounds[target] = tbounds; } var planeMovie:Sprite = Sprite(MovieMaterial(plane.material).movie); var movieSize:Point = new Point(planeMovie.width, planeMovie.height); var castClip:Sprite = getCastClip(plane); castClip.blendMode = this.blend; castClip.filters = this.filters; castClip.alpha = this.alpha; if(clear) castClip.graphics.clear(); vertexRefs = new Dictionary(true); var tlp:Number3D = new Number3D(light.x, light.y, light.z); Matrix3D.multiplyVector(Matrix3D.inverse(target.world), tlp); var center:Number3D = new Number3D(tbounds.min.x+tbounds.size.x*0.5, tbounds.min.y+tbounds.size.y*0.5, tbounds.min.z+tbounds.size.z*0.5); var dif:Number3D = Number3D.sub(lp, center); dif.normalize(); var other:Number3D = new Number3D(); other.x = -dif.y; other.y = dif.x; other.z = 0; other.normalize(); var cross:Number3D = Number3D.cross(new Number3D(plane.transform.n12, plane.transform.n22, plane.transform.n32), p3d.normal); cross.normalize(); //cross = new Number3D(-dif.y, dif.x, 0); //cross.normalize(); cross.multiplyEq(b.radius*scaleRadius); if(_type == DIRECTIONAL){ var oPos:Number3D = new Number3D(target.x, target.y, target.z); Matrix3D.multiplyVector(target.world, oPos); Matrix3D.multiplyVector(inv, oPos); dir = new Number3D(oPos.x-lp.x, oPos.y-lp.y, oPos.z-lp.z); } //numberRefs = new Dictionary(true); var pos:Number3D; var c2d:Point; var r2d:Point; //_type = SPOTLIGHT; pos = projectVertex(new Vertex3D(center.x, center.y, center.z), lp, inv, target.world); c2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); pos = projectVertex(new Vertex3D(center.x+cross.x, center.y+cross.y, center.z+cross.z), lp, inv, target.world); r2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); var dx:Number = r2d.x-c2d.x; var dy:Number = r2d.y-c2d.y; var rad:Number = Math.sqrt(dx*dx+dy*dy); castClip.graphics.beginFill(color); castClip.graphics.moveTo(c2d.x, c2d.y); castClip.graphics.drawCircle(c2d.x, c2d.y, rad); castClip.graphics.endFill(); } public function getCastClip(plane:Plane):Sprite{ var planeMovie:Sprite = Sprite(MovieMaterial(plane.material).movie); var movieSize:Point = new Point(planeMovie.width, planeMovie.height); var castClip:Sprite;// = new Sprite(); if(planeMovie.getChildByName("castClip"+uid)) return Sprite(planeMovie.getChildByName("castClip"+uid)); else{ castClip = new Sprite(); castClip.name = "castClip"+uid; castClip.scrollRect = new Rectangle(0, 0, movieSize.x, movieSize.y); //castClip.alpha = 0.4; planeMovie.addChild(castClip); return castClip; } } public function castFaces(light:PointLight3D, target:TriangleMesh3D, plane:Plane, cull:Boolean=false, clear:Boolean = true):void{ var planeVertices:Array = plane.geometry.vertices; //convert to target space? var world:Matrix3D = plane.world; var inv:Matrix3D = Matrix3D.inverse(plane.transform); var lp:Number3D = new Number3D(light.x, light.y, light.z); Matrix3D.multiplyVector(inv, lp); var tlp:Number3D; if(cull){ tlp = new Number3D(light.x, light.y, light.z); Matrix3D.multiplyVector(Matrix3D.inverse(target.world), tlp); } //Matrix3D.multiplyVector(Matrix3D.inverse(target.transform), tlp); //p3d.setThreePoints(planeVertices[0].getPosition(), planeVertices[1].getPosition(), planeVertices[2].getPosition()); p3d.setNormalAndPoint(plane.geometry.faces[0].faceNormal, new Number3D()); if(_type == DIRECTIONAL){ var oPos:Number3D = new Number3D(target.x, target.y, target.z); Matrix3D.multiplyVector(target.world, oPos); Matrix3D.multiplyVector(inv, oPos); dir = new Number3D(oPos.x-lp.x, oPos.y-lp.y, oPos.z-lp.z); } var bounds:Object = planeBounds[plane]; if(!bounds){ bounds = plane.boundingBox(); planeBounds[plane] = bounds; } var castClip:Sprite = getCastClip(plane); castClip.blendMode = this.blend; castClip.filters = this.filters; castClip.alpha = this.alpha; var planeMovie:Sprite = Sprite(MovieMaterial(plane.material).movie); var movieSize:Point = new Point(planeMovie.width, planeMovie.height); if(clear) castClip.graphics.clear(); vertexRefs = new Dictionary(true); //numberRefs = new Dictionary(true); var pos:Number3D; var p2d:Point; var s2d:Point; var hitVert:Number3D = new Number3D(); for each(var t:Triangle3D in target.geometry.faces){ if( cull){ hitVert.x = t.v0.x; hitVert.y = t.v0.y; hitVert.z = t.v0.z; if(Number3D.dot(t.faceNormal, Number3D.sub(tlp, hitVert)) <= 0) continue; } castClip.graphics.beginFill(color); pos = projectVertex(t.v0, lp, inv, target.world); s2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); castClip.graphics.moveTo(s2d.x, s2d.y); pos = projectVertex(t.v1, lp, inv, target.world); p2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); castClip.graphics.lineTo(p2d.x, p2d.y); pos = projectVertex(t.v2, lp, inv, target.world); p2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); castClip.graphics.lineTo(p2d.x, p2d.y); castClip.graphics.lineTo(s2d.x, s2d.y); castClip.graphics.endFill(); } } public function invalidate():void{ invalidateModels(); invalidatePlanes(); } public function invalidatePlanes():void{ planeBounds = new Dictionary(true); } public function invalidateTargets():void{ numberRefs = new Dictionary(true); targetBounds = new Dictionary(true); } public function invalidateModels():void{ models = new Dictionary(true); invalidateTargets(); } private function get2dPoint(pos3D:Number3D, min3D:Number3D, size3D:Number3D, movieSize:Point):Point{ return new Point((pos3D.x-min3D.x)/size3D.x*movieSize.x, ((-pos3D.y-min3D.y)/size3D.y*movieSize.y)); } private function projectVertex(v:Vertex3D, light:Number3D, invMat:Matrix3D, world:Matrix3D):Number3D{ var pos:Number3D = vertexRefs[v]; if(pos) return pos; var n:Number3D = numberRefs[v]; if(!n){ n = new Number3D(v.x, v.y, v.z); Matrix3D.multiplyVector(world, n); Matrix3D.multiplyVector(invMat, n); numberRefs[v] = n; } if(_type == SPOTLIGHT){ lightRay.x = light.x; lightRay.y = light.y; lightRay.z = light.z; }else{ lightRay.x = n.x-dir.x; lightRay.y = n.y-dir.y; lightRay.z = n.z-dir.z; } pos = p3d.getIntersectionLineNumbers(lightRay, n); vertexRefs[v] = pos; return pos; } } } package designLab.utils { public class LayerConstant { public const INTRO:String = "INTRO"; // Intro layer string constant } }*emphasized text*

    Read the article

  • Flex, Papervision3d: basic scenes, cameras, planes issue

    - by user157880
    // Import Papervision3D import org.papervision3d.Papervision3D; import org.papervision3d.scenes.; import org.papervision3d.cameras.; import org.papervision3d.objects.; import org.papervision3d.materials.; public var scene:Scene3D; public var camera:Camera3D; public var target:DisplayObject3D; public var screenshotArray: Array;//array to store pictures public var radius:Number; public var image:Image; private function initPapervision():void { target= new DisplayObject3D(); camera= new Camera3D(target); 1067: Implicit coercion of a value of type org.papervision3d.objects:DisplayObject3D to an unrelated type Number. scene= new Scene3D(thisContainer); 1137: Incorrect number of arguments. Expected no more than 0. scene.addChild( new DisplayObject3D() , "center" ); } public function handleCreationComplete():void { image = new Image(); image.source = "one_t.jpg"; image.maintainAspectRatio = true; image.scaleContent = false; image.autoLoad = false; image.addEventListener(Event.COMPLETE, handleImageLoad); image.load(); initPapervision(); } public function handleImageLoad(event:Event):void { init3D(); // onEnterFrame addEventListener( Event.ENTER_FRAME, loop3D ); addEventListener( MouseEvent.MOUSE_MOVE , handleMouseMove); } public function init3D():void { addScreenshots(20); } public function handleMouseMove(event:MouseEvent):void { camera.y = Math.max( thisContainer.mouseY*5 , -450 ); } public function addScreenshots(planeCount:Number):void { var obj:DisplayObject3D = scene.getChildByName ("center"); screenshotArray = new Array(planeCount); var texture:BitmapData = new BitmapData(image.content.loaderInfo.width, image.content.loaderInfo.height, false, 0); texture.draw(image); // Create texture with a bitmap from the library var materialSpace :MaterialObject3D = new BitmapMaterial(texture); materialSpace.doubleSided = true; materialSpace.smooth = false; radius = 500; camera.z = radius + 50; camera.y = 50; for (var i:Number = 0; i < planeCount; i++ ) { screenshotArray[i] = new Object() <b>screenshotArray[i].plane = new Plane( materialSpace, 100, 100, 2, 2 );</b> 1180: Call to a possibly undefined method Plane. // Position plane var rotation:Number = (360/planeCount)* i ; var rotationRadians:Number = (rotation-90) * (Math.PI/180); screenshotArray[i].rotation = rotation; screenshotArray[i].plane.z = (radius * Math.cos(rotationRadians) ) * -1; screenshotArray[i].plane.x = radius * Math.sin(rotationRadians) * -1; screenshotArray[i].plane.y = 100; screenshotArray[i].plane.lookAt(obj); // Add to scene scene.addChild( screenshotArray[i].plane ); } <b>scene.renderCamera(camera);</b> <i>1061: Call to a possibly undefined method renderCamera through a reference with static type org.papervision3d.scenes:Scene3D.</i> } public function loop3D(event:Event):void { var obj:DisplayObject3D = scene.getChildByName ("center"); for (var i:Number = 0; i < screenshotArray.length ; i++ ) { var rotation:Number = screenshotArray[i].rotation; rotation += (thisContainer.mouseX/50)/(screenshotArray.length/10); var rotationRadians:Number = (rotation-90) * (Math.PI/180); screenshotArray[i].rotation = rotation; screenshotArray[i].plane.z = (radius * Math.cos(rotationRadians) ) * -1; screenshotArray[i].plane.x = radius * Math.sin(rotationRadians) * -1; screenshotArray[i].plane.lookAt(obj); } //now lets render the scene <b>scene.renderCamera(camera);</b> <i>1061: Call to a possibly undefined method renderCamera through a reference with static type org.papervision3d.scenes:Scene3D.</i> } ]]

    Read the article

  • Flash Mouse.hide() cmd+tab(alt+tab) bring the mouse back

    - by DickieBoy
    Having a bit of trouble with Mouse.show() and losing focus of the swf This isn't my demo: but its showing the same bug http://www.foundation-flash.com/tutorials/as3customcursors/ What i do to recreate it is: mouse over the swf, hit cmd+tab to highlight another window, result is that the mouse is not brought back and is still invisible, (to get it back go to the window bar at the top of the screen and click something). I have an area in which movement is detected and an image Things I have tried package { import flash.display.Sprite; import flash.display.MovieClip; import com.greensock.*; import flash.events.*; import flash.utils.Timer; import flash.events.TimerEvent; import flash.utils.*; import flash.ui.Mouse; public class mousey_movey extends MovieClip { public var middle_of_the_flash; //pixels per second public var speeds = [0,1,3,5,10]; public var speed; public var percentage_the_mouse_is_across_the_screen; public var mouse_over_scrollable_area:Boolean; public var image_move_interval; public function mousey_movey() { middle_of_the_flash = stage.stageWidth/2; hot_area_for_movement.addEventListener(MouseEvent.MOUSE_OVER, mouseEnter); hot_area_for_movement.addEventListener(MouseEvent.MOUSE_OUT, mouseLeave); hot_area_for_movement.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove); stage.addEventListener(Event.MOUSE_LEAVE, show_mouse); stage.addEventListener(MouseEvent.MOUSE_OUT, show_mouse); stage.addEventListener(Event.DEACTIVATE,show_mouse); hot_area_for_movement.alpha=0; hot_area_for_movement.x=0; hot_area_for_movement.y=34; } public function show_mouse(e) { trace(e.type) trace('show_mouse') Mouse.show(); } public function onActivate(e) { trace('activate'); Mouse.show(); } public function onDeactivate(e) { trace('deactivate'); } public function get_speed(percantage_from_middle):int { if(percantage_from_middle > 80) { return speeds[4] } else { if(percantage_from_middle > 60) { return speeds[3] } else { if(percantage_from_middle > 40) { return speeds[2] } else { if(percantage_from_middle > 20) { return speeds[1] } else { return 0; } } } } } public function mouseLeave(e:Event):void{ Mouse.show(); clearInterval(image_move_interval); } public function mouseEnter(e:Event):void{ Mouse.hide(); image_move_interval = setInterval(moveImage,1); } public function mouseMove(e:Event):void { percentage_the_mouse_is_across_the_screen = Math.round(((middle_of_the_flash-stage.mouseX)/middle_of_the_flash)*100); speed = get_speed(Math.abs(percentage_the_mouse_is_across_the_screen)); airplane_icon.x = stage.mouseX; airplane_icon.y = stage.mouseY; } public function stageMouseMove(e:Event):void{ Mouse.show(); } public function moveImage():void { if(percentage_the_mouse_is_across_the_screen > 0) { moving_image.x+=speed; airplane_icon.scaleX = -1; } else { moving_image.x-=speed; airplane_icon.scaleX = 1; } } } } Nothing too fancy, im just scrolling an image left of right at a speed which is generated by how far you are from the middle of the stage, and making an airplane moveclip follow the mouse. The events: stage.addEventListener(Event.MOUSE_LEAVE, show_mouse); stage.addEventListener(MouseEvent.MOUSE_OUT, show_mouse); stage.addEventListener(Event.DEACTIVATE,show_mouse); All fire and work correctly when in the browser, seem a little buggy when running a test through flash, was expecting this as ive experienced it before. The deactivate call even runs when testing and cmd+tabbing but shows no mouse. Any help on the matter is appreciated Thanks, Dickie

    Read the article

  • Running game, leaving game and continuing animation

    - by Madrusec
    I have been trying to learn some Actionscript recently and have been trying to run an interactive story that at one point turns into an extremel simple shooter game. After the player either wins or looses, then he/she is taken to the rest of the animated story. So I have everything up to the point where the games runs (successfully) but for some reason I am unable to have flash run the rest of the frames, most of which have no code at all. This is the code for scene 1: stop (); import flash.display.MovieClip; import flash.events.MouseEvent; import flash.utils.Timer; import flash.events.TimerEvent; var stoneInGame:uint; var stoneMaker: Timer; var container_mc: MovieClip; var cursor:MovieClip; var score:int; var anxiety:int; var anxiety_mc :MovieClip = new mcAnxiety(); //stage.addChild( anxiety_mc ); function initializeGame():void { stoneInGame = 10; stoneMaker = new Timer(1000, stoneInGame); container_mc = new MovieClip(); addChild(container_mc); container_mc.addChild(anxiety_mc); anxiety_mc.x = 497; anxiety_mc.y = 360; stoneMaker.addEventListener(TimerEvent.TIMER, createStones); stoneMaker.start(); cursor = new Cursor(); addChild(cursor); cursor.enabled = false; Mouse.hide(); stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor); score = 0; anxiety = anxiety_mc.totalFrames; anxiety_mc.gotoAndStop(anxiety); } function dragCursor(event:MouseEvent):void { cursor.x = this.mouseX; cursor.y = this.mouseY; } function createStones(event:TimerEvent):void { var stone:MovieClip; stone = new Stone(); stone.x = Math.random() * stage.stageWidth; stone.y = Math.random() * stage.stageHeight; container_mc.addChild(stone); } function increaseScore():void { score ++; if(score >= stoneInGame) { dragCursor.stop(); createStones.stop(); stoneMaker.stop(); trace("you wind!"); } } function decreaseAnxiety():void { anxiety--; if(anxiety <= 0) { stoneMaker.stop(); trace("you lose!"); } else { anxiety_mc.gotoAndStop(anxiety); } increaseScore(); } initializeGame(); So what I tried to do was adding gotoAndPlay() inside both the decreaseAnxiety and increaseScore functions after the trace statements and referenced a frame where I have more keyframes that continue a story. However, Flash just goes back to the beginning of the timeline and I even the functions that change and control the cursor seem to be running. This leads me to believe that I need to make sure that I tell flash o stup running certain functions before jumping to another frame. However, it seems to me that I would still have the same issue and not be able to continue in the timeline. Is there something I am missing? How can I jump out of all this code once the game finishes and simply continue playing the rest of the frames? Any pointers would be greatly appreciated. Thank you

    Read the article

< Previous Page | 1 2 3 4