Search Results

Search found 1322 results on 53 pages for 'euclidean distance'.

Page 8/53 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • [UIView didCreateWorkout:Type:Distance:Time:Message:]: unrecognized selector sent to instance.

    - by Stephen
    Hello, I'm getting the above error and have been looking at it all day, I'm getting no where fast. Anyone any ideas ? I'm new to IPhone Development. Code Below: #import "WorkoutViewController.h" #import "Workout.h" @implementation WorkoutViewController @synthesize workoutDelegate; //@synthesize Speed; //@synthesize Calories; @synthesize route; @synthesize type; @synthesize distance; @synthesize time; @synthesize message; @synthesize DBContents; @synthesize workoutArray; @synthesize managedObjectContext; //@synthesize saveWorkout; //@synthesize cancelWorkout; -(IBAction)hideKeyboard { } -(IBAction)saveWorkout { [workoutDelegate didCreateWorkout: route.text Type: type.text Distance: distance.text Time: time.text Message: message.text]; } -(IBAction)cancelWorkout { [self.workoutDelegate didCancelWorkout]; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -(void)viewDidLoad { //Set images for Save & Cancel buttons. UIImage *normalImage = [[UIImage imageNamed:@"whiteButton.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0]; [saveWorkout setBackgroundImage:normalImage forState:UIControlStateNormal]; [cancelWorkout setBackgroundImage:normalImage forState:UIControlStateNormal]; UIImage *pressedImage = [[UIImage imageNamed:@"blueButton.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0]; [saveWorkout setBackgroundImage:pressedImage forState:UIControlStateHighlighted]; [cancelWorkout setBackgroundImage:pressedImage forState:UIControlStateHighlighted]; //Fetch details from the database. NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Workout" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; NSError *error; self.workoutArray = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; [request release]; //self.workoutArray = [[NSMutableArray alloc] init]; //self.DBContents.text = [self.workoutArray objectAtIndex:0]; [super viewDidLoad]; } -(void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } -(void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } -(void) didCreateWorkout:(NSString *)thisRoute Type:(NSString *)thisType Distance:(NSString *)thisDistance Time:(NSString *)thisTime Message:(NSString *)thisMessage { // Add the new workout. Workout *newWorkout = [NSEntityDescription insertNewObjectForEntityForName:@"Workout" inManagedObjectContext:self.managedObjectContext]; newWorkout.route = thisRoute; newWorkout.type = thisType; newWorkout.distance = thisDistance; newWorkout.time = thisTime; newWorkout.message = thisMessage; [self.workoutArray addObject:newWorkout]; //[self dismissModalViewControllerAnimated:YES]; } -(void)didCancelWorkout { [self dismissModalViewControllerAnimated:YES]; } -(void)dealloc { // [Speed release]; // [Calories release]; [route release]; [type release]; [distance release]; [time release]; [message release]; // [saveWorkout release]; // [cancelWorkout release]; [workoutArray release]; [managedObjectContext release]; [super dealloc]; } @end I'm trying to save details that I key on the screen (WorkoutViewController.xib) and I click the save button and get the above error. Thanks Stephen

    Read the article

  • This code is of chess game. What is represented by 'DISTANCE' in code? [closed]

    - by rajeshverma423
    package chess; public class Evaluate { public static final int PIECE_KING = 0; public static final int PIECE_QUEEN = 1; public static final int PIECE_ROOK = 2; public static final int PIECE_BISHOP = 3; public static final int PIECE_KNIGHT = 4; public static final int PIECE_PAWN = 5; public static final int FULL_BIT_RANK = 4080; public static final int LAZY_MARGIN = 100; public static final int ISOLATED_PENALTY = 10; public static final int DOUBLE_PENALTY = 4; public static final int[] PIECE_VALUE = { 0, 9, 5, 3, 3, 1 }; public static final int[] PASS_PAWN = { 0, 35, 30, 20, 10, 5 }; public static final byte[] DISTANCE = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 0, 0, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7 };

    Read the article

  • In a graph, how to find the nearest node to a group of nodes?

    - by Nikola
    Hello, I have an undirected, unweighted graph, which doesn't have to be planar. I also have a subset of graph's nodes (true subset) and I need to find a node not belonging to the subset, with minimum sum of distances to all nodes in the subset. So far, I have implemented breath-first search starting from each node in the subset, and the intersection that occurs first is the node I am looking for. Unfortunately, it is running too slow since the graph contains a large number of nodes. Any advice or comment will be appreciated. Thank you, Nikola

    Read the article

  • how do I make my submenu position dynamic based on the distance to the edge of the window?

    - by Mario Antoci
    I'm trying to write a jQuery script that will find the distance to the right edge of the browser window from my css class element and then position the child submenu dropdowns to the right or left depending on the available space to the right. Also it needs to revert to the default settings on hoverout. Here is what I have so far but it's not calculating properly. $(document).ready(function(){ $('#dnnMenu .subLevel').hover(function(){ if ($(window).width() - $('#dnnMenu .subLevel').offset().left - '540' >= '270') { $('#dnnMenu .subLevelRight').css('left', '270px');} else {$('#dnnMenu .subLevelRight').css('left', '-270px');} }); $(document).ready(function () { function HoverOver() { $(this).addClass('hover'); } function HoverOut() { $(this).removeClass('hover'); } var config = { sensitivity: 2, interval: 100, over: HoverOver, timeout: 100, out: HoverOut }; $("#dnnMenu .topLevel > li.haschild").hoverIntent(config); $(".subLevel li.haschild").hover(HoverOver, HoverOut); }); Basically I tried to take the width of the current window, minus the distance to the left edge of the browser of the first level submenu, minus the width of both elements together which would equal 540px, to calculate the distance to the right edge of the window when the first level submenu is hovered over. if the distance to the right of my first level submenu element is less than 540px then the second level sub menu css property is changed to position to the left instead of right. I also know that it needs to revert back to default after hover out so it can recalculate the distance from other positions within the menu structure and still have those second level submenus with enough room to still display on the right of the first level. here is css for the elements in question. #dnnMenu .subLevel{ display: none; position: absolute; margin: 0; z-index: 1210; background: #639ec8; text-transform: none;} #dnnMenu .subLevelRight{ position: absolute; display: none; left: 270px; top: 0px;} The site's not live yet and I tried to create a jsfiddle but it doesn't look right. Any help would be greatly appreciated! Best Regards, Mario

    Read the article

  • Find the closest locations to a given address

    - by xtine
    I have built an application in CakePHP that lists businesses. There are about 2000 entries, and the latitude and longitude coordinates for each business is in the DB. I now am trying to tackle the search function. There will be an input box where the user can put a street address, city, or zipcode, and then I would like it to return the 11 closest businesses as found from the database. How would I go about doing this?

    Read the article

  • Querying a perimeter around a Geocode-Location (Lat/Lon)

    - by Tim
    Hi, how can I search for geo-objects in a certain perimeter ? E.g. I have several objects with Lat/Lon coordinates stored in my DB. Now I want to retrieve all the objects which lie in a specific perimeter (10 miles or 20 miles) around a given point. I guess what I would have to do is to form some query like: SELECT * FROM objects o where o.lat < (myPositionLat+x) AND o.lon < (myPositionLon+y) Is this right? How do I determine/set the values for x and y?

    Read the article

  • Vacuum spread in a tile-based space game (like in Faster Than Light game)

    - by Reeze
    I've a space game with tilemap that looks like this (simplified): Map view - from top (like in SimCity 1) 0 - room space, 1 - some kind of wall, 8 - "lock" beetween rooms public int[,] _layer = new int[,] { { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 1, 1, 8, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 1, 0, 8, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, }; Each tile contains Air property (100 = air, 0 = vacuum). I made a little helper method to take tiles near tile with vacuum (to "suck air"): Point[] GetNearCells(Point cell, int distance = 1, bool diag = false) { Point topCell = new Point(cell.X, cell.Y - distance); Point botCell = new Point(cell.X, cell.Y + distance); Point leftCell = new Point(cell.X - distance, cell.Y); Point rightCell = new Point(cell.X + distance, cell.Y); if (diag) { return new[] { topCell, botCell, leftCell, rightCell }; } Point topLeftCell = new Point(cell.X - distance, cell.Y - distance); Point topRightCell = new Point(cell.X + distance, cell.Y + distance); Point botLeftCell = new Point(cell.X - distance, cell.Y - distance); Point botRightCell = new Point(cell.X - distance, cell.Y - distance); return new[] { topCell, botCell, leftCell, rightCell, topLeftCell, topRightCell, botLeftCell, botRightCell }; } What is the best practice to fill rooms with vacuum (decrease air) from some point? Should i use some kind of water flow? Thank you for any help!

    Read the article

  • 2D Game: Fast(est) way to find x closest entities for another entity - huge amount of entities, high

    - by Pygmy
    I'm working on a 2D game that has a huge amount of dynamic entities. For fun's sake, let's call them soldiers, and let's say there are 50000 of them (which I just randomly thought up, it might be much more or much less :)). All these soldiers are moving every frame according to rules - think boids / flocking / steering behaviour. For each soldier, to update it's movement I need the X soldiers that are closest to the one I'm processing. What would be the best spatial hierarchy to store them to facilitate calculations like this without too much overhead ? (All entities are updated/moved every frame, so it has to handle dynamic entities very well)

    Read the article

  • Fastest pathfinding for static node matrix

    - by Sean Martin
    I'm programming a route finding routine in VB.NET for an online game I play, and I'm searching for the fastest route finding algorithm for my map type. The game takes place in space, with thousands of solar systems connected by jump gates. The game devs have provided a DB dump containing a list of every system and the systems it can jump to. The map isn't quite a node tree, since some branches can jump to other branches - more of a matrix. What I need is a fast pathfinding algorithm. I have already implemented an A* routine and a Dijkstra's, both find the best path but are too slow for my purposes - a search that considers about 5000 nodes takes over 20 seconds to compute. A similar program on a website can do the same search in less than a second. This website claims to use D*, which I have looked into. That algorithm seems more appropriate for dynamic maps rather than one that does not change - unless I misunderstand it's premise. So is there something faster I can use for a map that is not your typical tile/polygon base? GBFS? Perhaps a DFS? Or have I likely got some problem with my A* - maybe poorly chosen heuristics or movement cost? Currently my movement cost is the length of the jump (the DB dump has solar system coordinates as well), and the heuristic is a quick euclidean calculation from the node to the goal. In case anyone has some optimizations for my A*, here is the routine that consumes about 60% of my processing time, according to my profiler. The coordinateData table contains a list of every system's coordinates, and neighborNode.distance is the distance of the jump. Private Function findDistance(ByVal startSystem As Integer, ByVal endSystem As Integer) As Integer 'hCount += 1 'If hCount Mod 0 = 0 Then 'Return hCache 'End If 'Initialize variables to be filled Dim x1, x2, y1, y2, z1, z2 As Integer 'LINQ queries for solar system data Dim systemFromData = From result In jumpDataDB.coordinateDatas Where result.systemId = startSystem Select result.x, result.y, result.z Dim systemToData = From result In jumpDataDB.coordinateDatas Where result.systemId = endSystem Select result.x, result.y, result.z 'LINQ execute 'Fill variables with solar system data for from and to system For Each solarSystem In systemFromData x1 = (solarSystem.x) y1 = (solarSystem.y) z1 = (solarSystem.z) Next For Each solarSystem In systemToData x2 = (solarSystem.x) y2 = (solarSystem.y) z2 = (solarSystem.z) Next Dim x3 = Math.Abs(x1 - x2) Dim y3 = Math.Abs(y1 - y2) Dim z3 = Math.Abs(z1 - z2) 'Calculate distance and round 'Dim distance = Math.Round(Math.Sqrt(Math.Abs((x1 - x2) ^ 2) + Math.Abs((y1 - y2) ^ 2) + Math.Abs((z1 - z2) ^ 2))) Dim distance = firstConstant * Math.Min(secondConstant * (x3 + y3 + z3), Math.Max(x3, Math.Max(y3, z3))) 'Dim distance = Math.Abs(x1 - x2) + Math.Abs(z1 - z2) + Math.Abs(y1 - y2) 'hCache = distance Return distance End Function And the main loop, the other 30% 'Begin search While openList.Count() != 0 'Set current system and move node to closed currentNode = lowestF() move(currentNode.id) For Each neighborNode In neighborNodes If Not onList(neighborNode.toSystem, 0) Then If Not onList(neighborNode.toSystem, 1) Then Dim newNode As New nodeData() newNode.id = neighborNode.toSystem newNode.parent = currentNode.id newNode.g = currentNode.g + neighborNode.distance newNode.h = findDistance(newNode.id, endSystem) newNode.f = newNode.g + newNode.h newNode.security = neighborNode.security openList.Add(newNode) shortOpenList(OLindex) = newNode.id OLindex += 1 Else Dim proposedG As Integer = currentNode.g + neighborNode.distance If proposedG < gValue(neighborNode.toSystem) Then changeParent(neighborNode.toSystem, currentNode.id, proposedG) End If End If End If Next 'Check to see if done If currentNode.id = endSystem Then Exit While End If End While If clarification is needed on my spaghetti code, I'll try to explain.

    Read the article

  • Collisions not working as intended

    - by Stan
    I'm making a game, it's a terraria-like game, with 20x20 blocks, and you can place and remove those blocks. Now, I am trying to write collisions, but it isn't working as I want, the collision succesfully stops the player from going through the ground, but, when I press a key like A + S, that means if I walk down and left (Noclip is on atm), my player will go into the ground, bug up, and exit the ground somewhere else in the level. I made a video of it. The red text means which buttons I am pressing. http://www.youtube.com/watch?v=mo4frZyNwOs You see, if I press A and S together, I go into the ground. Here is my collision code: Vector2 collisionDist, normal; private bool IsColliding(Rectangle body1, Rectangle body2) { normal = Vector2.Zero; Vector2 body1Centre = new Vector2(body1.X + (body1.Width / 2), body1.Y + (body1.Height / 2)); Vector2 body2Centre = new Vector2(body2.X + (body2.Width / 2), body2.Y + (body2.Height / 2)); Vector2 distance, absDistance; float xMag, yMag; distance = body1Centre - body2Centre; float xAdd = ((body1.Width) + (body2.Width)) / 2.0f; float yAdd = ((body1.Height) + (body2.Height)) / 2.0f; absDistance.X = (distance.X < 0) ? -distance.X : distance.X; absDistance.Y = (distance.Y < 0) ? -distance.Y : distance.Y; if (!((absDistance.X < xAdd) && (absDistance.Y < yAdd))) return false; xMag = xAdd - absDistance.X; yMag = yAdd - absDistance.Y; if (xMag < yMag) normal.X = (distance.X > 0) ? xMag : -xMag; else normal.Y = (distance.Y > 0) ? yMag : -yMag; return true; } private void PlayerCollisions() { foreach (Block blocks in allTiles) { collisionDist = Vector2.Zero; if (blocks.Texture != airTile && blocks.Texture != stoneDarkTexture && blocks.Texture != stoneDarkTextureSelected && blocks.Texture != airTileSelected && blocks.Texture != doorTexture && blocks.Texture != doorTextureSelected) { if (IsColliding(player.plyRect, blocks.tileRect)) { if (normal.Length() > collisionDist.Length()) { collisionDist = normal; } player.Position.X += collisionDist.X; player.Position.Y += collisionDist.Y; break; } } } } I got PlayerCollisions() running in my Update method. As you can see it works partly, but if it runs perfectly, it would be awesome, though I have no idea how to fix this problem. Help would be greatly appreciated. EDIT: If I remove the break; it works partly, then it is just the thing that it spasms when it hits two or more blocks at once, like, if I touch 2/3 blocks at once, it does twice the force up. How can I make it so that it only does the force for one block, so it stays correct, and does not spasm? Thanks.

    Read the article

  • How do I print out objects in an array in python?

    - by Jonathan
    I'm writing a code which performs a k-means clustering on a set of data. I'm actually using the code from a book called collective intelligence by O'Reilly. Everything works, but in his code he uses the command line and i want to write everything in notepad++. As a reference his line is >>>kclust=clusters.kcluster(data,k=10) >>>[rownames[r] for r in k[0]] Here is my code: from PIL import Image,ImageDraw def readfile(filename): lines=[line for line in file(filename)] # First line is the column titles colnames=lines[0].strip( ).split('\t')[1:] rownames=[] data=[] for line in lines[1:]: p=line.strip( ).split('\t') # First column in each row is the rowname rownames.append(p[0]) # The data for this row is the remainder of the row data.append([float(x) for x in p[1:]]) return rownames,colnames,data from math import sqrt def pearson(v1,v2): # Simple sums sum1=sum(v1) sum2=sum(v2) # Sums of the squares sum1Sq=sum([pow(v,2) for v in v1]) sum2Sq=sum([pow(v,2) for v in v2]) # Sum of the products pSum=sum([v1[i]*v2[i] for i in range(len(v1))]) # Calculate r (Pearson score) num=pSum-(sum1*sum2/len(v1)) den=sqrt((sum1Sq-pow(sum1,2)/len(v1))*(sum2Sq-pow(sum2,2)/len(v1))) if den==0: return 0 return 1.0-num/den class bicluster: def __init__(self,vec,left=None,right=None,distance=0.0,id=None): self.left=left self.right=right self.vec=vec self.id=id self.distance=distance def hcluster(rows,distance=pearson): distances={} currentclustid=-1 # Clusters are initially just the rows clust=[bicluster(rows[i],id=i) for i in range(len(rows))] while len(clust)>1: lowestpair=(0,1) closest=distance(clust[0].vec,clust[1].vec) # loop through every pair looking for the smallest distance for i in range(len(clust)): for j in range(i+1,len(clust)): # distances is the cache of distance calculations if (clust[i].id,clust[j].id) not in distances: distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec) #print 'i' #print i #print #print 'j' #print j #print d=distances[(clust[i].id,clust[j].id)] if d<closest: closest=d lowestpair=(i,j) # calculate the average of the two clusters mergevec=[ (clust[lowestpair[0]].vec[i]+clust[lowestpair[1]].vec[i])/2.0 for i in range(len(clust[0].vec))] # create the new cluster newcluster=bicluster(mergevec,left=clust[lowestpair[0]], right=clust[lowestpair[1]], distance=closest,id=currentclustid) # cluster ids that weren't in the original set are negative currentclustid-=1 del clust[lowestpair[1]] del clust[lowestpair[0]] clust.append(newcluster) return clust[0] def kcluster(rows,distance=pearson,k=4): # Determine the minimum and maximum values for each point ranges=[(min([row[i] for row in rows]),max([row[i] for row in rows])) for i in range(len(rows[0]))] # Create k randomly placed centroids clusters=[[random.random( )*(ranges[i][1]-ranges[i][0])+ranges[i][0] for i in range(len(rows[0]))] for j in range(k)] lastmatches=None for t in range(100): print 'Iteration %d' % t bestmatches=[[] for i in range(k)] # Find which centroid is the closest for each row for j in range(len(rows)): row=rows[j] bestmatch=0 for i in range(k): d=distance(clusters[i],row) if d<distance(clusters[bestmatch],row): bestmatch=i bestmatches[bestmatch].append(j) # If the results are the same as last time, this is complete if bestmatches==lastmatches: break lastmatches=bestmatches # Move the centroids to the average of their members for i in range(k): avgs=[0.0]*len(rows[0]) if len(bestmatches[i])>0: for rowid in bestmatches[i]: for m in range(len(rows[rowid])): avgs[m]+=rows[rowid][m] for j in range(len(avgs)): avgs[j]/=len(bestmatches[i]) clusters[i]=avgs return bestmatches

    Read the article

  • ActionScript Tweening Matrix Transform (big problem)

    - by TheDarkIn1978
    i'm attempting to tween the position and angle of a sprite. if i call the functions without tweening, to appear in one step, it's properly set at the correct coordinates and angle. however, tweening it makes it all go crazy. i'm using an rotateAroundInternalPoint matrix, and assume tweening this along with coordinate positions is messing up the results. works fine (without tweening): public function curl():void { imageWidth = 400; imageHeight = 600; parameters.distance = 0.5; parameters.angle = 45; backCanvas.x = imageWidth - imageHeight * parameters.distance; backCanvas.y = imageHeight - imageHeight * parameters.distance; var internalPointMatrix:Matrix = backCanvas.transform.matrix; MatrixTransformer.rotateAroundInternalPoint(internalPointMatrix, backCanvas.width * parameters.distance, 0, parameters.angle); backCanvas.transform.matrix = internalPointMatrix; } doesn't work properly (with tweening): public function curlUp():void { imageWidth = 400; imageHeight = 600; parameters.distance = 0.5; parameters.angle = 45; distanceTween = new Tween(parameters, "distance", None.easeNone, 0, distance, 1, true); angleTween = new Tween(parameters, "angle", None.easeNone, 0, angle, 1, true); angleTween.addEventListener(TweenEvent.MOTION_CHANGE, animateCurl); } private function animateCurl(evt:TweenEvent):void { backCanvas.x = imageWidth - imageHeight * parameters.distance; backCanvas.y = imageHeight - imageHeight * parameters.distance; var internalPointMatrix:Matrix = backCanvas.transform.matrix; MatrixTransformer.rotateAroundInternalPoint(internalPointMatrix, backCanvas.width * parameters.distance, 0, parameters.angle - previousAngle); backCanvas.transform.matrix = internalPointMatrix; previousAngle = parameters.angle; } in order for the angle to tween properly, i had to add a variable that would track it's last angle setting and subtract it from the new one. however, i still can not get this tween to return the same end position and angle as is without tweening. i've been stuck on this problem for a day now, so any help would be greatly appreciated.

    Read the article

  • Scale 2D coordinates and keep their relative euclidean distances intact?

    - by eiaxlid
    I have a set of points like: pointA(3302.34,9392.32), pointB(34322.32,11102.03), etc. I need to scale these so each x- and y-coordinate is in the range (0.0 - 1.0). I tried doing this by first finding the largest x value in the data set (maximum_x_value), and the largest y value in the set (minimum_y_value). I then did the following: pointA.x = (pointA.x - minimum_x_value) / (maximum_x_value - minimum_x_value) pointA.y = (pointA.y - minimum_y_value) / (maximum_y_value - minimum_y_value) This changes the relative distances(?), and therefore makes the data useless for my purposes. Is there a way to scale these coordinates while keeping their relative distances the intact?

    Read the article

  • Function to get X, Y position of an object orbiting a point, given a distance and angle in radians?

    - by Jake Petroules
    I am trying to code a function for a camera that orbits a point. Assume a 3d coordinate plane where Z is up. Ignore Z. Let's say the camera's position starts at (0, 0, z). The object to orbit is at, say (50, 50, z). So we have a distance of ~70 units. Calling the function with {(50, 50, z), 70, x} where x is the position in orbit, in radians, should return where the position of the camera should be. I believe this involves cos and tan but my trig isn't that great... point3d getCameraPosition(point3d objectPosition, float distance, float rotationRadians) { // ??? }

    Read the article

  • Distance between a line and a point in Objective-C ?

    - by micropsari
    Hello, I have 2 class : // point : (x, y) @interface ICPoint : NSObject { NSInteger x; NSInteger y; } // line : y= ax + b @interface ICLine : NSObject { float a; float b; } and this method: // return the distance between a line and a point -(NSInteger) distance:(ICPoint *)point { return fabs(-a*point.x +point.y - b) / sqrt(a*a + 1); } The formula seems right (based on wikipedia), but the results are wrong... why ? Thanks !

    Read the article

  • Android/ iOS how to determine small changes in distance using sensors?

    - by Tom
    I have been doing a bit of research, but I cannot seem to find a way to determine small distances (centimeters and meters) using the sensors in Android or iOS devices. Bluetooth appears too inaccurate and require more than one device, GPS only works over larger variations in distance, and small variations in rotation seem to make using the accelerometer nearly impossible. Is there a method that I am unaware of that would allow me to do such a thing? I am familiar with Calculus, so using Integrals to determine distance based on changes in time and velocity/ acceleration is not a problem for me, I just do not know how to determine those things. Thank you.

    Read the article

  • Raycasting "fisheye effect" question

    - by mattboy
    Continuing my exploration of raycasting, I am very confused about how the correction of the fisheye effect works. Looking at the screenshot below from the tutorial at permadi.com, the way I understand the cause of the fisheye effect is that the rays that are cast are distances from the player, rather than the distances perpendicular to the screen (or camera plane) which is what really needs to be displayed. The distance perpendicular to the screen then, in my world, should simply be the distance of Y coordinates (Py - Dy) assuming that the player is facing straight upwards. Continuing the tutorial, this is exactly how it seems to be according to the below screenshot. From my point of view, the "distorted distance" below is the same as the distance PD calculated above, and what's labelled the "correct distance" below should be the same as Py - Dy. Yet, this clearly isn't the case according to the tutorial. My question is, WHY is this not the same? How could it not be? What am I understanding and visualizing wrong here?

    Read the article

  • SQL SERVER – Spatial Database Queries – What About BLOB – T-SQL Tuesday #006

    - by pinaldave
    Michael Coles is one of the most interesting book authors I have ever met. He has a flair of writing complex stuff in a simple language. There are a very few people like that.  I really enjoyed reading his recent book, Expert SQL Server 2008 Encryption. I strongly suggest taking a look at it. This blog is written in response to T-SQL Tuesday #006: “What About BLOB? by Michael Coles. Spatial Database is my favorite subject. Since I did my TechEd India 2010 presentation, I have enjoyed this subject a lot. Before I continue this blog post, there are a few other blog posts, so I suggest you read them.  To help build the environment run the queries, I am going to present them in this single blog post. SQL SERVER – What is Spatial Database? – Developing with SQL Server Spatial and Deep Dive into Spatial Indexing This blog post explains the basics of Spatial Database and also provides a good introduction to Indexing concept. SQL SERVER – World Shapefile Download and Upload to Database – Spatial Database This blog post will enable you with how to load the shape file into database. SQL SERVER – Spatial Database Definition and Research Documents This blog post links to the white paper about Spatial Database written by Microsoft experts. SQL SERVER – Introduction to Spatial Coordinate Systems: Flat Maps for a Round Planet This blog post links to the white paper explaining coordinate system, as written by Microsoft experts. After reading the above listed blog posts, I am very confident that you are ready to run the following script. Once you create a database using the World Shapefile, as mentioned in the second link above,you can display the image of India just like the following. Please note that this is not an accurate political map. The boundary of this map has many errors and it is just a representation. You can run the following query to generate the map of India from the database spatial which you have created after following the instructions here. USE Spatial GO -- India Map SELECT [CountryName] ,[BorderAsGeometry] ,[Border] FROM [Spatial].[dbo].[Countries] WHERE Countryname = 'India' GO Now, let us find the longitude and latitude of the two major IT cities of India, Hyderabad and Bangalore. I find their values as the following: the values of longitude-latitude for Bangalore is 77.5833300000 13.0000000000; for Hyderabad, longitude-latitude is 78.4675900000 17.4531200000. Now, let us try to put these values on the India Map and see their location. -- Bangalore DECLARE @GeoLocation GEOGRAPHY SET @GeoLocation = GEOGRAPHY::STPointFromText('POINT(77.5833300000 13.0000000000)',4326).STBuffer(20000); -- Hyderabad DECLARE @GeoLocation1 GEOGRAPHY SET @GeoLocation1 = GEOGRAPHY::STPointFromText('POINT(78.4675900000 17.4531200000)',4326).STBuffer(20000); -- Bangalore and Hyderabad on Map of India SELECT name, [GeoLocation] FROM [IndiaGeoNames] I WHERE I.[GeoLocation].STDistance(@GeoLocation) <= 0 UNION ALL SELECT name, [GeoLocation] FROM [IndiaGeoNames] I WHERE I.[GeoLocation].STDistance(@GeoLocation1) <= 0 UNION ALL SELECT '',[Border] FROM [Spatial].[dbo].[Countries] WHERE Countryname = 'India' GO Now let us quickly draw a straight line between them. DECLARE @GeoLocation GEOGRAPHY SET @GeoLocation = GEOGRAPHY::STPointFromText('POINT(78.4675900000 17.4531200000)',4326).STBuffer(10000); DECLARE @GeoLocation1 GEOGRAPHY SET @GeoLocation1 = GEOGRAPHY::STPointFromText('POINT(77.5833300000 13.0000000000)',4326).STBuffer(10000); DECLARE @GeoLocation2 GEOGRAPHY SET @GeoLocation2 = GEOGRAPHY::STGeomFromText('LINESTRING(78.4675900000 17.4531200000, 77.5833300000 13.0000000000)',4326) SELECT name, [GeoLocation] FROM [IndiaGeoNames] I WHERE I.[GeoLocation].STDistance(@GeoLocation) <= 0 UNION ALL SELECT name, [GeoLocation] FROM [IndiaGeoNames] I1 WHERE I1.[GeoLocation].STDistance(@GeoLocation1) <= 0 UNION ALL SELECT '' name, @GeoLocation2 UNION ALL SELECT '',[Border] FROM [Spatial].[dbo].[Countries] WHERE Countryname = 'India' GO Let us use the distance function of the spatial database and find the straight line distance between this two cities. -- Distance Between Hyderabad and Bangalore DECLARE @GeoLocation GEOGRAPHY SET @GeoLocation = GEOGRAPHY::STPointFromText('POINT(78.4675900000 17.4531200000)',4326) DECLARE @GeoLocation1 GEOGRAPHY SET @GeoLocation1 = GEOGRAPHY::STPointFromText('POINT(77.5833300000 13.0000000000)',4326) SELECT @GeoLocation.STDistance(@GeoLocation1)/1000 'KM'; GO The result of above query is as displayed in following image. As per SQL Server, the distance between these two cities is 501 KM, but according to what I know, the distance between those two cities is around 562 KM by road. However, please note that roads are not straight and they have lots of turns, whereas this is a straight-line distance. What would be more accurate is the distance between these two cities by air travel. When we look at the air travel distance between Bangalore and Hyderabad, the total distance covered is 495 KM, which is very close to what SQL Server has estimated, which is 501 KM. Bravo! SQL Server has accurately provided the distance between two of the cities. SQL Server Spatial Database can be very useful simply because it is very easy to use, as demonstrated above. I appreciate your comments, so let me know what your thoughts and opinions about this are. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, SQL, SQL Authority, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology Tagged: Spatial Database

    Read the article

  • Game Maker Studio Gravity Problems

    - by Dusty
    I've started messing around with Game Maker Studio. The problem I'm having is trying to get a gravity code for orbiting. Here's how i did it in XNA foreach (GravItem Item in StarSystem.ActiveItems.OfType<GravItem>()) { if (this != Item) { Velocity += (10 * Vector2.Normalize(Item.Position - this.Position * (this.Mass * Item.Mass) / (Vector2.DistanceSquared(this.Position, Item.Position)) / (this.Mass)); } } Simple and works well, things or bit and everything is nice. but in Game maker i don't have the luxury of Vector2's or a For-each loop to loop threw all the objects that have a mass. I've tried a few different things but nothing seems to work distance = distance_to_object(obj_moon); //--Gravity hspeed += (0.5 * (distance) * (Mass * obj_moon.Mass) / (sqr(distance)) / Mass) vspeed += (0.5 * (distance) * (Mass * obj_moon.Mass) / (sqr(distance)) / Mass) thanks for the help

    Read the article

  • most efficient AABB vs Ray collision algorithms

    - by Asher Einhorn
    Is there a known 'most efficient' algorithm for AABB vs Ray collision detection? I recently stumbled accross Arvo's AABB vs Sphere collision algorithm, and I am wondering if there is a similarly noteworthy algorithm for this. One must have condition for this algorithm is that I need to have the option of querying the result for the distance from the ray's origin to the point of collision. having said this, if there is another, faster algorithm which does not return distance, then in addition to posting one that does, also posting that algorithm would be very helpful indeed. Please also state what the function's return argument is, and how you use it to return distance or a 'no-collision' case. For example, does it have an out parameter for the distance as well as a bool return value? or does it simply return a float with the distance, vs a value of -1 for no collision? (For those that don't know: AABB = Axis Aligned Bounding Box)

    Read the article

  • Eculidean space and vector magnitude

    - by Starkers
    Below we have distances from the origin calculated in two different ways, giving the Euclidean distance, the Manhattan distance and the Chebyshev distance. Euclidean distance is what we use to calculate the magnitude of vectors in 2D/3D games, and that makes sense to me: Let's say we have a vector that gives us the range a spaceship with limited fuel can travel. If we calculated this with Manhattan metric, our ship could travel a distance of X if it were travelling horizontally or vertically, however the second it attempted to travel diagonally it could only tavel X/2! So like I say, Euclidean distance does make sense. However, I still don't quite get how we calculate 'real' distances from the vector's magnitude. Here are two points, purple at (2,2) and green at (3,3). We can take two points away from each other to derive a vector. Let's create a vector to describe the magnitude and direction of purple from green: |d| = purple - green |d| = (purple.x, purple.y) - (green.x, green.y) |d| = (2, 2) - (3, 3) |d| = <-1,-1> Let's derive the magnitude of the vector via Pythagoras to get a Euclidean measurement: euc_magnitude = sqrt((x*x)+(y*y)) euc_magnitude = sqrt((-1*-1)+(-1*-1)) euc_magnitude = sqrt((1)+(1)) euc_magnitude = sqrt(2) euc_magnitude = 1.41 Now, if the answer had been 1, that would make sense to me, because 1 unit (in the direction described by the vector) from the green is bang on the purple. But it's not. It's 1.41. 1.41 units is the direction described, to me at least, makes us overshoot the purple by almost half a unit: So what do we do to the magnitude to allow us to calculate real distances on our point graph? Worth noting I'm a beginner just working my way through theory. Haven't programmed a game in my life!

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >