Setting up Touch Events on Materials in Papervision - actionscript

I am working with papervision and would like to setup a TouchEvent on each side of a Cube. How would i go about it ? Right now i am setting up the events on the movieclip which i pass to the MovieMaterial class. The MouseEvent is working fine but the TouchEvent doesn't seem to fire.
public function MiniCube(k:int, j:int, i:int)
{
var matList:Object = {all:new ColorMaterial(0xff0000,1,true)};
matList.back = createColorMC(0x000000,'back');
matList.front = createColorMC(0x000000,'front');
matList.top = createColorMC(0x000000,'top');
matList.bottom = createColorMC(0x000000,'bottom');
matList.right = createColorMC(0x000000,'right');
matList.left = createColorMC(0x000000,'left');
cube = new Cube(new MaterialsList(matList),10,10,10);
}
private function createColorMC(color:uint, name:String):MovieMaterial
{
var ClassReference:Class = getDefinitionByName(iconArr[Math.floor(Math.random() * iconArr.length)]) as Class;
var mc=new ClassReference();
mc.name = name;
//MOUSE EVENT WORKS
mc.addEventListener(MouseEvent.MOUSE_DOWN, onMovieMatClicked);
//TOUCH EVENT DOESNT
mc.addEventListener(TouchEvent.TOUCH_BEGIN, onMovieMatClicked);
var movieMat:MovieMaterial = new MovieMaterial(mc,true,true);
movieMat.interactive = true;
movieMat.smooth = true;
movieMat.animated = true;
return movieMat;
}

Did you enable multitouch on your application? The following line goes in the constructor of your main application class:
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
or
Multitouch.inputMode = MultitouchInputMode.GESTURE;

Related

Windows 10 Universal App custom map

I want to create an app for airplane navigation. Since for pilots the Bing maps are useless I need to create my own map a texture of an aeronautical map.
I couldn't find any clue how to start on this. Is there an SDK for Bing maps where I can create my own texture/overlay?
Do I need to start from rock bottom and create a picture and change its position so the relevant part is in the visible area of the device?
I need the following features:
Show current position on the map.
Add some custom POIs via coordinates
After quite some research I figured it out myself.
Here is most of the code needed if you have the same scenario
Uri format:
"https://webserver/tiles/{zoomlevel}/{x}/{y}.png";
private void InitMap()
{
_gps = new Geolocator();
pointBuffer = cologne;
image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/images/airplane.png"));
MyMap.Style = MapStyle.None;
//Setup Icao Layer
_icaoTileSource = new MapTileSource();
var _tileLayer = new HttpMapTileDataSource();
_tileLayer.UriFormatString = IcaoUri;
_icaoTileSource.DataSource = _tileLayer;
MyMap.TileSources.Add(_icaoTileSource);
//Setup VFR Layer
_vfrTileSource = new MapTileSource();
var _vfrtileLayer = new HttpMapTileDataSource();
_vfrtileLayer.UriFormatString = VfrUri;
_vfrTileSource.DataSource = _vfrtileLayer;
//Setup Low Level Layer
_lowlvlTileSource = new MapTileSource();
var _lowlvltileLayer = new HttpMapTileDataSource();
_lowlvltileLayer.UriFormatString = LowLvlUri;
_lowlvlTileSource.DataSource = _lowlvltileLayer;
airplane = new MapIcon()
{
Title = "My Position",
Image = image,
Visible = true,
Location = cologne,
NormalizedAnchorPoint = new Point(0.5, 0.5)
};
_tileLayer.AllowCaching = true;
MyMap.MapElements.Add(airplane);
systemSetCenter = true;
MyMap.Center = cologne;
MyMap.ZoomLevel = 10;
_vm.ZoomLevel = MyMap.ZoomLevel;
MyMap.ZoomLevelChanged += (s, e) =>
{
if(s.ZoomLevel > maxZoomLevel)
{
s.ZoomLevel = maxZoomLevel;
}
_vm.ZoomLevel = s.ZoomLevel;
};
}

could not be able to create http service programmatically in flex

I'm trying to create HttpService through Action Script and I want to convert this mxml code to my Action Script
mxml code code is here:
<s:HTTPService id="weatherService"
url="{BASE_URL}"
resultFormat="object"
result="weatherService_resultHandler(event)"
fault="weatherService_faultHandler(event)"
showBusyCursor="true">
<s:request xmlns="">
<q>{cityName.text.toString()}</q>
<format>{FORMAT}</format>
<num_of_days>{NUMBER_OF_DAYS}</num_of_days>
<key>{API_KEY}</key>
</s:request>
</s:HTTPService>
How to convert this in actionscript?
This might help you and please note here the following code not using binding
import mx.rpc.http.HTTPService;
private function callService():void
{
var requestObj:Object = {};
requestObj.q = cityName.text.toString();
requestObj.format = FORMAT;
requestObj.num_of_days = cNUMBER_OF_DAYS;
requestObj.key = API_KEY;
var weatherService:HTTPService = new HTTPService();
weatherService.url = BASE_URL;
weatherService.resultFormat = "object";
weatherService.showBusyCursor = true;
weatherService.request = requestObj;
weatherService.addEventListener(ResultEvent.RESULT , weatherService_resultHandler);
weatherService.addEventListener(FaultEvent.FAULT, weatherService_faultHandler);
weatherService.send();
}
protected function weatherService_resultHandler(event:ResultEvent):void
{
trace("got result");
}
protected function weatherService_faultHandler(event:FaultEvent):void
{
trace("got fault");
}

AS2: rollover on attached movieclip

The following is the chunk of my code that is attaching a movieclip (from timeline), tracing thisDot works so it is not the variable which is a problem but there is no rollover applied to the attached movieclip.
var dot_name:String = new String(Graphs[s]._name+"_dot"+i);
var dotObj:Object = new Object();
if (prevX != undefined) {
dotObj._x = newX;
} else {
dotObj._x = 0;
}
dotObj._y = Slide_y;
Graphs[s].chart.attachMovie("graph_dot",dot_name,Graphs[s].chart.getNextHighestDepth(),dotObj);
eval(thisDot=Graphs[s]+".chart."+dot_name);
Graphs_dots[s].push(thisDot);
thisDot.onRollOver = function () {
trace(this);
Looks to me that this row:
eval(thisDot=Graphs[s]+".chart."+dot_name);
should be this instead?
thisDot=eval(Graphs[s]+".chart."+dot_name);

AIR application: Cannot access a property or method of a null object reference. No idea what's causing this

I'm using code for the open source MP3 player Howler and trying to port it to a Spark MobileApplication type. I'm getting a null pointer exception and I have no idea what's causing it. I've tried debugging extensively with breakpoints at what I think is causing the error, and set breakpoints in the untouched Howler project but all the variables in scope seem to be identical between my non-working project, and the Howler project. The only thing I can think of is that Howler uses MX components and I am using spark. I've pasted all my code below (which is very long) but I've bolded the lines that are throwing the error. The error occurs immediately after I choose a folder in the browse folder dialog.
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="Home"
xmlns:Comp="components.*" xmlns:display="flash.display.*">
<s:Button id="browse" x="546" y="43" label="Open Directory" click="browseForFolder()"/>
<s:DataGrid id="dgPlaylist" width="82" height="141" itemRenderer="components.DurationFormatter">
</s:DataGrid>
<s:Button id="btnForward" x="187" y="126" label="Forward"/>
<s:Button id="btnPause" x="90" y="39" label="Pause"/>
<s:Button id="btnBack" x="55" y="166" label="Back" click="changeSoundIndex(-1)"/>
<s:Button id="btnPlay" x="336" y="199" label="Button"/>
<s:Button id="btnStop" x="366" y="89" label="Stop"/>
<s:VScrollBar id="sldrPosition" x="280" y="43" mouseDown="thumbTimer.stop()"
mouseUp="thumbTimer.start()"
/>
<s:VScrollBar id="sldrVolume" x="265" y="234" change="ChangeSoundTransform()"
/>
<s:RichText id="txtID3" x="236" y="41" width="99">
</s:RichText>
<fx:Declarations>
</fx:Declarations>
<fx:Script>
<![CDATA[
import com.ericcarlisle.PlayList;
import com.ericcarlisle.PlayModes;
import com.ericcarlisle.Utility;
import flash.desktop.NativeDragManager;
import flash.media.Sound;
import mx.core.UIComponent;
import mx.events.CloseEvent;
import mx.events.DragEvent;
import org.osmf.traits.PlayTrait;
import spark.components.DataGrid;
// Player properties
private var playMode:String = "STOP";
private var volume:uint;
private const panning:int = 0;
private var selectedFileCount:uint;
private var loadedFileCount:uint;
private var soundIndex:uint;
// Player objects
private var SoundObj:Sound;
private var Channel:SoundChannel;
private var Transform:SoundTransform;
private var thumbTimer:Timer;
private var PlayList:com.ericcarlisle.PlayList;
private var SoundFilter:FileFilter = new FileFilter("Sounds", "*.mp3;*.wav");
//private var PlaylistFilter:FileFilter = new FileFilter("Sounds", "*.pls;*.m3u");
// Visualization objects.
private var Spectrum:ByteArray;
private const VISUALIZER_HEIGHT:Number = 50;
private const VISUALIZER_COLOR:Number = 0x336699;
// ID3 and other metadata
private var ID3:ID3Info;
private var Duration:int;
/*---------- PLAYER INITIALIZER ----------*/
// Initialization function used to add event handlers and set initial settings.
private function init():void
{
// Set player initial settings.
playMode = PlayModes.STOP;
selectedFileCount = 0;
loadedFileCount = 0;
soundIndex = 0;
// Set initial application height.
//this.height= cvsControlBar.height + cvsPlayer.height;
// Set volume.
volume = sldrVolume.value;
// Instantiate sound objects.
Channel = new SoundChannel();
Transform = new SoundTransform(volume/100, panning);
PlayList = new com.ericcarlisle.PlayList();
// Bind playlist data to datagrid.
dgPlaylist.dataProvider = PlayList.Sounds;
// Create a timer to control the song position hslider.
thumbTimer = new Timer(500);
thumbTimer.addEventListener(TimerEvent.TIMER, onTimerTick);
// Create event handlers for application.
this.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
this.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER, onPlayerDragInto);
this.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP, onPlayerDropInto);
this.addEventListener(InvokeEvent.INVOKE, onInvoke);
}
/*---------- DRAG/DROP & FILE MANAGEMENT ----------*/
private function onInvoke(event:InvokeEvent):void
{
if (event.arguments.length > 0)
{
var file:File;
var files:Array = new Array();
for (var i:int = 0; i < event.arguments.length; i++)
{
file = new File(event.arguments[i]);
files.push(file);
}
if (PlayList.Sounds.length > 0) removeAllSounds();
loadFiles(files);
}
}
// Handles file selection event dispatched by browse dialog.
private function onFileSelect(event:FileListEvent):void
{
loadFiles(event.files);
}
// Handles folder selection event dispatched by browse dialog.
private function onDirectorySelect(event:Event):void
{
var directory:File = event.target as File;
**loadFiles(directory.getDirectoryListing());**
}
// Loads a batch of files into the playlist.
private function loadFiles(files:Array):void
{
var file:File;
// Count the number of files selected. Only accept files with .mp3 extension.
selectedFileCount = 0;
for (var i:uint = 0; i < files.length; i++)
{
file = files[i];
if (file.extension == "mp3") selectedFileCount++;
}
// Reset the count on files currently loaded.
loadedFileCount = 0;
**// Set the player mode so that loaded files are played automatically.
if (PlayList.Sounds.length == 0) playMode = PlayModes.LOADTOPLAY;**
// Load files as sound objects.
for(var j:uint = 0; j < files.length; j++)
{
file = files[j];
if (file.extension == "mp3" || file.extension == "wav")
{
var sound:Sound = new Sound(new URLRequest(file.url));
sound.addEventListener(Event.ID3,onID3);
}
}
}
// Presents file browse (multiple file) dialog.
private function browseForFiles():void
{
var SoundFile:File = new File();
SoundFile.browseForOpenMultiple("Open", [SoundFilter]);//, PlaylistFilter]);
SoundFile.addEventListener(FileListEvent.SELECT_MULTIPLE, onFileSelect);
}
// Presents file browse (folder) dialog.
private function browseForFolder():void
{
var directory:File = File.documentsDirectory;
directory.browseForDirectory("Select Directory");
directory.addEventListener(Event.SELECT, onDirectorySelect);
}
// Accept files dragged into player.
private function onPlayerDragInto(event:Event):void
{
NativeDragManager.acceptDragDrop(this);
}
// Manages files dropped into player.
private function onPlayerDropInto(event:NativeDragEvent):void
{
// Accept only files.
if (event.clipboard.hasFormat(ClipboardFormats.FILE_LIST_FORMAT))
{
// Parse dragged contents into array of files.
var dragFiles:Array = event.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
// Load the files.
loadFiles(dragFiles);
}
}
/*---------- SOUND MANAGEMENT ----------*/
private function loadSound():void
{
SoundObj = new Sound();
SoundObj.load(new URLRequest(PlayList.Sounds[soundIndex]["url"]));
SoundObj.addEventListener(Event.COMPLETE, onSoundLoaded);
}
private function onSoundLoaded(event:Event):void
{
// Retrieve data for current sound from playlist.
var soundData:Object = PlayList.Sounds[soundIndex];
// Place ID3 information into the readout panel.
//txtID3.htmlText = Utility.ReadoutHTML(soundData["title"], soundData["track"], soundData["album"], soundData["artist"], soundData["year"], soundData["duration"]);
// Configure the holizontal slider to act as a playhead.
sldrPosition.maximum = soundData["duration"];
// Set the selected row in the playlist display.
dgPlaylist.selectedIndex = soundIndex;
// Start the player if the mode is correct.
if (playMode == PlayModes.LOADTOPLAY)
{
playSound();
}
else
{
playMode = PlayModes.LOADED;
}
}
// Plays the current sound.
public function playSound():void
{
// Load sound into channel.
Channel.stop();
Channel = SoundObj.play(sldrPosition.value,0,Transform);
playMode = PlayModes.PLAY;
// Start position timer.
thumbTimer.start();
// Configure UI controls.
btnPlay.visible = false;
btnPause.visible = true;
sldrPosition.enabled = true;
btnPlay.enabled = true;
btnStop.enabled = true;
setBackForwardButtons();
Channel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
}
private function setBackForwardButtons():void
{
if (soundIndex == PlayList.Sounds.length-1 || PlayList.Sounds.length == 0)
{
btnForward.enabled = false;
}
else
{
btnForward.enabled = true;
}
if (soundIndex == 0 || PlayList.Sounds.length == 0)
{
btnBack.enabled = false;
}
else
{
btnBack.enabled = true;
}
}
// Stops the current sound.
public function stopSound():void
{
Channel.stop();
thumbTimer.stop();
sldrPosition.value = 0;
playMode = PlayModes.STOP;
//Visualizer.graphics.clear();
btnPlay.visible = true;
btnPause.visible = false;
}
// Pause a playing sound.
private function pauseSound():void
{
Channel.stop();
thumbTimer.stop();
btnPlay.visible = true;
btnPause.visible = false;
}
// Change the sound index
private function changeSoundIndex(delta:int):void
{
stopSound();
playMode = PlayModes.LOADTOPLAY;
soundIndex = soundIndex + delta;
loadSound();
}
// Change the volume and panning via the sound transform object.
private function ChangeSoundTransform():void
{
volume = Math.round(sldrVolume.value);
Channel.soundTransform = new SoundTransform(volume/100, panning);
}
// Handles event for sound completing.
private function onSoundComplete(event:Event):void
{
stopSound();
soundIndex++;
if (soundIndex < PlayList.Sounds.length)
{
playMode = PlayModes.LOADTOPLAY;
loadSound();
}
}
// Load ID3 information into local variables.
// Update the readout panel.
// Configure position slider.
private function onID3(event:Event):void
{
var sound:Sound = Sound(event.target);
ID3 = ID3Info(sound.id3);
Duration = Math.floor(sound.length);
// Load sound id3 data into the playlist.
PlayList.AddSound(ID3.songName, ID3.album, ID3.artist, ID3.track, ID3.year, ID3.genre, Duration, sound.url);
// Increment the loaded file count.
loadedFileCount++;
if (loadedFileCount == selectedFileCount * 2)
{
// Refresh the playlist so that new results will be visually displayed.
PlayList.Sounds.refresh();
// Set the count properties.
selectedFileCount = 0;
loadedFileCount = 0;
soundIndex = 0;
if (playMode == PlayModes.LOADTOPLAY) loadSound();
}
}
/*---------- VISUALIZATION ----------*/
private function UpdateVisualizer():void
{
// Instantiate a new byte array to contain spectrum data.
Spectrum = new ByteArray();
// Clear the visualizer graphics.
//Visualizer.graphics.clear();
// Dump the spectrum data into the byte array.
SoundMixer.computeSpectrum(Spectrum,false,0);
var f:Number;
var i:int;
var ave:int;
//Visualizer.graphics.lineStyle(1, VISUALIZER_COLOR,1);
//Visualizer.graphics.beginFill(VISUALIZER_COLOR, 0.75);
for (i = 0; i < 512; i=i+10)
{
f = Spectrum.readFloat();
//Visualizer.drawRoundRect(Math.floor(i*0.7) + 7, cvsReadout.height - 10, 4, -Math.abs(f) * (cvsReadout.height-10));
}
//Visualizer.graphics.endFill();
}
// Updates the position of the hslider thumb.
private function onTimerTick(event:TimerEvent):void
{
sldrPosition.value = Math.round(Channel.position);
}
// Update the wave visualizer if the sound is playing.
private function onEnterFrame(event:Event):void
{
if (playMode == PlayModes.PLAY)
{
UpdateVisualizer();
}
}
// Show application information.
private function showHowlerInfo():void
{
//cvsAbout.visible = true;
}
private function togglePlayList():void
{
}
private function onItemDoubleClick(event:Event):void
{
this.playMode = PlayModes.LOADTOPLAY;
thumbTimer.stop();
sldrPosition.value = 0;
loadSound();
}
/*---------- ERROR HANDLING ----------*/
// Handles IO errors.
private function onIOError(event:IOErrorEvent):void
{
//Alert.show("File load error: " + event.text);
}
private function startMove():void
{
stage.nativeWindow.startMove();
}
private function unloadSound():void
{
stopSound();
txtID3.text = "";
btnPlay.visible = true;
btnPause.visible = false;
btnPlay.enabled = false;
btnStop.enabled = false;
}
private function removeSound():void
{
var index:int = dgPlaylist.selectedIndex;
if (index >= 0)
{
if (index == soundIndex)
{
unloadSound();
}
PlayList.RemoveSoundAt(index);
PlayList.Sounds.refresh();
setBackForwardButtons();
}
}
private function removeAllSounds():void
{
unloadSound();
PlayList.Sounds.removeAll();
PlayList.Sounds.refresh();
setBackForwardButtons();
}
private function onKeyDown(event:KeyboardEvent):void
{
if (event.charCode.toString() == "8" || event.charCode.toString() == "127")
{
removeSound();
}
}
]]>
</fx:Script>
</s:View>
I'm new to Flex so I don't know if this is causing the problem or not, but the Howler app uses an MX:DataGrid defined like this:
<mx:DataGrid x="6"
y="7"
width="388"
height="310"
id="dgPlaylist"
keyDown="onKeyDown(event)"
dragMoveEnabled="true"
doubleClickEnabled="true"
dragEnabled="true"
dropEnabled="true"
dragComplete="onPlaylistDragDrop(event)"
itemDoubleClick="onItemDoubleClick(event)">
<mx:columns>
<mx:DataGridColumn width="168" headerText="Title" dataField="title" />
<mx:DataGridColumn width="160" headerText="Album" dataField="album"/>
<mx:DataGridColumn width="60" headerText="Duration" dataField="duration" textAlign="right" itemRenderer="components.DurationFormatter"/>
</mx:columns>
</mx:DataGrid>
It has additional columns that I'm not using. Could this be the cause?
We are going to need the error message. Generally what you are experiencing is called a null pointer exception ( just like the error said ). Which basically means you tried to access a property of an object that is null. For example, running the following code will cause the same problem
var arrayCollection:ArrayCollection;
arrayCollection.addItem( new Object() );
To fix your error, you should find the object that the error is referring to in your code and make sure it isn't null when your program executes whatever line it is complaining about, or add an if-loop in the event it is null.

Volume slider - volume doesn't change until mouse over

I've created a small music player with a sliding volume control. I'm having trouble with the volume. Though it does control volume properly, if I set the initial volume to less than 100%, the volume always starts at 100% until I move my mouse over the player. At that point, the volume changes to whatever the initial volume is set to.
Is this a flash bug, or am I missing something?
Here is the affected code (code for other buttons/functions omitted for brevity):
var song_initvolume:Number = 100;
slider_1._x = groove_1._x + song_initvolume;
playSong(0,song_play);
slider_1.onPress = function() {
this.startDrag(true, groove_1._x, groove_1._y, groove_1._x + 96, groove_1._y);
}
slider_1.onRelease = function() {
this.stopDrag();
}
slider_1.onMouseMove = function(){
newPoint = new Object();
newPoint.x = this._x;
newPoint.y = this._y;
groove_1.globalToLocal(newPoint);
mySound_sound.setVolume(-1 * newPoint.x);
}
function playSong(songNum,songPlay,reset_Pos){
if(reset_Pos){
mySound_sound = new Sound();
}
var myTitle = mySongs_array[songNum].TITLE;
trace("Playing TITLE= " + myTitle);
var myArtist = mySongs_array[songNum].ARTIST;
trace("Playing ARTIST= " + myArtist);
var myURL = mySongs_array[songNum].URL;
trace("Playing URL= " + myURL);
title_txt.text = mySongs_array[songNum].TITLE;
artist_txt.text = mySongs_array[songNum].ARTIST;
mySound_sound.loadSound(myURL,songPlay);
// start oncomplete
mySound_sound.onSoundComplete = function() {
song_pos = 0;
reset_Pos = true;
if(song_continuous){
song_play = true;
current_song++;
if (current_song>=my_total){
current_song=0;
if(song_loop){
song_play = true;
} else {
song_play = false;
}
}
} else {
song_play = false;
}
playSong(current_song,song_play,reset_Pos);
}
// end oncomplete
}
I'd like to be able to set the volume at say 50%, but the above mentioned behavior happens each time.
Any ideas are greatly appreciated.
You need to call mySound_sound.setVolume() with your initial value. Right now you only do in in the onMouseMove handler.
Just fixed with this code:
mySound_sound.onLoad = function(){
mySound_sound.setVolume(-1 * song_volume);
}
Works great now!

Resources