Search Results

Search found 1910 results on 77 pages for 'driving directions'.

Page 5/77 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • how to use 3D map Actionscript class in mxml file for display map.

    - by nemade-vipin
    hello friends, I have created the application in which I have to use 3D map Action Script class in mxml file to display a map in form. that is in tab navigator last tab. My ActionScript 3D map class is(FlyingDirections):- package src.SBTSCoreObject { import src.SBTSCoreObject.JSONDecoder; import com.google.maps.InfoWindowOptions; import com.google.maps.LatLng; import com.google.maps.LatLngBounds; import com.google.maps.Map3D; import com.google.maps.MapEvent; import com.google.maps.MapOptions; import com.google.maps.MapType; import com.google.maps.MapUtil; import com.google.maps.View; import com.google.maps.controls.NavigationControl; import com.google.maps.geom.Attitude; import com.google.maps.interfaces.IPolyline; import com.google.maps.overlays.Marker; import com.google.maps.overlays.MarkerOptions; import com.google.maps.services.Directions; import com.google.maps.services.DirectionsEvent; import com.google.maps.services.Route; import flash.display.Bitmap; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.filters.DropShadowFilter; import flash.geom.Point; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.utils.Timer; import flash.utils.getTimer; public class FlyingDirections extends Map3D { /** * Panoramio home page. */ private static const PANORAMIO_HOME:String = "http://www.panoramio.com/"; /** * The icon for the car. */ [Embed("assets/car-icon-24px.png")] private static const Car:Class; /** * The Panoramio icon. */ [Embed("assets/iw_panoramio.png")] private static const PanoramioIcon:Class; /** * We animate a zoom in to the start the route before the car starts * to move. This constant sets the time in seconds over which this * zoom occurs. */ private static const LEAD_IN_DURATION:Number = 3; /** * Duration of the trip in seconds. */ private static const TRIP_DURATION:Number = 40; /** * Constants that define the geometry of the Panoramio image markers. */ private static const BORDER_T:Number = 3; private static const BORDER_L:Number = 10; private static const BORDER_R:Number = 10; private static const BORDER_B:Number = 3; private static const GAP_T:Number = 2; private static const GAP_B:Number = 1; private static const IMAGE_SCALE:Number = 1; /** * Trajectory that the camera follows over time. Each element is an object * containing properties used to generate parameter values for flyTo(..). * fraction = 0 corresponds to the start of the trip; fraction = 1 * correspondsto the end of the trip. */ private var FLY_TRAJECTORY:Array = [ { fraction: 0, zoom: 6, attitude: new Attitude(0, 0, 0) }, { fraction: 0.2, zoom: 8.5, attitude: new Attitude(30, 30, 0) }, { fraction: 0.5, zoom: 9, attitude: new Attitude(30, 40, 0) }, { fraction: 1, zoom: 8, attitude: new Attitude(50, 50, 0) }, { fraction: 1.1, zoom: 8, attitude: new Attitude(130, 50, 0) }, { fraction: 1.2, zoom: 8, attitude: new Attitude(220, 50, 0) }, ]; /** * Number of panaramio photos for which we load data. We&apos;ll select a * subset of these approximately evenly spaced along the route. */ private static const NUM_GEOTAGGED_PHOTOS:int = 50; /** * Number of panaramio photos that we actually show. */ private static const NUM_SHOWN_PHOTOS:int = 7; /** * Scaling between real trip time and animation time. */ private static const SCALE_TIME:Number = 0.001; /** * getTimer() value at the instant that we start the trip. If this is 0 then * we have not yet started the car moving. */ private var startTimer:int = 0; /** * The current route. */ private var route:Route; /** * The polyline for the route. */ private var polyline:IPolyline; /** * The car marker. */ private var marker:Marker; /** * The cumulative duration in seconds over each step in the route. * cumulativeStepDuration[0] is 0; cumulativeStepDuration[1] adds the * duration of step 0; cumulativeStepDuration[2] adds the duration * of step 1; etc. */ private var cumulativeStepDuration:/*Number*/Array = []; /** * The cumulative distance in metres over each vertex in the route polyline. * cumulativeVertexDistance[0] is 0; cumulativeVertexDistance[1] adds the * distance to vertex 1; cumulativeVertexDistance[2] adds the distance to * vertex 2; etc. */ private var cumulativeVertexDistance:Array; /** * Array of photos loaded from Panoramio. This array has the same format as * the &apos;photos&apos; property within the JSON returned by the Panoramio API * (see http://www.panoramio.com/api/), with additional properties added to * individual photo elements to hold the loader structures that fetch * the actual images. */ private var photos:Array = []; /** * Array of polyline vertices, where each element is in world coordinates. * Several computations can be faster if we can use world coordinates * instead of LatLng coordinates. */ private var worldPoly:/*Point*/Array; /** * Whether the start button has been pressed. */ private var startButtonPressed:Boolean = false; /** * Saved event from onDirectionsSuccess call. */ private var directionsSuccessEvent:DirectionsEvent = null; /** * Start button. */ private var startButton:Sprite; /** * Alpha value used for the Panoramio image markers. */ private var markerAlpha:Number = 0; /** * Index of the current driving direction step. Used to update the * info window content each time we progress to a new step. */ private var currentStepIndex:int = -1; /** * The fly directions map constructor. * * @constructor */ public function FlyingDirections() { key="ABQIAAAA7QUChpcnvnmXxsjC7s1fCxQGj0PqsCtxKvarsoS-iqLdqZSKfxTd7Xf-2rEc_PC9o8IsJde80Wnj4g"; super(); addEventListener(MapEvent.MAP_PREINITIALIZE, onMapPreinitialize); addEventListener(MapEvent.MAP_READY, onMapReady); } /** * Handles map preintialize. Initializes the map center and zoom level. * * @param event The map event. */ private function onMapPreinitialize(event:MapEvent):void { setInitOptions(new MapOptions({ center: new LatLng(-26.1, 135.1), zoom: 4, viewMode: View.VIEWMODE_PERSPECTIVE, mapType:MapType.PHYSICAL_MAP_TYPE })); } /** * Handles map ready and looks up directions. * * @param event The map event. */ private function onMapReady(event:MapEvent):void { enableScrollWheelZoom(); enableContinuousZoom(); addControl(new NavigationControl()); // The driving animation will be updated on every frame. addEventListener(Event.ENTER_FRAME, enterFrame); addStartButton(); // We start the directions loading now, so that we&apos;re ready to go when // the user hits the start button. var directions:Directions = new Directions(); directions.addEventListener( DirectionsEvent.DIRECTIONS_SUCCESS, onDirectionsSuccess); directions.addEventListener( DirectionsEvent.DIRECTIONS_FAILURE, onDirectionsFailure); directions.load("48 Pirrama Rd, Pyrmont, NSW to Byron Bay, NSW"); } /** * Adds a big blue start button. */ private function addStartButton():void { startButton = new Sprite(); startButton.buttonMode = true; startButton.addEventListener(MouseEvent.CLICK, onStartClick); startButton.graphics.beginFill(0x1871ce); startButton.graphics.drawRoundRect(0, 0, 150, 100, 10, 10); startButton.graphics.endFill(); var startField:TextField = new TextField(); startField.autoSize = TextFieldAutoSize.LEFT; startField.defaultTextFormat = new TextFormat("_sans", 20, 0xffffff, true); startField.text = "Start!"; startButton.addChild(startField); startField.x = 0.5 * (startButton.width - startField.width); startField.y = 0.5 * (startButton.height - startField.height); startButton.filters = [ new DropShadowFilter() ]; var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.addChild(startButton); startButton.x = 0.5 * (container.width - startButton.width); startButton.y = 0.5 * (container.height - startButton.height); var panoField:TextField = new TextField(); panoField.autoSize = TextFieldAutoSize.LEFT; panoField.defaultTextFormat = new TextFormat("_sans", 11, 0x000000, true); panoField.text = "Photos provided by Panoramio are under the copyright of their owners."; container.addChild(panoField); panoField.x = container.width - panoField.width - 5; panoField.y = 5; } /** * Handles directions success. Starts flying the route if everything * is ready. * * @param event The directions event. */ private function onDirectionsSuccess(event:DirectionsEvent):void { directionsSuccessEvent = event; flyRouteIfReady(); } /** * Handles click on the start button. Starts flying the route if everything * is ready. */ private function onStartClick(event:MouseEvent):void { startButton.removeEventListener(MouseEvent.CLICK, onStartClick); var container:DisplayObjectContainer = getDisplayObject() as DisplayObjectContainer; container.removeChild(startButton); startButtonPressed = true; flyRouteIfReady(); } /** * If we have loaded the directions and the start button has been pressed * start flying the directions route. */ private function flyRouteIfReady():void { if (!directionsSuccessEvent || !startButtonPressed) { return; } var directions:Directions = directionsSuccessEvent.directions; // Extract the route. route = directions.getRoute(0); // Draws the polyline showing the route. polyline = directions.createPolyline(); addOverlay(directions.createPolyline()); // Creates a car marker that is moved along the route. var car:DisplayObject = new Car(); marker = new Marker(route.startGeocode.point, new MarkerOptions({ icon: car, iconOffset: new Point(-car.width / 2, -car.height) })); addOverlay(marker); transformPolyToWorld(); createCumulativeArrays(); // Load Panoramio data for the region covered by the route. loadPanoramioData(directions.bounds); var duration:Number = route.duration; // Start a timer that will trigger the car moving after the lead in time. var leadInTimer:Timer = new Timer(LEAD_IN_DURATION * 1000, 1); leadInTimer.addEventListener(TimerEvent.TIMER, onLeadInDone); leadInTimer.start(); var flyTime:Number = -LEAD_IN_DURATION; // Set up the camera flight trajectory. for each (var flyStep:Object in FLY_TRAJECTORY) { var time:Number = flyStep.fraction * duration; var center:LatLng = latLngAt(time); var scaledTime:Number = time * SCALE_TIME; var zoom:Number = flyStep.zoom; var attitude:Attitude = flyStep.attitude; var elapsed:Number = scaledTime - flyTime; flyTime = scaledTime; flyTo(center, zoom, attitude, elapsed); } } /** * Loads Panoramio data for the route bounds. We load data about more photos * than we need, then select a subset lying along the route. * @param bounds Bounds within which to fetch images. */ private function loadPanoramioData(bounds:LatLngBounds):void { var params:Object = { order: "popularity", set: "full", from: "0", to: NUM_GEOTAGGED_PHOTOS.toString(10), size: "small", minx: bounds.getWest(), miny: bounds.getSouth(), maxx: bounds.getEast(), maxy: bounds.getNorth() }; var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest( "http://www.panoramio.com/map/get_panoramas.php?" + paramsToString(params)); loader.addEventListener(Event.COMPLETE, onPanoramioDataLoaded); loader.addEventListener(IOErrorEvent.IO_ERROR, onPanoramioDataFailed); loader.load(request); } /** * Transforms the route polyline to world coordinates. */ private function transformPolyToWorld():void { var numVertices:int = polyline.getVertexCount(); worldPoly = new Array(numVertices); for (var i:int = 0; i < numVertices; ++i) { var vertex:LatLng = polyline.getVertex(i); worldPoly[i] = fromLatLngToPoint(vertex, 0); } } /** * Returns the time at which the route approaches closest to the * given point. * @param world Point in world coordinates. * @return Route time at which the closest approach occurs. */ private function getTimeOfClosestApproach(world:Point):Number { var minDistSqr:Number = Number.MAX_VALUE; var numVertices:int = worldPoly.length; var x:Number = world.x; var y:Number = world.y; var minVertex:int = 0; for (var i:int = 0; i < numVertices; ++i) { var dx:Number = worldPoly[i].x - x; var dy:Number = worldPoly[i].y - y; var distSqr:Number = dx * dx + dy * dy; if (distSqr < minDistSqr) { minDistSqr = distSqr; minVertex = i; } } return cumulativeVertexDistance[minVertex]; } /** * Returns the array index of the first element that compares greater than * the given value. * @param ordered Ordered array of elements. * @param value Value to use for comparison. * @return Array index of the first element that compares greater than * the given value. */ private function upperBound(ordered:Array, value:Number, first:int=0, last:int=-1):int { if (last < 0) { last = ordered.length; } var count:int = last - first; var index:int; while (count > 0) { var step:int = count >> 1; index = first + step; if (value >= ordered[index]) { first = index + 1; count -= step - 1; } else { count = step; } } return first; } /** * Selects up to a given number of photos approximately evenly spaced along * the route. * @param ordered Array of photos, each of which is an object with * a property &apos;closestTime&apos;. * @param number Number of photos to select. */ private function selectEvenlySpacedPhotos(ordered:Array, number:int):Array { var start:Number = cumulativeVertexDistance[0]; var end:Number = cumulativeVertexDistance[cumulativeVertexDistance.length - 2]; var closestTimes:Array = []; for each (var photo:Object in ordered) { closestTimes.push(photo.closestTime); } var selectedPhotos:Array = []; for (var i:int = 0; i < number; ++i) { var idealTime:Number = start + ((end - start) * (i + 0.5) / number); var index:int = upperBound(closestTimes, idealTime); if (index < 1) { index = 0; } else if (index >= ordered.length) { index = ordered.length - 1; } else { var errorToPrev:Number = Math.abs(idealTime - closestTimes[index - 1]); var errorToNext:Number = Math.abs(idealTime - closestTimes[index]); if (errorToPrev < errorToNext) { --index; } } selectedPhotos.push(ordered[index]); } return selectedPhotos; } /** * Handles completion of loading the Panoramio index data. Selects from the * returned photo indices a subset of those that lie along the route and * initiates load of each of these. * @param event Load completion event. */ private function onPanoramioDataLoaded(event:Event):void { var loader:URLLoader = event.target as URLLoader; var decoder:JSONDecoder = new JSONDecoder(loader.data as String); var allPhotos:Array = decoder.getValue().photos; for each (var photo:Object in allPhotos) { var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); photo.closestTime = getTimeOfClosestApproach(fromLatLngToPoint(latLng, 0)); } allPhotos.sortOn("closestTime", Array.NUMERIC); photos = selectEvenlySpacedPhotos(allPhotos, NUM_SHOWN_PHOTOS); for each (photo in photos) { var photoLoader:Loader = new Loader(); // The images aren&apos;t on panoramio.com: we can&apos;t acquire pixel access // using "new LoaderContext(true)". photoLoader.load( new URLRequest(photo.photo_file_url)); photo.loader = photoLoader; // Save the loader info: we use this to find the original element when // the load completes. photo.loaderInfo = photoLoader.contentLoaderInfo; photoLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, onPhotoLoaded); } } /** * Creates a MouseEvent listener function that will navigate to the given * URL in a new window. * @param url URL to which to navigate. */ private function createOnClickUrlOpener(url:String):Function { return function(event:MouseEvent):void { navigateToURL(new URLRequest(url)); }; } /** * Handles completion of loading an individual Panoramio image. * Adds a custom marker that displays the image. Initially this is made * invisible so that it can be faded in as needed. * @param event Load completion event. */ private function onPhotoLoaded(event:Event):void { var loaderInfo:LoaderInfo = event.target as LoaderInfo; // We need to find which photo element this image corresponds to. for each (var photo:Object in photos) { if (loaderInfo == photo.loaderInfo) { var imageMarker:Sprite = createImageMarker(photo.loader, photo.owner_name, photo.owner_url); var options:MarkerOptions = new MarkerOptions({ icon: imageMarker, hasShadow: true, iconAlignment: MarkerOptions.ALIGN_BOTTOM | MarkerOptions.ALIGN_LEFT }); var latLng:LatLng = new LatLng(photo.latitude, photo.longitude); var marker:Marker = new Marker(latLng, options); photo.marker = marker; addOverlay(marker); // A hack: we add the actual image after the overlay has been added, // which creates the shadow, so that the shadow is valid even if we // don&apos;t have security privileges to generate the shadow from the // image. marker.foreground.visible = false; marker.shadow.alpha = 0; var imageHolder:Sprite = new Sprite(); imageHolder.addChild(photo.loader); imageHolder.buttonMode = true; imageHolder.addEventListener( MouseEvent.CLICK, createOnClickUrlOpener(photo.photo_url)); imageMarker.addChild(imageHolder); return; } } trace("An image was loaded which could not be found in the photo array."); } /** * Creates a custom marker showing an image. */ private function createImageMarker(child:DisplayObject, ownerName:String, ownerUrl:String):Sprite { var content:Sprite = new Sprite(); var panoramioIcon:Bitmap = new PanoramioIcon(); var iconHolder:Sprite = new Sprite(); iconHolder.addChild(panoramioIcon); iconHolder.buttonMode = true; iconHolder.addEventListener(MouseEvent.CLICK, onPanoramioIconClick); panoramioIcon.x = BORDER_L; panoramioIcon.y = BORDER_T; content.addChild(iconHolder); // NOTE: we add the image as a child only after we&apos;ve added the marker // to the map. Currently the API requires this if it&apos;s to generate the // shadow for unprivileged content. // Shrink the image, so that it doesn&apos;t obcure too much screen space. // Ideally, we&apos;d subsample, but we don&apos;t have pixel level access. child.scaleX = IMAGE_SCALE; child.scaleY = IMAGE_SCALE; var imageW:Number = child.width; var imageH:Number = child.height; child.x = BORDER_L + 30; child.y = BORDER_T + iconHolder.height + GAP_T; var authorField:TextField = new TextField(); authorField.autoSize = TextFieldAutoSize.LEFT; authorField.defaultTextFormat = new TextFormat("_sans", 12); authorField.text = "author:"; content.addChild(authorField); authorField.x = BORDER_L; authorField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var ownerField:TextField = new TextField(); ownerField.autoSize = TextFieldAutoSize.LEFT; var textFormat:TextFormat = new TextFormat("_sans", 14, 0x0e5f9a); ownerField.defaultTextFormat = textFormat; ownerField.htmlText = "<a href=\"" + ownerUrl + "\" target=\"_blank\">" + ownerName + "</a>"; content.addChild(ownerField); ownerField.x = BORDER_L + authorField.width; ownerField.y = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B; var totalW:Number = BORDER_L + Math.max(imageW, ownerField.width + authorField.width) + BORDER_R; var totalH:Number = BORDER_T + iconHolder.height + GAP_T + imageH + GAP_B + ownerField.height + BORDER_B; content.graphics.beginFill(0xffffff); content.graphics.drawRoundRect(0, 0, totalW, totalH, 10, 10); content.graphics.endFill(); var marker:Sprite = new Sprite(); marker.addChild(content); content.x = 30; content.y = 0; marker.graphics.lineStyle(); marker.graphics.beginFill(0xff0000); marker.graphics.drawCircle(0, totalH + 30, 3); marker.graphics.endFill(); marker.graphics.lineStyle(2, 0xffffff); marker.graphics.moveTo(30 + 10, totalH - 10); marker.graphics.lineTo(0, totalH + 30); return marker; } /** * Handles click on the Panoramio icon. */ private function onPanoramioIconClick(event:MouseEvent):void { navigateToURL(new URLRequest(PANORAMIO_HOME)); } /** * Handles failure of a Panoramio image load. */ private function onPanoramioDataFailed(event:IOErrorEvent):void { trace("Load of image failed: " + event); } /** * Returns a string containing cgi query parameters. * @param Associative array mapping query parameter key to value. * @return String containing cgi query parameters. */ private static function paramsToString(params:Object):String { var result:String = ""; var separator:String = ""; for (var key:String in params) { result += separator + encodeURIComponent(key) + "=" + encodeURIComponent(params[key]); separator = "&"; } return result; } /** * Called once the lead-in flight is done. Starts the car driving along * the route and starts a timer to begin fade in of the Panoramio * images in 1.5 seconds. */ private function onLeadInDone(event:Event):void { // Set startTimer non-zero so that the car starts to move. startTimer = getTimer(); // Start a timer that will fade in the Panoramio images. var fadeInTimer:Timer = new Timer(1500, 1); fadeInTimer.addEventListener(TimerEvent.TIMER, onFadeInTimer); fadeInTimer.start(); } /** * Handles the fade in timer&apos;s TIMER event. Sets markerAlpha above zero * which causes the frame enter handler to fade in the markers. */ private function onFadeInTimer(event:Event):void { markerAlpha = 0.01; } /** * The end time of the flight. */ private function get endTime():Number { if (!cumulativeStepDuration || cumulativeStepDuration.length == 0) { return startTimer; } return startTimer + cumulativeStepDuration[cumulativeStepDuration.length - 1]; } /** * Creates the cumulative arrays, cumulativeStepDuration and * cumulativeVertexDistance. */ private function createCumulativeArrays():void { cumulativeStepDuration = new Array(route.numSteps + 1); cumulativeVertexDistance = new Array(polyline.getVertexCount() + 1); var polylineTotal:Number = 0; var total:Number = 0; var numVertices:int = polyline.getVertexCount(); for (var stepIndex:int = 0; stepIndex < route.numSteps; ++stepIndex) { cumulativeStepDuration[stepIndex] = total; total += route.getStep(stepIndex).duration; var startVertex:int = stepIndex >= 0 ? route.getStep(stepIndex).polylineIndex : 0; var endVertex:int = stepIndex < (route.numSteps - 1) ? route.getStep(stepIndex + 1).polylineIndex : numVertices; var duration:Number = route.getStep(stepIndex).duration; var stepVertices:int = endVertex - startVertex; var latLng:LatLng = polyline.getVertex(startVertex); for (var vertex:int = startVertex; vertex < endVertex; ++vertex) { cumulativeVertexDistance[vertex] = polylineTotal; if (vertex < numVertices - 1) { var nextLatLng:LatLng = polyline.getVertex(vertex + 1); polylineTotal += nextLatLng.distanceFrom(latLng); } latLng = nextLatLng; } } cumulativeStepDuration[stepIndex] = total; } /** * Opens the info window above the car icon that details the given * step of the driving directions. * @param stepIndex Index of the current step. */ private function openInfoForStep(stepIndex:int):void { // Sets the content of the info window. var content:String; if (stepIndex >= route.numSteps) { content = "<b>" + route.endGeocode.address + "</b>" + "<br /><br />" + route.summaryHtml; } else { content = "<b>" + stepIndex + ".</b> " + route.getStep(stepIndex).descriptionHtml; } marker.openInfoWindow(new InfoWindowOptions({ contentHTML: content })); } /** * Displays the driving directions step appropriate for the given time. * Opens the info window showing the step instructions each time we * progress to a new step. * @param time Time for which to display the step. */ private function displayStepAt(time:Number):void { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex >= 0 && stepIndex <= maxStepIndex && currentStepIndex != stepIndex) { openInfoForStep(stepIndex); currentStepIndex = stepIndex; } } /** * Returns the LatLng at which the car should be positioned at the given * time. * @param time Time for which LatLng should be found. * @return LatLng. */ private function latLngAt(time:Number):LatLng { var stepIndex:int = upperBound(cumulativeStepDuration, time) - 1; var minStepIndex:int = 0; var maxStepIndex:int = route.numSteps - 1; if (stepIndex < minStepIndex) { return route.startGeocode.point; } else if (stepIndex > maxStepIndex) { return route.endGeocode.point; } var stepStart:Number = cumulativeStepDuration[stepIndex]; var stepEnd:Number = cumulativeStepDuration[stepIndex + 1]; var stepFraction:Number = (time - stepStart) / (stepEnd - stepStart); var startVertex:int = route.getStep(stepIndex).polylineIndex; var endVertex:int = (stepIndex + 1) < route.numSteps ? route.getStep(stepIndex + 1).polylineIndex : polyline.getVertexCount(); var stepVertices:int = endVertex - startVertex; var stepLeng

    Read the article

  • How to use Devicemotion/Gyroscope to move a dot from center to 8 directions of iphone screen

    - by iSeeker
    I am trying to move a dot at center to 8 directions of iphone screen using Devicemotion such that it moves faster when tilted at a faster rate. Rough sketch is below: I could find a similar implementation in an app called Gyrododge in appstore, i cant figure out how to make it work... Update: This is what i have done so far, but the response is not smooth, and is very jittery.. xdiff and ydiff are the change of device attitude in x and y directions, derived from quatenion implementation. if (currDeviceMotion.rotationRate.x < -2) { NSLog(@"To Top"); if (195+800*ydiff >=193 && 195+800*ydiff <= 197) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (195+800*ydiff >=390 ) { [self.pitchDot setFrame:CGRectMake(150, 390, 20, 20)]; }else if (195+800*ydiff <= 0){ [self.pitchDot setFrame:CGRectMake(150, 0, 20, 20)]; }else if(195+800*ydiff < 194){ [self.pitchDot setFrame:CGRectMake(150, 195+800*ydiff, 20, 20)]; }else if(195+800*ydiff > 196){ [self.pitchDot setFrame:CGRectMake(150, 195+800*ydiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x > 2){ NSLog(@"To Bottom"); if (195+800*ydiff >=193 && 195+800*ydiff <= 197) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (195+800*ydiff >=390 ) { [self.pitchDot setFrame:CGRectMake(150, 390, 20, 20)]; }else if (195+800*ydiff <= 0){ [self.pitchDot setFrame:CGRectMake(150, 0, 20, 20)]; }else if(195+800*ydiff < 194){ [self.pitchDot setFrame:CGRectMake(150, 195+800*ydiff, 20, 20)]; }else if(195+800*ydiff > 196){ [self.pitchDot setFrame:CGRectMake(150, 195+800*ydiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.y < -2){ NSLog(@"To Left"); if (150+500*xdiff >= 148 && 150+500*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+500*xdiff >= 300 ) { [self.pitchDot setFrame:CGRectMake(300, 195, 20, 20)]; }else if (150+500*xdiff <= 0){ [self.pitchDot setFrame:CGRectMake(0, 195, 20, 20)]; }else if(150+500*xdiff < 148){ [self.pitchDot setFrame:CGRectMake(150+500*xdiff, 195, 20, 20)]; }else if(150+500*xdiff > 152){ [self.pitchDot setFrame:CGRectMake(150+500*xdiff, 195, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.y > 2){ NSLog(@"To Right"); if (150+500*xdiff >= 148 && 150+500*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+500*xdiff >= 300 ) { [self.pitchDot setFrame:CGRectMake(300, 195, 20, 20)]; }else if (150+500*xdiff <= 0){ [self.pitchDot setFrame:CGRectMake(0, 195, 20, 20)]; }else if(150+500*xdiff < 148){ [self.pitchDot setFrame:CGRectMake(150+500*xdiff, 195, 20, 20)]; }else if(150+500*xdiff > 152){ [self.pitchDot setFrame:CGRectMake(150+500*xdiff, 195, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x < -0.20 && currDeviceMotion.rotationRate.y > 0.20 ){ NSLog(@"To Diagonal Right Top"); if (150+650*xdiff >= 148 && 150+650*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+650*xdiff >= 300 ) { [self.pitchDot setFrame:CGRectMake(300, 0, 20, 20)]; }else if(150+650*xdiff > 152){ [self.pitchDot setFrame:CGRectMake(150+650*xdiff, 195-1.3*650*xdiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x > 0.20 && currDeviceMotion.rotationRate.y < -0.20 ){ NSLog(@"To Diagonal Left Bottom"); if (150+650*xdiff >= 148 && 150+650*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+650*xdiff <= 0 ) { [self.pitchDot setFrame:CGRectMake(0, 390, 20, 20)]; }else if(150+650*xdiff < 148){ [self.pitchDot setFrame:CGRectMake(150+650*xdiff, 195-1.3*650*xdiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x < -0.20 && currDeviceMotion.rotationRate.y < -0.20 ){ NSLog(@"To Diagonal Left Top and xdiff is %f",xdiff); if (150+650*xdiff >= 148 && 150+650*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+650*xdiff <= 0 ) { [self.pitchDot setFrame:CGRectMake(0, 0, 20, 20)]; }else if(150+650*xdiff < 148){ [self.pitchDot setFrame:CGRectMake(150+650*xdiff, 195+1.3*650*xdiff, 20, 20)]; } } }else if (currDeviceMotion.rotationRate.x > 0.20 && currDeviceMotion.rotationRate.y > 0.20 ){ NSLog(@"To Diagonal Right Bottom"); if (150+650*xdiff >= 148 && 150+650*xdiff <=152) { [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; }else{ if (150+650*xdiff >= 300 ) { [self.pitchDot setFrame:CGRectMake(300, 390, 20, 20)]; }else if(150+650*xdiff > 152){ [self.pitchDot setFrame:CGRectMake(150+650*xdiff, 195+1.3*650*xdiff, 20, 20)]; } } }else if((currDeviceMotion.rotationRate.x < 0.20 && currDeviceMotion.rotationRate.x < -0.20) ||(currDeviceMotion.rotationRate.y < 0.20 && currDeviceMotion.rotationRate.y < -0.20) ||(currDeviceMotion.rotationRate.z < 0.20 && currDeviceMotion.rotationRate.z < -0.20)){ [self.rollDot setFrame:CGRectMake(150, 195, 20, 20)]; [self.pitchDot setFrame:CGRectMake(150, 195, 20, 20)]; } It could be great if i could make it move like the application i have stated above, called Gyrododge This link also addresses a similar question:Link. Any advice or help is greatly appreciated... Thanks.

    Read the article

  • "Test to measure your ability to follow directions and solve complex problems in a neat and orderly manner." [closed]

    - by Matt
    Use the table of symbol substitutions when answering the problem below: Circle = 0 Dot = 1 Line = 2 Triangle = 3 Square = 4 Pentagon = 5 Hexagon = 6 Cross = 7 Heart = 8 Smiley Face = 9 Use the following special rule when answering the problem below: If ever a square is next to a cross during long multiplication, the square shall be treated as a triangle. Problem: Show your work in doing long multiplication of Pentagon Pentagon Nonagon by Line Square Octagon. Show your work using symbols not numbers.

    Read the article

  • car and cdr in scheme is driving me crazy ...

    - by kristian Roger
    Hi Im facing a probem with the car and cdr functions for example: first I defined a list caled it x (define x (a (bc) d ( (ef) g ) )) so x now is equal to (a (bc) d ( (ef) g ) now for example I need to get the g from this list using only car and cdr (!! noshortcuts as caddr cddr !!) the correct answer is: (car(cdr(car(cdr(cdr(cdr x)))))) BUT how ? :-( I work according to the rule (the car gives the head of list and cdr gives the tail) and instead of getting the answer above I keep reaching wronge answers can any one help me in understanding this ... give me step or a way to solve it step by step thanx in advance Im really sick of scheme language.

    Read the article

  • car and cdr in Scheme are driving me crazy ...

    - by kristian Roger
    Hi Im facing a problem with the car and cdr functions for example: first I defined a list called it x (define x (a (bc) d ( (ef) g ) )) so x now is equal to (a (bc) d ( (ef) g ) ) now for example I need to get the g from this list using only car and cdr (!! noshortcuts as caddr cddr !!) the correct answer is: (car(cdr(car(cdr(cdr(cdr x)))))) BUT how ? :-( I work according to the rules (the car gives the head of list and cdr gives the tail) and instead of getting the answer above I keep reaching wrong answers. Can any one help me in understanding this ... give me step or a way to solve it step by step Thanks in advance. I'm really sick of Scheme.

    Read the article

  • Does Oracle re-hash the driving table for each join on the same table columns?

    - by thecoop
    Say you've got the following query on 9i: SELECT /*+ USE_HASH(t2 t3) */ * FROM table1 t1 -- this has lots of rows LEFT JOIN table2 t2 ON t1.col1 = t2.col1 AND t1.col2 = t2.col2 LEFT JOIN table3 t3 ON t1.col1 = t3.col1 AND t1.col2 = t3.col2 Due to 9i not having RIGHT OUTER HASH JOIN, it needs to hash table1 for both joins. Does it re-hash table1 between joining t2 and t3 (even though it's using the same join columns), or does it keep the same hash information for both joins?

    Read the article

  • How to align Buttons in a TableLayout to different directions?

    - by Bevor
    Hello, probably I don't understand the layout properties of TableLayout yet. It doesn't seem to be possible to achieve such a flexible table like in HTML, because there are no cells. My target is it to achieve such a layout: Link to draft How can I do that? I thought about using a GridView but this doesn't seem to be useful in XML. My efforts look like this: <TableLayout android:id="@+id/tableLayout" android:layout_width="320sp" android:layout_height="fill_parent" android:layout_gravity="center_horizontal" android:gravity="bottom" android:layout_alignParentBottom="true"> <TableRow android:background="#333333" android:gravity="bottom" android:layout_width="fill_parent"> <Button android:id="@+id/btnUp" android:layout_width="60sp" android:layout_height="50sp" android:gravity="left" android:text="Lift U" /> <Button android:id="@+id/btnScreenUp" android:gravity="right" android:layout_gravity="right" android:layout_width="60sp" android:layout_height="50sp" android:text="Scrn U" /> </TableRow> <TableRow android:background="#444444" android:gravity="bottom" android:layout_gravity="right"> <Button android:id="@+id/btnDown" android:layout_width="60sp" android:layout_height="50sp" android:text="Lift D" /> <Button android:id="@+id/btnScreenLeft" android:layout_width="60sp" android:layout_height="50sp" android:gravity="right" android:layout_gravity="right" android:text="Scrn L" /> <Button android:id="@+id/btnScreenDown" android:layout_width="60sp" android:layout_height="50sp" android:gravity="right" android:layout_gravity="right" android:text="Scrn D" /> <Button android:id="@+id/btnScreenRight" android:layout_width="60sp" android:layout_height="50sp" android:gravity="right" android:layout_gravity="right" android:text="Scrn R" /> </TableRow> </TableLayout>

    Read the article

  • Converting "fr_FR" into "French (France)" in both directions. (Objective-C iPhone)

    - by Janice
    I can easily change a short region-code (en_US) into a longer string... but it there an easy way to also move in the other direction? [displayInEnglish displayNameForKey:NSLocaleIdentifier value:regionCountryCode]; "en_US" becomes "English (United States)". "English (United States)" becomes "en_US". I currently store the short region-code in a database.... but when I show some aggregate results... I need to display the longer strings to the user. Or should I just store the longer strings right in the database... and not even worry about "converting" them later? I'm trying to show a "dollars total" for each country. If you were a user... which would you more likely wish to see (for a currency-total list)? A "French" total A "France" total A "French (France)" total A "fr_Fr" total?

    Read the article

  • Directions and Opinions on Creating Update System for the Application.

    - by AlwaysBeCoding
    Hi people. I just try to figure out a good solution on designing the update process for a windows form application i created. I think of a button inside the app for manual checking of an update and checking when starting the app. Only I'm not familiar with technics. I though to have the update setup file in a FTP Server and checking the server for an update with a txt file in there with filename and version info. When app is finished downloading the update, closing and starting the update setup file. Any suggestions, opinions on the subject?

    Read the article

  • Is it possible to integrate Google Maps with the directions and the Transit layer into an iPhone app

    - by t4v
    Sorry if this question is obvious for some of you. I know we can link to the existing Goggle Maps app, but I would like to have an app that does not exit and provides the direction within. I intend using GTFS for public transit. On the other hand, would it be possible to plot a line inside the iPhone app the results as returned by Google Transit? (say, I send it the arrival and departure addresses) Thank you so much!

    Read the article

  • [Google Maps] Trouble with invalid argument when switching jQueryUI based tabs

    - by Chad
    Here's a page with the issue To reproduce the error, using IE - click the directions tab, then any of the others. What I'm trying to do is this: On page load, do nothing really. However, when the directions tab loads - setup the map. Like so: $('#tabs').bind('tabsshow', function(event, ui) { if (ui.panel.id == "tabs-5") { // get map for directions var dirMap = new GMap2($("div#dirMap").get(0)); dirMap.setCenter(new GLatLng(35.79648921414565,139.40663874149323), 12); dirMap.enableScrollWheelZoom(); dirMap.addControl(new PanoMapTypeControl()); geocoder = new GClientGeocoder(); $("#dirMap").resizable({ stop: function() { dirMap.checkResize(); } }); // clear dirText $("div#dirMapText").html(""); dirMap.clearOverlays(); var polygon = new GPolygon([new GLatLng(35.724496338474104,139.3444061279297),new GLatLng(35.74748750802863,139.3363380432129),new GLatLng(35.75765724051559,139.34303283691406),new GLatLng(35.76545779822543,139.3418312072754),new GLatLng(35.767547103447725,139.3476676940918),new GLatLng(35.75835374997911,139.34955596923828),new GLatLng(35.755149755962755,139.3567657470703),new GLatLng(35.74679090345495,139.35796737670898),new GLatLng(35.74762682821177,139.36294555664062),new GLatLng(35.744422402303826,139.36346054077148),new GLatLng(35.74860206266584,139.36946868896484),new GLatLng(35.735644401200986,139.36843872070312),new GLatLng(35.73843117306677,139.36174392700195),new GLatLng(35.73592308277646,139.3531608581543),new GLatLng(35.72686543236113,139.35298919677734),new GLatLng(35.724496338474104,139.3444061279297)], "#f33f00", 5, 1, "#ff0000", 0.2);dirMap.addOverlay(polygon); // load directions directions = new GDirections(dirMap, $("div#dirMapText").get(0)); directions.load("from: [email protected],139.37083393335342 to: Ruby [email protected],139.40663874149323"); } }); What the heck is causing the error? The IE javascript debugger claims the error lies in main.js, line 139 character 28. (the google maps api file). Which is this line: function zf(a,b){a=a.style;a.width=b.getWidthString();a.height=b.getHeightString()} Any ideas? Thanks in advance!

    Read the article

  • google maps call within a For Loop not returning distance

    - by Richard Reddy
    Hi, I am calling google maps within a for loop in my javascript as I have mulitple routes that need to be costed separately based on distances. Everything works great except that the distance is only returned for one of the routes. I have a feeling that it is something to do with the way I have the items declared within the ajax call for the maps. Any ideas what could be the issue from the code below? for (var i = 1; i <= numJourneys; i++) { var mapContainer = 'directionsMap' + i; var directionContainer = $('#getDistance' + i); $.ajax({ async: false, type: "POST", url: "Journey/LoadWayPoints", data: "{'args': '" + i + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { if (msg.d != '[]') { var map = new GMap2(document.getElementById(mapContainer)); var distance = directionContainer; var wp = new Array(); //routes var counter = 0; $.each(content, function () { wp[counter] = new GLatLng(this['Lat'], this['Long']); counter = counter + 1; }); map.clearOverlays(); map.setCenter(wp[0], 14); // load directions directions = new GDirections(map); GEvent.addListener(directions, "load", function () { alert(directions.getDistance()); //directionContainer.html(directions.getDistance().html); }); directions.loadFromWaypoints(wp, { getSteps: true }); } } }); }

    Read the article

  • 2D pathfinding - finding smooth paths

    - by Kooi Nam Ng
    I was trying to implement a simple pathfinding, but the outcome is less satisfactory than what I intended to achieve. The thing is units in games like Starcraft 2 move in all directions whereas units in my case only move in at most 8 directions (Warcraft 1 style) as these 8 directions direct to next available nodes (they move from a tile to next neighboring tile). What should I do in order to achieve the result as in Starcraft 2? Shrink the tile size? On the picture you can see a horizontal line of rock tiles being obstacles, and the found path marked as green tiles. The red line is the path I want to achieve.

    Read the article

  • DirectionsDistance in google maps API v3

    - by Yawn
    Hey, I'm trying to work out how to use this to get the distance from the successful directions: http://code.google.com/apis/maps/documentation/v3/reference.html#DirectionsDistance This is the code I have so far: var googleMaps = { // HTML Nodes fromInput: google_maps_from, toInput: google_maps_to, // API Objects dirService: new google.maps.DirectionsService(), dirRenderer: new google.maps.DirectionsRenderer(), map: null, showDirections: function(dirResult, dirStatus) { if (dirStatus != google.maps.DirectionsStatus.OK) { //Here we'll handle the errors a bit better :P alert('Directions failed: ' + dirStatus); return; } else { //Get the distance here //onGDirectionsLoad(); } // Show directions googleMaps.dirRenderer.setMap(googleMaps.map); googleMaps.dirRenderer.setPanel(document.getElementById("directions")); googleMaps.dirRenderer.setDirections(dirResult); }, getSelectedTravelMode: function() { return google.maps.DirectionsTravelMode.DRIVING; }, getSelectedUnitSystem: function() { return google.maps.DirectionsUnitSystem.METRIC; }, getDirections: function() { var fromStr = googleMaps.fromInput; var toStr = googleMaps.toInput; var dirRequest = { origin: fromStr, destination: toStr, travelMode: googleMaps.getSelectedTravelMode(), unitSystem: googleMaps.getSelectedUnitSystem(), provideTripAlternatives: true }; googleMaps.dirService.route(dirRequest, googleMaps.showDirections); }, init: function() { googleMaps.map = new google.maps.Map(document.getElementById("map_canvas"), { zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }); // Show directions onload googleMaps.getDirections(); } }; // Onload handler to fire off the app. google.maps.event.addDomListener(window, 'load', googleMaps.init); I could do this just fine in v2, just having trouble working out the v3 equivalent :x

    Read the article

  • Trigger event after GDirections.loadFromWaypoints in Google Maps API

    - by Soldarnal
    I'm attempting to add some text to the directions results the Google Maps API returns to the specified div (directionsPanel). This code below would work fine, except that the jQuery line fires before loadFromWaypoints has finished modifying the DOM. If I run that line by manually triggering it after the directions content has finished loading, it executes as expected. directions = new GDirections(map, directionsPanel); directions.loadFromWaypoints(waypoints); $("td[@jscontent='address']").append(" some content"); How can I add some sort of listener (on perhaps either the loadFromWaypoints callback function or the directionsPanel div itself) to execute my jQuery line after the DOM has finished reloading?

    Read the article

  • next line character a huge influence on xmlparser?

    - by jovany
    I have question about a basic xml file I'm parsing and just putting in simple nextlines(Enters). I'll try to explain my problem with this next example. I'm( still) building an xml tree and all it has to do ( this is a testtree ) is put the summary in an itemlist. I then export it to a plist so I can see if everything is done correctly. A method that does this is in the parser which looks like this if([elementName isEqualToString:@"Book"]) { [appDelegate.books addObject:aBook]; [aBook release]; aBook = nil; } else { [aBook setValue:currentElementValue forKey:elementName]; NSString *directions = [NSString stringWithFormat:currentElementValue]; [directionTree = setObject:directions forKey:@"directions"]; } [currentElementValue release]; currentElementValue = nil; } the export for the plistfile happens at the endtag of books. Below is the first xmlfile <?xml version="1.0" encoding="UTF-8"?> <Books><Book id="1"><summary>Ero adn the ancient quest to measure the globe.</summary></Book><Book id="2"><summary>how the scientific revolution began.</summary></Book></Books> This is my output http://img139.imageshack.us/img139/9175/picture6rtn.png If I make some adjustments like here <?xml version="1.0" encoding="UTF-8"?> <Books><Book id="1"> <summary>Ero adn the ancient quest to measure the globe.</summary> </Book> <Book id="2"> <summary>how the scientific revolution began.</summary> </Book> </Books> My directions key with type string remains empty... http://img248.imageshack.us/img248/5838/picture7y.png I never knew that if I just put in an enter it would have such an influence. Does anyone know a solution to this since my real xml file looks like this. ps. the funny thing is I can actually see ( when debugging)my directions string (NSString directions ) fill up with the currentElementValue in both cases.

    Read the article

  • Why wont my while loop take new input (c++)

    - by Van
    I've written a program to get a string input from a user and parse it into tokens and move a robot according to the input. My problem is trying to issue more than one command. The code looks like: void Navigator::manualDrive() { const int bufSize = 42; char uinput[bufSize]; char delim[] = " "; char *token; while(true) { Navigator::parseInstruction(uinput); } } /* parseInstruction(char *c) -- parses cstring instructions received * and moves robot accordingly */ void Navigator::parseInstruction(char * c) { const int bufSize = 42; char uinput[bufSize]; char delim[] = " "; char *token; cout << "Enter your directions below: \n"; cin.ignore(); cin.getline (uinput, bufSize); token=strtok(uinput, delim); if(strcmp("forward", token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); Navigator::travel(inches); } if(strcmp("back",token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); double value = fabs(0.0735 * fabs(inches) - 0.0550); myRobot.backward(1/*speed*/, value/*time*/); } if(strcmp("turn",token) == 0) { int degrees; token = strtok(NULL, delim); if(strcmp("left",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.0041 * degrees - 0.0523); myRobot.turnLeft(1/*speed*/, value/*time*/); } } if(strcmp("turn",token) == 0) { int degrees; token = strtok(NULL, delim); if(strcmp("right",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.0041 * degrees - 0.0523); myRobot.turnRight(1/*speed*/, value/*time*/); } } if(strcmp("stop",token) == 0) { myRobot.motors(0,0); } } In the function manualDrive I have a while loop calling the function parseInstruction infinitely. The program outputs "Enter your directions below: " When I give the program instructions it executes them, and then it outputs "enter your directions below: " again and when I input my directions again it does not execute them and outputs "Enter your directions below: " instead. I'm sure this is a very simple fix I'm just very new to c++. So if you could please help me out and tell me why the program only takes the first set of directions. thanks

    Read the article

  • Why wont my while loop wont take new input (c++)

    - by Van
    I've written a program to get a string input from a user and parse it into tokens and move a robot according to the input. My problem is trying to issue more than one command. The code looks like: void Navigator::manualDrive() { const int bufSize = 42; char uinput[bufSize]; char delim[] = " "; char *token; while(true) { Navigator::parseInstruction(uinput); } } /* parseInstruction(char *c) -- parses cstring instructions received * and moves robot accordingly */ void Navigator::parseInstruction(char * c) { const int bufSize = 42; char uinput[bufSize]; char delim[] = " "; char *token; cout << "Enter your directions below: \n"; cin.ignore(); cin.getline (uinput, bufSize); token=strtok(uinput, delim); if(strcmp("forward", token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); Navigator::travel(inches); } if(strcmp("back",token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); double value = fabs(0.0735 * fabs(inches) - 0.0550); myRobot.backward(1/*speed*/, value/*time*/); } if(strcmp("turn",token) == 0) { int degrees; token = strtok(NULL, delim); if(strcmp("left",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.0041 * degrees - 0.0523); myRobot.turnLeft(1/*speed*/, value/*time*/); } } if(strcmp("turn",token) == 0) { int degrees; token = strtok(NULL, delim); if(strcmp("right",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.0041 * degrees - 0.0523); myRobot.turnRight(1/*speed*/, value/*time*/); } } if(strcmp("stop",token) == 0) { myRobot.motors(0,0); } } In the function manualDrive I have a while loop calling the function parseInstruction infinitely. The program outputs "Enter your directions below: " When I give the program instructions it executes them, and then it outputs "enter your directions below: " again and when I input my directions again it does not execute them and outputs "Enter your directions below: " instead. I'm sure this is a very simple fix I'm just very new to c++. So if you could please help me out and tell me why the program only takes the first set of directions. thanks

    Read the article

  • different for lusses java

    - by Ayrton
    Hi I'm having some difficulties with the following problem: I'm making a little game where you're at a specific spot and each spot has each some possible directions. The available directions are N(ord),E(ast),S,W . I use the function getPosDirections to get the possible directions of that spot. The function returns the directions into an ArrayList e.g. for spot J3: [E,W] Now the game goes like this: 2 dices will be rolled so you get a number between 2 and 12, this number represents the number of steps you can make. What I want is an ArrayList of all the possible routes e.g.: I throw 3 and I'm currently at spot J3: [[E,N,E],[E,N,S],[E,S,E],[E,S,S],[W,N,E],[W,N,S],[W,S,E],[W,S,S]] How would obtain the last mentioned Array(list) Thanks in advance

    Read the article

  • different for loops java

    - by Ayrton
    I'm having some difficulties with the following problem: I'm making a little game where you're at a specific spot and each spot has each some possible directions. The available directions are N(ord),E(ast),S,W . I use the function getPosDirections to get the possible directions of that spot. The function returns the directions into an ArrayList<String> e.g. for spot J3: [E,W] Now the game goes like this: 2 dice will be rolled so you get a number between 2 and 12, this number represents the number of steps you can make. What I want is an ArrayList of all the possible routes e.g.: I throw 3 and I'm currently at spot J3: [[E,N,E],[E,N,S],[E,S,E],[E,S,S],[W,N,E],[W,N,S],[W,S,E],[W,S,S]] How would obtain the last mentioned Array(list)?

    Read the article

  • Passing GLatLng from array to Google

    - by E. Rose
    Hello All, To preface this, I am a complete programming amateur so this may be quite easily solved. As is though, it is frustrating me to no end. Basically, I have a database of Venue Names with GLat and GLng (other stuff too) that I am pulling down to my website based on a geolocated search. The javascript that I have pulls in a formatted subset of the database, dumps the glat and glng into an array and is supposed to take those points and plot out several markers each with an info window containing the details behind each marker. For some reason, the marker geodata is not being populated and/or is not being passed. The array is declared using [] and will not work when normally declared using (). It only brings up a map with the first value in the array and goes blank if i try to manually input later entries. There is a large block of commented out code relating to directions generation. That code worked for some reason. If anyone can tell me what I am doing wrong in rewriting it to map the markers and not give directions, please tell me. Any help would be much appreciated. var letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; google.load("maps", "2", {"other_params":"sensor=true"}); var map function initialize(){ window.map = new google.maps.Map2(document.getElementById("map")); map.addControl(new GLargeMapControl()); } google.setOnLoadCallback(initialize); function getVenueResults(_zip, _num, _remove){ var rFlag = ''; if(_remove != null){ rFlag = "&removeId=" + _remove; } var url = 'ajax/getVenues.php?zip=' + _zip + "&num=" + _num + rFlag; new Ajax.Updater('resultsContainer', url, { onComplete: processResults }); } function processResults(){ window.map.clearOverlays(); var waypoints = []; var resultsList = $$('.resultWrapper'); var stepList = $$('.resultDirections'); for(i=0; i for(i=0; i<resultsList.length; i++){ var resultsElem = resultsList[i]; resultsElem.removeClassName('firstResult'); resultsElem.removeClassName('lastResult'); if(i == 0){ resultsElem.addClassName('firstResult'); } if(i == resultsList.length - 1){ resultsElem.addClassName('lastResult'); } var insertContent = '<div class="resultDirections" id="resultDirections' + i + '"></div>'; Element.insert(resultsElem, { bottom : insertContent }) var num = resultsElem.getElementsByClassName('numHolder'); num[0].innerHTML = '<b>' + letters[i] + ".</b> "; var geolat = resultsElem.getElementsByClassName('geolat')[0].value; var geolong = resultsElem.getElementsByClassName('geolong')[0].value; var point = new GLatLng(geolat, geolong); waypoints[i] = point; } if(waypoints.length == 1){ map.setCenter(waypoints[0], 16); map.addOverlay(new GMarker(waypoints[0])); resultsElem.getElementsByClassName('numHolder')[0].innerHTML = ''; }else{ map.setCenter(waypoints[0], 16); for(j=0; j< waypoints.length; j++) { var vLoc = waypoints[j]; var vInfo = resultsElem.getElementByClassName('resultBox[j]]').innerHTML; //unfinished function to mine name out of div and make it the marker title //x = resultsElem.getElementsByTagName("b"); // for (i=0;i<x.length;i++) // //marker.value = resultsElem.getElementBy('numHolder').innerHTML var marker = createMarker(vLoc, vInfo); map.addOverlay(marker); } } function createMarker(vLoc, vInfo) { var marker = (new GMarker(vLoc)); var cont = vInfo; GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(cont); }); return marker; } //var directions = new GDirections(window.map, document.getElementById('directionsPanel')); //directions.loadFromWaypoints(waypoints, { travelMode: G_TRAVEL_MODE_WALKING }); //GEvent.addListener(directions, "load" , function() { // var numRoutes = directions.getNumRoutes(); // for(j=0; j< numRoutes; j++){ // var thisRoute = directions.getRoute(j); // var routeText = ''; // for(k=0; k < thisRoute.getNumSteps(); k++){ // var thisStep = thisRoute.getStep(k); // if(k != 0){ routeText += " &nbsp;||&nbsp; "; } // routeText += thisStep.getDescriptionHtml(); // } // $('resultDirections' + j).innerHTML = routeText; // } // $('resultDirections' + numRoutes).hide(); //}); } function moveUp(_obj){ var parentObj = $(_obj).up().up(); var prevSib = parentObj.previous(); prevSib.insert({before: parentObj}); processResults(); } function moveDown(_obj){ var parentObj = $(_obj).up().up(); var nextSib = parentObj.next(); nextSib.insert({after: parentObj}); processResults(); }

    Read the article

  • Prevent oversteering catastrophe in racing games

    - by jdm
    When playing GTA III on Android I noticed something that has been annoying me in almost every racing game I've played (maybe except Mario Kart): Driving straight ahead is easy, but curves are really hard. When I switch lanes or pass somebody, the car starts swiveling back and forth, and any attempt to correct it makes it only worse. The only thing I can do is to hit the brakes. I think this is some kind of oversteering. What makes it so irritating is that it never happens to me in real life (thank god :-)), so 90% of the games with vehicles inside feel unreal to me (despite probably having really good physics engines). I've talked to a couple of people about this, and it seems either you 'get' racing games, or you don't. With a lot of practice, I did manage to get semi-good at some games (e.g. from the Need for Speed series), by driving very cautiously, braking a lot (and usually getting a cramp in my fingers). What can you do as a game developer to prevent the oversteering resonance catastrophe, and make driving feel right? (For a casual racing game, that doesn't strive for 100% realistic physics) I also wonder what games like Super Mario Kart exactly do differently so that they don't have so much oversteering? I guess one problem is that if you play with a keyboard or a touchscreen (but not wheels and pedals), you only have digital input: gas pressed or not, steering left/right or not, and it's much harder to steer appropriately for a given speed. The other thing is that you probably don't have a good sense of speed, and drive much faster than you would (safely) in reality. From the top of my head, one solution might be to vary the steering response with speed.

    Read the article

  • snapping an angle to the closest cardinal direction

    - by Josh E
    I'm developing a 2D sprite-based game, and I'm finding that I'm having trouble with making the sprites rotate correctly. In a nutshell, I've got spritesheets for each of 5 directions (the other 3 come from just flipping the sprite horizontally), and I need to clamp the velocity/rotation of the sprite to one of those directions. My sprite class has a pre-computed list of radians corresponding to the cardinal directions like this: protected readonly List<float> CardinalDirections = new List<float> { MathHelper.PiOver4, MathHelper.PiOver2, MathHelper.PiOver2 + MathHelper.PiOver4, MathHelper.Pi, -MathHelper.PiOver4, -MathHelper.PiOver2, -MathHelper.PiOver2 + -MathHelper.PiOver4, -MathHelper.Pi, }; Here's the positional update code: if (velocity == Vector2.Zero) return; var rot = ((float)Math.Atan2(velocity.Y, velocity.X)); TurretRotation = SnapPositionToGrid(rot); var snappedX = (float)Math.Cos(TurretRotation); var snappedY = (float)Math.Sin(TurretRotation); var rotVector = new Vector2(snappedX, snappedY); velocity *= rotVector; //...snip private float SnapPositionToGrid(float rotationToSnap) { if (rotationToSnap == 0) return 0.0f; var targetRotation = CardinalDirections.First(x => (x - rotationToSnap >= -0.01 && x - rotationToSnap <= 0.01)); return (float)Math.Round(targetRotation, 3); } What am I doing wrong here? I know that the SnapPositionToGrid method is far from what it needs to be - the .First(..) call is on purpose so that it throws on no match, but I have no idea how I would go about accomplishing this, and unfortunately, Google hasn't helped too much either. Am I thinking about this the wrong way, or is the answer staring at me in the face?

    Read the article

  • LinearLayout - How to get text to be on the right of an icon?

    - by RED_
    Hi there, Bit of a newbie when it comes to android, only been working on it properly for a few days but even after all the searching I've done im stumped and nobody seems to know how to help me. I have this so far: http://img263.imageshack.us/i/sellscreen.jpg How can I move the text to be besides each icon rather than underneath it? Hoping the gallery won't be moved either. Here is the code i have: <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Gallery xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions." /> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions."/> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions."/> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions."/> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions." /> </LinearLayout> </ScrollView> Top half of my code doesn't seem to be showing for some reason but it's just the opening of the linear layout. I will be forever grateful to anyone that can help, i've been racking my brains for days and getting nowhere. Really getting stressed out by it. Thanks in advance!!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >