Search Results

Search found 440 results on 18 pages for 'abs'.

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

  • Java - Tile engine changing number in array not changing texture

    - by Corey
    I draw my map from a txt file. Would I have to write to the text file to notice the changes I made? Right now it changes the number in the array but the tile texture doesn't change. Do I have to do more than just change the number in the array? public class Tiles { public Image[] tiles = new Image[5]; public int[][] map = new int[64][64]; private Image grass, dirt, fence, mound; private SpriteSheet tileSheet; public int tileWidth = 32; public int tileHeight = 32; Player player = new Player(); public void init() throws IOException, SlickException { tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight); grass = tileSheet.getSprite(0, 0); dirt = tileSheet.getSprite(7, 7); fence = tileSheet.getSprite(2, 0); mound = tileSheet.getSprite(2, 6); tiles[0] = grass; tiles[1] = dirt; tiles[2] = fence; tiles[3] = mound; int x=0, y=0; BufferedReader in = new BufferedReader(new FileReader("assets/map.dat")); String line; while ((line = in.readLine()) != null) { String[] values = line.split(","); for (String str : values) { int str_int = Integer.parseInt(str); map[x][y]=str_int; //System.out.print(map[x][y] + " "); y=y+1; } //System.out.println(""); x=x+1; y = 0; } in.close(); } public void update(GameContainer gc) { } public void render(GameContainer gc) { for(int x = 0; x < map.length; x++) { for(int y = 0; y < map.length; y ++) { int textureIndex = map[y][x]; Image texture = tiles[textureIndex]; texture.draw(x*tileWidth,y*tileHeight); } } } Mouse picking public void checkDistance(GameContainer gc) { Input input = gc.getInput(); float mouseX = input.getMouseX(); float mouseY = input.getMouseY(); double mousetileX = Math.floor((double)mouseX/tiles.tileWidth); double mousetileY = Math.floor((double)mouseY/tiles.tileHeight); double playertileX = Math.floor(playerX/tiles.tileWidth); double playertileY = Math.floor(playerY/tiles.tileHeight); double lengthX = Math.abs((float)playertileX - mousetileX); double lengthY = Math.abs((float)playertileY - mousetileY); double distance = Math.sqrt((lengthX*lengthX)+(lengthY*lengthY)); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON) && distance < 4) { System.out.println("Clicked"); if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) { tiles.map[(int)mousetileX][(int)mousetileY] = 0; } } System.out.println(tiles.map[(int)mousetileX][(int)mousetileY]); }

    Read the article

  • Basic collision direction detection on 2d objects

    - by Osso Buko
    I am trying to develop a platform game for Android by using ANdroid GL Engine (ANGLE). And I am having trouble with collision detection. I have two objects which is shaped as rectangular. And no change in rotation. Here is a scheme of attributes of objects. What i am trying to do is when objects collide they block each other's movement on that direction. Every object has 4 boolean (bTop, bBottom, bRight, bLeft). For example when bBottom is true object can't advance on that direction. I came up with a solution but it seems it only works on one dimensional. Bottom and top or right and left. public void collisionPlatform (MyObject a, MyObject b) { // first obj is player and second is a wall or a platform Vector p1 = a.mPosition; // p1 = middle point of first object Vector d1 = a.mPosition2; // width(mX) and height of first object Vector mSpeed1 = a.mSpeed; // speed vector of first object Vector p2 = b.mPosition; // p1 = middle point of second object Vector d2 = b.mPosition2; // width(mX) and height of second object Vector mSpeed2 = b.mSpeed; // speed vector of second object float xDist, yDist; // distant between middle of two object float width , height; // this is average of two objects measurements width=(width1+width2)/2 xDist=(p1.mX - p2.mX); // calculate distance // if positive first object is at the right yDist=(p1.mY - p2.mY); // if positive first object is below width = d1.mX + d2.mX; // average measurements calculate height = d1.mY + d2.mY; width/=2; height/=2; if (Math.abs(xDist) < width && Math.abs(yDist) < height) { // Two object is collided if(p1.mY>p2.mY) { // first object is below second one a.bTop = true; if(a.mSpeed.mY<0) a.mSpeed.mY=0; b.bBottom = true; if(b.mSpeed.mY>0) b.mSpeed.mY=0; } else { a.bBottom = true; if(a.mSpeed.mY>0) a.mSpeed.mY=0; b.bTop = true; if(b.mSpeed.mY<0) b.mSpeed.mY=0; } } As seen in my code it simply will not work. when object comes from right or left it doesn't work. I tried couple of ways other than this one but none worked. I am guessing right method will include mSpeed vector. But I have no idea how to do it. I really appreciate if you could help. Sorry for my bad english.

    Read the article

  • [SOLVED] BitmapFactory.decodeStream returning null when options are set.

    - by Robert Foss
    Hi! I'm having issues with BitmapFactory.decodeStream(inputStream). When using it without options, it will return an image. But when I use it with options as in .decodeStream(inputStream, null, options) it never returns Bitmaps. What I'm trying to do is to downsample a Bitmap before I actually load it to save memory. I've read some good guides, but none using .decodeStream. Here httpIM:NOT//nornalbion.SPAMcom/blog/?p=143 httpIM:NOT//kfb-android.blogspot.SPAMcom/2009/04/image-processing-in-android.html WORKS JUST FINE URL url = new URL(sUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); DOESNT WORK InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); InputStream is = connection.getInputStream(); Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH); if(options.outHeight * options.outWidth * 2 >= 200*100*2){ // Load, scaling to smallest power of 2 that'll get it <= desired dimensions double sampleSize = scaleByHeight ? options.outHeight / TARGET_HEIGHT : options.outWidth / TARGET_WIDTH; options.inSampleSize = (int)Math.pow(2d, Math.floor( Math.log(sampleSize)/Math.log(2d))); } // Do the actual decoding options.inJustDecodeBounds = false; Bitmap img = BitmapFactory.decodeStream(is, null, options);

    Read the article

  • BitmapFactory.decodeStream returning null when options are set.

    - by Robert Foss
    Hi! I'm having issues with BitmapFactory.decodeStream(). When using it without options, it will return an image. But when I use it with options as in .decodeStream(inputStream, null, options) it never returns Bitmaps. What I'm trying to do is to downsample a Bitmap before I actually load it to save memory. I've read some good guides, but none using .decodeStream. Here httpIM:NOT//nornalbion.SPAMcom/blog/?p=143 httpIM:NOT//kfb-android.blogspot.SPAMcom/2009/04/image-processing-in-android.html WORKS JUST FINE InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); DOESNT WORK InputStream is = connection.getInputStream(); Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH); if(options.outHeight * options.outWidth * 2 >= 200*100*2){ // Load, scaling to smallest power of 2 that'll get it <= desired dimensions double sampleSize = scaleByHeight ? options.outHeight / TARGET_HEIGHT : options.outWidth / TARGET_WIDTH; options.inSampleSize = (int)Math.pow(2d, Math.floor( Math.log(sampleSize)/Math.log(2d))); System.out.println("Samplesize: " + options.inSampleSize); } // Do the actual decoding options.inJustDecodeBounds = false; //options.inTempStorage = new byte[IMG_BUFFER_LEN]; Bitmap img = BitmapFactory.decodeStream(is, null, options);

    Read the article

  • Tricky file parsing. Inconsistent Delimeters

    - by Ben Truby
    I need to parse a file with the following format. 0000000 ...ISBN.. ..Author.. ..Title.. ..Edit.. ..Year.. ..Pub.. ..Comments.. NrtlExt Nrtl Next Navg NQoH UrtlExt Urtl Uext Uavg UQoH ABS NEB MBS FOL ABE0001 0-679-73378-7 ABE WOMAN IN THE DUNES (INT'L ED) 1st 64 RANDOM 0.00 13.90 0.00 10.43 0 21.00 10.50 6.44 3.22 2 2.00 0.50 2.00 2.00 ABS The ID and ISBN are not a problem, the title is. There is no set length for these fields, and there are no solid delimiters- the space can be used for most of the file. Another issue is that there is not always an entry in the comments field. When there is, there are spaced within the content. So I can get the first two, and the last fourteen. I need some help figuring out how to parse the middle six fields. This file was generated by an older program that I cannot change. I am using php to parse this file.

    Read the article

  • Iterative Cartesian Product in Java

    - by akappa
    Hi, I want to compute the cartesian product of an arbitrary number of nonempty sets in Java. I've wrote that iterative code... public static <T> List<Set<T>> cartesianProduct(List<Set<T>> list) { List<Iterator<T>> iterators = new ArrayList<Iterator<T>>(list.size()); List<T> elements = new ArrayList<T>(list.size()); List<Set<T>> toRet = new ArrayList<Set<T>>(); for (int i = 0; i < list.size(); i++) { iterators.add(list.get(i).iterator()); elements.add(iterators.get(i).next()); } for (int j = 1; j >= 0;) { toRet.add(Sets.newHashSet(elements)); for (j = iterators.size()-1; j >= 0 && !iterators.get(j).hasNext(); j--) { iterators.set(j, list.get(j).iterator()); elements.set(j, iterators.get(j).next()); } elements.set(Math.abs(j), iterators.get(Math.abs(j)).next()); } return toRet; } ...but I found it rather inelegant. Someone has a better, still iterative solution? A solution that uses some wonderful functional-like approach? Otherwise... suggestion about how to improve it? Errors? Thanks :)

    Read the article

  • floating exception using icc compiler

    - by Hristo
    I'm compiling my code via the following command: icc -ltbb test.cxx -o test Then when I run the program: time ./mp6 100 > output.modified Floating exception 4.871u 0.405s 0:05.28 99.8% 0+0k 0+0io 0pf+0w I get a "Floating exception". This following is code in C++ that I had before the exception and after: // before if (j < E[i]) { temp += foo(0, trr[i], ex[i+j*N]); } // after temp += (j < E[i])*foo(0, trr[i], ex[i+j*N]); This is boolean algebra... so (j < E[i]) is either going to be a 0 or a 1 so the multiplication would result either in 0 or the foo() result. I don't see why this would cause a floating exception. This is what foo() does: int foo(int s, int t, int e) { switch(s % 4) { case 0: return abs(t - e)/e; case 1: return (t == e) ? 0 : 1; case 2: return (t < e) ? 5 : (t - e)/t; case 3: return abs(t - e)/t; } return 0; } foo() isn't a function I wrote so I'm not too sure as to what it does... but I don't think the problem is with the function foo(). Is there something about boolean algebra that I don't understand or something that works differently in C++ than I know of? Any ideas why this causes an exception? Thanks, Hristo

    Read the article

  • What is the name of this geometrical function?

    - by Spike
    In a two dimentional integer space, you have two points, A and B. This function returns an enumeration of the points in the quadrilateral subset bounded by A and B. A = {1,1} B = {2,3} Fn(A,B) = {{1,1},{1,2},{1,3},{2,1},{2,2},{2,3}} I can implement it in a few lines of LINQ. private void UnknownFunction(Point to, Point from, List<Point> list) { var vectorX = Enumerable.Range(Math.Min(to.X, from.X), Math.Abs(to.X - from.Y) + 1); var vectorY = Enumerable.Range(Math.Min(to.Y, from.Y), Math.Abs(to.Y - from.Y) + 1); foreach (var x in vectorX) foreach (var y in vectorY) list.Add(new Point(x, y)); } I'm fairly sure that this is a standard mathematical operation, but I can't think what it is. Feel free to tell me that it's one line of code in your language of choice. Or to give me a cunning implementation with lambdas or some such. But mostly I just want to know what it's called. It's driving me nuts. It feels a little like a convolution, but it's been too long since I was at school for me to be sure.

    Read the article

  • Could not determine the size of this expression.

    - by Søren
    Hi, I have resently started to use MATLAB Simulink, and my problem is that i can't implement an AMDF function, because simulink compiler cannot determine the lengths. Simulink errors: |--------------------------------------------------------------------------------------- Could not determine the size of this expression. Function 'Embedded MATLAB Function2' (#38.728.741), line 33, column 32: "1:flength-k+1" Errors occurred during parsing of Embedded MATLAB function 'Embedded MATLAB Function2'(#38) Embedded MATLAB Interface Error: Errors occurred during parsing of Embedded MATLAB function 'Embedded MATLAB Function2'(#38) . |--------------------------------------------------------------------------------------- MY CODE: |--------------------------------------------------------------------------------------- persistent sLength persistent fLength persistent amdf % Length of the frame flength = length(frame); % Pitch period is between 2.5 ms and 19.5 ms for LPC-10 algorithm % This because this algorithm assumes the frequencyspan is 50 and 400 Hz pH = ceil((1/min(fspan))*fs); if(pH flength) pH = flength; end; pL = ceil((1/max(fspan))*fs); if(pL <= 0 || pL = flength) pL = 0; end; sLength = pH - pL; % Normalize the frame frame = frame/max(max(abs(frame))); % Allocating memory for the calculation of the amdf %amdf = zeros(1,sLength); %%%%%%%% amdf = 0; % Calculating the AMDF with unbiased normalizing for k = (pL+1):pH amdf(k-pL) = sum(abs(frame(1:flength-k+1) - frame(k:flength)))/(flength-k+1); end; % Output of the AMDF if(min(amdf) < lvlThr) voiced = 1; else voiced = 0; end; % Output of the minimum of the amdf minAMDF = min(amdf); |---------------------------------------------------------------------------------------- HELP Kind regards Søren

    Read the article

  • Can this code be further optimized??

    - by kaki
    i understand that the code given below will not be compltely understood unless i explain my whole of previous and next lines of code. But this is part of the code which is causing so much of delay in my project and want to optimize this. i want to know which code part is faulty and how could this be replaced. i guess,few can say that use of this function is heavy compared and other ligher method are available to do this work please help, thanks in advance for i in range(len(lists)): save=database_index[lists[i]] #print save #if save[1]!='text0194'and save[1]!='text0526': using_data[save[0]]=save p=os.path.join("c:/begpython/wavnk/",str(str(str(save[1]).replace('phone','text'))+'.pm')) x1=open(p , 'r') x2=open(p ,'r') for i in range(6): x1.readline() x2.readline() gen = (float(line.partition(' ')[0]) for line in x1) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[4]))) #print r[0] a1=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a1 p1=str(str(a1).rstrip('\n')).split(' ') #print p1 join_cost_index_end[save[0]]=p1 #print join_cost_index_end gen = (float(line.partition(' ')[0]) for line in x2) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[3]))) #print r[0] a2=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a2 p2=str(str(a2).rstrip('\n')).split(' ') #print p2 join_cost_index_strt[save[0]]=p2 #print join_cost_index_strt j=j+1 #print j #print join_cost_index_end #print join_cost_index_strt enter code here here my database_index has about 2,50,000 entries`

    Read the article

  • Trying to draw a dynamic rectangle in SVG

    - by Shaun
    To be more specific, here are the steps I need: onmousedown - set x and y of rect as mouse coordinates onmousemove - using the current x and y mouse coordinates calculate height and width of the rect, set these and append onmouseup - remove the rectangle, and call a function based off some calculations from the rect. Here is what I have but isn't quite working (right now I have it drawing a line to make it simpler): onmousedown: startbox(evt) function startbox(evt) { if(evt.button === 0) { x1 = evt.clientX + div.scrollLeft-5; y1 = evt.clientY + div.scrollTop-30; obj.setAttributeNS(null, "x1", x1); obj.setAttributeNS(null, "y1", y1); Root.setAttributeNS(null, "onmousemove", "updatebox(evt)"); } } onmousemove: updatebox(evt) function updatebox(evt) { if(evt.button === 0) { x2 = evt.clientX + div.scrollLeft-5; y2 = evt.clientY + div.scrollTop-30; Root.appendChild(.obj); w = Math.abs(x2-x1); h = Math.abs(y2-y1); var strokecolor; if(w>20 && h>20) { strokecolor = "green"; validbox = true; } else { strokecolor = "red"; validbox = false; } var Attr={ x2:x2, y2:y2, stroke:strokecolor } assignAttr(obj, Attr); //just loops thru adding multiple attributes } } onmouseup: endbox() function endbox(evt) { if(evt.button===0) { Root.setAttributeNS(null, "onmousemove", ""); Root.removeChild(obj); if(validbox) { //do stuff validbox = !validbox; } } } Some of my problems with this are: Its slow in Chrome making drawing the line/rect feel sluggish. It won't work two times in a row. This is the real problem that I can't fix. Any and all feedback is welcome.

    Read the article

  • R: outlier cleaning for each column in a dataframe by using quantiles 0.05 and 0.95

    - by Rainer
    hi, I am a R-novice. I want to do some outlier cleaning and over-all-scaling from 0 to 1 before putting the sample into a random forest. g<-c(1000,60,50,60,50,40,50,60,70,60,40,70,50,60,50,70,10) If i do a simple scaling from 0 - 1 the result would be: > round((g - min(g))/abs(max(g) - min(g)),1) [1] 1.0 0.1 0.0 0.1 0.0 0.0 0.0 0.1 0.1 0.1 0.0 0.1 0.0 0.1 0.0 0.1 0.0 So my idea is to replace the values of each column that are greater than the 0.95-quantile with the next value smaller than the 0.95-quantile - and the same for the 0.05-quantile. So the pre-scaled result would be: g<-c(**70**,60,50,60,50,40,50,60,70,60,40,70,50,60,50,70,**40**) and scaled: > round((g - min(g))/abs(max(g) - min(g)),1) [1] 1.0 0.7 0.3 0.7 0.3 0.0 0.3 0.7 1.0 0.7 0.0 1.0 0.3 0.7 0.3 1.0 0.0 I need this formula for a whole dataframe, so the functional implementation within R should be something like: > apply(c, 2, function(x) x[x`<quantile(x, 0.95)]`<-max(x[x, ... max without the quantile(x, 0.95)) Can anyone help? Spoken beside: if there exists a function that does this job directly, please let me know. I already checked out cut and cut2. cut fails because of not-unique breaks; cut2 would work, but only gives back string values or the mean value, and I need a numeric vector from 0 - 1. for trial: a<-c(100,6,5,6,5,4,5,6,7,6,4,7,5,6,5,7,1) b<-c(1000,60,50,60,50,40,50,60,70,60,40,70,50,60,50,70,10) c<-cbind(a,b) c<-as.data.frame(c) Regards and thanks for help, Rainer

    Read the article

  • iPhone TabbarController Switch Transition

    - by user269737
    I've implemented gestures (touchBegan-moved-ended) in order to allow for swiping through my tabs. It works. I'd like to add a slide-from-left and slide-from-right transition. It would be better if it could be part of the gesture if statement which tells me if the swipe is towards the right of left. Since I determine which tab is displayed from that, I could show that specific transition along with the new tab. So my question is this: what's the simplest way to simplement a slide transition at a specific instance. I don't want it to be for the whole tabbarcontrol since this is specifically for the swiping. Thanks for the help, much appreciated. For clarification purposes, this is snippet shows how I'm switching tabs: if(abs(diffx / diffy) > 2.5 && abs(diffx) > HORIZ_SWIPE_DRAG_MIN) { // It appears to be a swipe. if(isProcessingListMove) { // ignore move, we're currently processing the swipe return; } if (mystartTouchPosition.x < currentTouchPosition.x) { isProcessingListMove = YES; self.tabBarController.selectedViewController = [self.tabBarController.viewControllers objectAtIndex:0]; return; } else { isProcessingListMove = YES; self.tabBarController.selectedViewController = [self.tabBarController.viewControllers objectAtIndex:1 ]; return; }

    Read the article

  • vectorizing loops in Matlab - performance issues

    - by Gacek
    This question is related to these two: http://stackoverflow.com/questions/2867901/introduction-to-vectorizing-in-matlab-any-good-tutorials http://stackoverflow.com/questions/2561617/filter-that-uses-elements-from-two-arrays-at-the-same-time Basing on the tutorials I read, I was trying to vectorize some procedure that takes really a lot of time. I've rewritten this: function B = bfltGray(A,w,sigma_r) dim = size(A); B = zeros(dim); for i = 1:dim(1) for j = 1:dim(2) % Extract local region. iMin = max(i-w,1); iMax = min(i+w,dim(1)); jMin = max(j-w,1); jMax = min(j+w,dim(2)); I = A(iMin:iMax,jMin:jMax); % Compute Gaussian intensity weights. F = exp(-0.5*(abs(I-A(i,j))/sigma_r).^2); B(i,j) = sum(F(:).*I(:))/sum(F(:)); end end into this: function B = rngVect(A, w, sigma) W = 2*w+1; I = padarray(A, [w,w],'symmetric'); I = im2col(I, [W,W]); H = exp(-0.5*(abs(I-repmat(A(:)', size(I,1),1))/sigma).^2); B = reshape(sum(H.*I,1)./sum(H,1), size(A, 1), []); But this version seems to be as slow as the first one, but in addition it uses a lot of memory and sometimes causes memory problems. I suppose I've made something wrong. Probably some logic mistake regarding vectorizing. Well, in fact I'm not surprised - this method creates really big matrices and probably the computations are proportionally longer. I have also tried to write it using nlfilter (similar to the second solution given by Jonas) but it seems to be hard since I use Matlab 6.5 (R13) (there are no sophisticated function handles available). So once again, I'm asking not for ready solution, but for some ideas that would help me to solve this in reasonable time. Maybe you will point me what I did wrong.

    Read the article

  • My Android XML files can't find ActionBarSherlock themes

    - by MalcolmMcC
    I'm trying to develop an app with ActionBarSherlock and everything works except the theming. Specifically, I can import com.actionbarsherlock.app.*, extend SherlockActivity, but I always have this error in my manifest: Error: No resource found that matches the given name (at 'theme' with value '@style/Theme.Sherlock'). I know there have been plenty of questions asked about this, but they have not worked for me. I have tried refreshing the workspace cleaning all of my projects putting the line in both the <activity> and the <application> setting my targetSdkVersion and minSdkVersion to various values, in both my manifest and ABS's and I've tried the following variations, and probably others: android:theme="@style/Theme.Sherlock" android:theme="@android:style/Theme.Sherlock" theme="@style/Theme.Sherlock" theme="@android:style/Theme.Sherlock" theme="@theme/Theme.Sherlock" theme="@android:theme/Theme.Sherlock" It's worth noting that the autocomplete after I typed "@style/" was showing nothing, so I tried making my own style in styles.xml and then that showed up but still nothing from ActionBarSherlock. Also, in styles.xml, I tried to make my own theme to extend Theme.Sherlock, and @style/Theme.Sherlock was not found there either when I tried to add it as a parent. I tried loading the samples but got a JAR Mismatch. My conclusion is that somehow my xml files are unable to access the ABS library, but I'm at a loss as to how to fix it. Any help hugely appreciated.

    Read the article

  • Apply Quaternion to Camera in libGDX

    - by Alex_Hyzer_Kenoyer
    I am trying to rotate my camera using a Quaternion in libGDX. I have a Quaternion created and being manipulated but I have no idea how to apply it to the camera, everything I've tried hasn't moved the camera at all. Here is how I set up the rotation Quaternion: public void rotateX(float amount) { tempQuat.set(tempVector.set(1.0f, 0.0f, 0.0f), amount * MathHelper.PIOVER180); rotation = rotation.mul(tempQuat); } public void rotateY(float amount) { tempQuat.set(tempVector.set(0.0f, 1.0f, 0.0f), amount * MathHelper.PIOVER180); rotation = tempQuat.mul(rotation); } Here is how I am trying to update the camera (Same update method as the original libGDX version but I added the part about the rotation matrix to the top): public void update(boolean updateFrustum) { float[] matrix = new float[16]; rotation.toMatrix(matrix); Matrix4 m = new Matrix4(); m.set(matrix); camera.view.mul(m); //camera.direction.mul(m).nor(); //camera.up.mul(m).nor(); float aspect = camera.viewportWidth / camera.viewportHeight; camera.projection.setToProjection(Math.abs(camera.near), Math.abs(camera.far), camera.fieldOfView, aspect); camera.view.setToLookAt(camera.position, tempVector.set(camera.position).add(camera.direction), camera.up); camera.combined.set(camera.projection); Matrix4.mul(camera.combined.val, camera.view.val); if (updateFrustum) { camera.invProjectionView.set(camera.combined); Matrix4.inv(camera.invProjectionView.val); camera.frustum.update(camera.invProjectionView); } }

    Read the article

  • Python optimization problem?

    - by user342079
    Alright, i had this homework recently (don't worry, i've already done it, but in c++) but I got curious how i could do it in python. The problem is about 2 light sources that emit light. I won't get into details tho. Here's the code (that I've managed to optimize a bit in the latter part): import math, array import numpy as np from PIL import Image size = (800,800) width, height = size s1x = width * 1./8 s1y = height * 1./8 s2x = width * 7./8 s2y = height * 7./8 r,g,b = (255,255,255) arr = np.zeros((width,height,3)) hy = math.hypot print 'computing distances (%s by %s)'%size, for i in xrange(width): if i%(width/10)==0: print i, if i%20==0: print '.', for j in xrange(height): d1 = hy(i-s1x,j-s1y) d2 = hy(i-s2x,j-s2y) arr[i][j] = abs(d1-d2) print '' arr2 = np.zeros((width,height,3),dtype="uint8") for ld in [200,116,100,84,68,52,36,20,8,4,2]: print 'now computing image for ld = '+str(ld) arr2 *= 0 arr2 += abs(arr%ld-ld/2)*(r,g,b)/(ld/2) print 'saving image...' ar2img = Image.fromarray(arr2) ar2img.save('ld'+str(ld).rjust(4,'0')+'.png') print 'saved as ld'+str(ld).rjust(4,'0')+'.png' I have managed to optimize most of it, but there's still a huge performance gap in the part with the 2 for-s, and I can't seem to think of a way to bypass that using common array operations... I'm open to suggestions :D

    Read the article

  • In Corona SDK the background image always cover other images

    - by user1446126
    I'm currently making a tower defense game with Corona SDK. However, while I'm making the gaming scene, The background scene always cover the monster spawn, I've tried background:toBack() ,however it's doesn't work.Here is my code: module(..., package.seeall) function new() local localGroup = display.newGroup(); local level=require(data.levelSelected); local currentDes = 1; monsters_list = display.newGroup() --The background local bg = display.newImage ("image/levels/1/bg.png"); bg.x = _W/2;bg.y = _H/2; bg:toBack(); --generate the monsters function spawn_monster(kind) local monster=require("monsters."..kind); newMonster=monster.new() --read the spawn(starting point) in level, and spawn the monster there newMonster.x=level.route[1][1];newMonster.y=level.route[1][2]; monsters_list:insert(newMonster); localGroup:insert(monsters_list); return monsters_list; end function move(monster,x,y) -- Using pythagoras to calauate the moving distace, Hence calauate the time consumed according to speed transition.to(monster,{time=math.sqrt(math.abs(monster.x-x)^2+math.abs(monster.y-y)^2)/(monster.speed/30),x=x, y=y, onComplete=newDes}) end function newDes() currentDes=currentDes+1; end --moake monster move according to the route function move_monster() for i=1,monsters_list.numChildren do move(monsters_list[i],200,200); print (currentDes); end end function agent() spawn_monster("basic"); end --Excute function above. timer2 = timer.performWithDelay(1000,agent,10); timer.performWithDelay(100,move_monster,-1); timer.performWithDelay(10,update,-1); move_monster(); return localGroup; end and the monster just stuck at the spawn point and stay there. but, When i comment these 3 lines of code: --local bg = display.newImage ("image/levels/1/bg.png"); --bg.x = _W/2;bg.y = _H/2; --bg:toBack(); The problem disappear Any ideas??Thanks for helping

    Read the article

  • Collision of dot and line in 2D space

    - by Anderiel
    So i'm trying to make my first game on android. The thing is i have a small moving ball and i want it to bounce from a line that i drew. For that i need to find if the x,y of the ball are also coordinates of one dot from the line. I tried to implement these equations about lines x=a1 + t*u1 y=a2 + t*u2 = (x-a1)/u1=(y-a2)/u2 (t=t which has to be if the point is on the line) where x and y are the coordinates im testing, dot[a1,a2] is a dot that is on the line and u(u1,u2) is the vector of the line. heres the code: public boolean Collided() { float u1 =Math.abs(Math.round(begin_X)-Math.round(end_X)); float u2 =Math.abs(Math.round(begin_Y)-Math.round(end_Y)); float t_x =Math.round((elect_X - begin_X)/u1); float t_y =Math.round((elect_Y - begin_Y)/u2); if(t_x==t_y) { return true; } else { return false; } } points [begin_X,end_X] and [begin_Y,end_Y] are the two points from the line and [elect_X,elect_Y] are the coordinates of the ball theoreticaly it should work, but in the reality the ball most of the time just goes straigth through the line or bounces somewhere else where it shouldnt

    Read the article

  • F# numeric associations

    - by b1g3ar5
    I have a numeric association for a custom type as follows: let DiffNumerics = { new INumeric<Diff> with member op.Zero = C 0.0 member op.One = C 1.0 member op.Add(a,b) = a + b member op.Subtract(a,b) = a - b member op.Multiply(a,b) = a * b member ops.Negate(a) = Diff.negate a member ops.Abs(a) = Diff.abs a member ops.Equals(a, b) = ((=) a b) member ops.Compare(a, b) = Diff.compare a b member ops.Sign(a) = int (Diff.sign a).Val member ops.ToString(x,fmt,fmtprovider) = failwith "not implemented" member ops.Parse(s,numstyle,fmtprovider) = failwith "not implemented" } GlobalAssociations.RegisterNumericAssociation(DiffNumerics) It works fine in f# interactive, but crashes when I run, because .ElementOps is not filled correctly for a matrix of these types. Any ideas why this might be? EDIT: In fsi, the code let A = dmatrix [[Diff.C 1.;Diff.C 2.;Diff.C 3.];[Diff.C 4.;Diff.C 5.;Diff.C 6.]] let B = matrix [[1.;2.;3.];[4.;5.;6.]] gives: > A.ElementOps;; val it : INumeric<Diff> = FSI_0003.NewAD+DiffNumerics@258 > B.ElementOps;; val it : INumeric<float> = Microsoft.FSharp.Math.Instances+FloatNumerics@115 > in the debugger A.ElementOps shows: '(A).ElementOps' threw an exception of type 'System.NotSupportedException' and, for the B matrix: Microsoft.FSharp.Math.Instances+FloatNumerics@115 So somehow the DiffNumerics isn't making it to the compiled program.

    Read the article

  • Manhattan Heuristic function for A-star (A*)

    - by Shawn Mclean
    I found this algorithm here. I have a problem, I cant seem to understand how to set up and pass my heuristic function. static public Path<TNode> AStar<TNode>(TNode start, TNode destination, Func<TNode, TNode, double> distance, Func<TNode, double> estimate) where TNode : IHasNeighbours<TNode> { var closed = new HashSet<TNode>(); var queue = new PriorityQueue<double, Path<TNode>>(); queue.Enqueue(0, new Path<TNode>(start)); while (!queue.IsEmpty) { var path = queue.Dequeue(); if (closed.Contains(path.LastStep)) continue; if (path.LastStep.Equals(destination)) return path; closed.Add(path.LastStep); foreach (TNode n in path.LastStep.Neighbours) { double d = distance(path.LastStep, n); var newPath = path.AddStep(n, d); queue.Enqueue(newPath.TotalCost + estimate(n), newPath); } } return null; } As you can see, it accepts 2 functions, a distance and a estimate function. Using the Manhattan Heuristic Distance function, I need to take 2 parameters. Do I need to modify his source and change it to accepting 2 parameters of TNode so I can pass a Manhattan estimate to it? This means the 4th param will look like this: Func<TNode, TNode, double> estimate) where TNode : IHasNeighbours<TNode> and change the estimate function to: queue.Enqueue(newPath.TotalCost + estimate(n, path.LastStep), newPath); My Manhattan function is: private float manhattanHeuristic(Vector3 newNode, Vector3 end) { return (Math.Abs(newNode.X - end.X) + Math.Abs(newNode.Y - end.Y)); }

    Read the article

  • Why would an image (the Mandelbrot) be skewed and wrap around?

    - by Sean D
    So I just wrote a little snippet to generate the Mandelbrot fractal and imagine my surprise when it came out all ugly and skewed (as you can see at the bottom). I'd appreciate a point in the direction of why this would even happen. It's a learning experience and I'm not looking for anyone to do it for me, but I'm kinda at a dead end debugging it. The offending generation code is: module Mandelbrot where import Complex import Image main = writeFile "mb.ppm" $ imageMB 1000 mandelbrotPixel x y = mb (x:+y) (0:+0) 0 mb c x iter | magnitude x > 2 = iter | iter >= 255 = 255 | otherwise = mb c (c+q^2) (iter+1) where q = x --Mandelbrot --q = (abs.realPart $ x) :+ (abs.imagPart $ x) --Burning Ship argandPlane x0 x1 y0 y1 width height = [(x,y)| y<-[y1,(y1-dy)..y0], --traverse from x<-[x0,(x0+dx)..x1]] --top-left to bottom-right where dx = (x1 - x0)/width dy = (y1 - y0)/height drawPicture :: (a->b->c)->(c->Colour)->[(a,b)]->Image drawPicture function colourFunction plane = map (colourFunction.uncurry function) plane imageMB s = createPPM s s $ drawPicture mandelbrotPixel (\x->[x,x,x]) $ argandPlane (-1.8) (-1.7) (0.02) 0.055 s' s' where s' = fromIntegral s And the image code (which I'm fairly confident in) is: module Image where type Colour = [Int] type Image = [Colour] createPPM :: Int -> Int -> Image -> String createPPM w h i = concat ["P3 ", show w, " ", show h, " 255\n", unlines.map (unwords.map show) $ i]

    Read the article

  • Random Movement in a Fixed Container

    - by James Barracca
    I'm looking to create something that can move randomly inside of a fixed div container. I love the way the object moves in this example that I found searching this website... http://jsfiddle.net/Xw29r/15/ The code on the jsfiddle contains the following: $(document).ready(function(){ animateDiv(); }); function makeNewPosition(){ // Get viewport dimensions (remove the dimension of the div) var h = $(window).height() - 50; var w = $(window).width() - 50; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); return [nh,nw]; } function animateDiv(){ var newq = makeNewPosition(); var oldq = $('.a').offset(); var speed = calcSpeed([oldq.top, oldq.left], newq); $('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){ animateDiv(); }); }; function calcSpeed(prev, next) { var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]); var greatest = x > y ? x : y; var speedModifier = 0.1; var speed = Math.ceil(greatest/speedModifier); return speed; }? CSS: div.a { width: 50px; height:50px; background-color:red; position:fixed; }? However, I don't believe the code above constricts that object at all. I need my object to move randomly inside of a container that is let's say for now... 1200px in width and 500px in height. Can someone steer me in the right direction? I'm super new to coding so I'm having a hard time finding an answer on my own. Thanks so much! James

    Read the article

  • Error in bisection method code in Matlab

    - by Amanda Collins
    I need to write a proper implementation of the bisection method, which means I must address all possible user input errors. Here is my code: function [x_sol, f_at_x_sol, N_iterations] = bisection(f, xn, xp, eps_f, eps_x) % solving f(x)=0 with bisection method % f is the function handle to the desired function, % xn and xp are borders of search, % f(xn)<0 and f(xp)>0 required, % eps_f defines how close f(x) should be to zero, % eps_x defines uncertainty of solution x if(f(xp) < 0) error('xp must be positive') end; if(f(xn)>0) error('xn must be negative') end; if (xn >= xp) error ('xn must be less than xp') end; xg=(xp+xn)/2; %initial guess fg=f(xg); % initial function evaluation N_iterations=1; while ( (abs(fg) > eps_f) & (abs(xg-xp) > eps_x) ) if (fg>0) xp=xg; else xn=xg; end xg=(xp+xn)/2; %update guess fg=f(xg); %update function evaluation N_iterations=N_iterations+1; end x_sol=xg; %solution is ready f_at_x_sol=fg; if (f_at_x_sol > eps_f) error('No convergence') end and here is the error message I receive when I try to test this in Matlab: >> bisection(x.^2, 2, -1, 1e-8, 1e-10) Attempted to access f(-1); index must be a positive integer or logical. Error in bisection (line 9) if(f(xp)<0) I was attempting to see if my error codes worked, but it doesn't look like they do. I get the same error when I try to test it on a function that should work.

    Read the article

  • Test for `point` within an attachment in `mail-mode`

    - by lawlist
    I'm looking for a better test to determine when point is within a hidden attachment in mail-mode (which is used by wl-draft-mode). The attachments are mostly hidden and look like this: --[[application/xls Content-Disposition: attachment; filename="hello-world.xls"][base64]] The test of invisible-p yields a result of nil. I am current using the following test, but it seems rather poor: (save-excursion (goto-char (point-max)) (goto-char (previous-char-property-change (point))) (goto-char (previous-char-property-change (point))) (re-search-backward "]]" (point-at-bol) t))) Any suggestions would be greatly appreciated. Here is the full snippet: (goto-char (point-max)) (cond ((= (save-excursion (abs (skip-chars-backward "\n\t"))) 0) (insert "\n\n")) ((and (= (save-excursion (abs (skip-chars-backward "\n\t"))) 1) (not (save-excursion (goto-char (previous-char-property-change (point))) (goto-char (previous-char-property-change (point))) (re-search-backward "]]" (point-at-bol) t)))) (insert "\n"))) GOAL:  If there are no attachments and no new lines at the end of the buffer, then insert \n\n and then insert the attachment thereafter. If there is just one new line at the end of the buffer, then insert \n and then insert the attachment thereafter. If there is an attachment at the end of the buffer, then do not insert any new lines.

    Read the article

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