Search Results

Search found 74 results on 3 pages for 'trigonometry'.

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

  • Programming concepts taken from the arts and humanities

    - by Joey Adams
    After reading Paul Graham's essay Hackers and Painters and Joel Spolsky's Advice for Computer Science College Students, I think I've finally gotten it through my thick skull that I should not be loath to work hard in academic courses that aren't "programming" or "computer science" courses. To quote the former: I've found that the best sources of ideas are not the other fields that have the word "computer" in their names, but the other fields inhabited by makers. Painting has been a much richer source of ideas than the theory of computation. — Paul Graham, "Hackers and Painters" There are certainly other, much stronger reasons to work hard in the "boring" classes. However, it'd also be neat to know that these classes may someday inspire me in programming. My question is: what are some specific examples where ideas from literature, art, humanities, philosophy, and other fields made their way into programming? In particular, ideas that weren't obviously applied the way they were meant to (like most math and domain-specific knowledge), but instead gave utterance or inspiration to a program's design and choice of names. Good examples: The term endian comes from Gulliver's Travels by Tom Swift (see here), where it refers to the trivial matter of which side people crack open their eggs. The terms journal and transaction refer to nearly identical concepts in both filesystem design and double-entry bookkeeping (financial accounting). mkfs.ext2 even says: Writing superblocks and filesystem accounting information: done Off-topic: Learning to write English well is important, as it enables a programmer to document and evangelize his/her software, as well as appear competent to other programmers online. Trigonometry is used in 2D and 3D games to implement rotation and direction aspects. Knowing finance will come in handy if you want to write an accounting package. Knowing XYZ will come in handy if you want to write an XYZ package. Arguably on-topic: The Monad class in Haskell is based on a concept by the same name from category theory. Actually, Monads in Haskell are monads in the category of Haskell types and functions. Whatever that means...

    Read the article

  • LWJGL Determining whether or not a polygon is on-screen.

    - by Brandon oubiub
    Not sure whether this is an LWJGL or math question. I want to check whether a shape is on-screen, so that I don't have to render it if it isn't. First of all, is there any simple way to do this that I am overlooking? Like some method or something that I haven't found? I'm going to assume there isn't. I tried using my trigonometry skills, but it is hard to do this because of how glRotate also distorts the image a little for perspective and realism. Or, is there any way to easily determine if a ray starting from the camera, and going outward in a straight line intersects a shape? (I can probably do it with my math skillz, but is there an easier way?) By the way, I can easily determine the angle at which the camera is facing around the x and y axis. EDIT: Or, possibly, I could get the angles of a vector from the camera to the object, and compare those angles to my camera angles. But I have a feeling that the distorts from glRotate and glTranslate would be an issue. I'll try it though.

    Read the article

  • Implementing Circle Physics in Java

    - by Shijima
    I am working on a simple physics based game where 2 balls bounce off each other. I am following a tutorial, 2-Dimensional Elastic Collisions Without Trigonometry, for the collision reactions. I am using Vector2 from the LIBGDX library to handle vectors. I am a bit confused on how to implement step 6 in Java from the tutorial. Below is my current code, please note that the code strictly follows the tutorial and there are redundant pieces of code which I plan to refactor later. Note: refrences to this refer to ball 1, and ball refers to ball 2. /* * Step 1 * * Find the Normal, Unit Normal and Unit Tangential vectors */ Vector2 n = new Vector2(this.position[0] - ball.position[0], this.position[1] - ball.position[1]); Vector2 un = n.normalize(); Vector2 ut = new Vector2(-un.y, un.x); /* * Step 2 * * Create the initial (before collision) velocity vectors */ Vector2 v1 = this.velocity; Vector2 v2 = ball.velocity; /* * Step 3 * * Resolve the velocity vectors into normal and tangential components */ float v1n = un.dot(v1); float v1t = ut.dot(v1); float v2n = un.dot(v2); float v2t = ut.dot(v2); /* * Step 4 * * Find the new tangential Velocities after collision */ float v1tPrime = v1t; float v2tPrime = v2t; /* * Step 5 * * Find the new normal velocities */ float v1nPrime = v1n * (this.mass - ball.mass) + (2 * ball.mass * v2n) / (this.mass + ball.mass); float v2nPrime = v2n * (ball.mass - this.mass) + (2 * this.mass * v1n) / (this.mass + ball.mass); /* * Step 6 * * Convert the scalar normal and tangential velocities into vectors??? */

    Read the article

  • Is there any place to find real-world usage-style tutorials for programming languages?

    - by OleDid
    Let's face it. When you want to learn something completely new, be it mathematics or foreign languages, it's easiest to learn when you get real world scenarios in front of you, with theory applied. For example, trigonometry can be extremely interesting when applied to creation of 2D platform games. Norwegian can be really interesting to learn if you live in Norway. When I try to look at a new programming language, I always find these steps the hardest: What tools do I need to compile and how do I do it Introduction-step: Why is this programming language so cool? Where and how is it used? (The step I am looking for, real-world scenarios) The rest, deep diving into the language, pure theory and such, is often much easier if you have completed step 1 and 2. Because now you know what it's all about, and can just read the specification when you need to. What I ask is, do you have any recommendations for places I can find such material for programming languages? Be it websites or companies selling books in this style, I'm interested. Also, I am interested in all languages. (If I had found a "real-world usage" explained for even INTERCAL, I would be interested). In some other thread here, I found a book called "Seven Languages in Seven Weeks". This is kind of what I am looking for, but I believe there must be "more like this".

    Read the article

  • Java - Using Linear Coordinates to Check Against AI [closed]

    - by Oliver Jones
    I'm working on some artificial intelligence, and I want my AI not to run into given coordinates as these are references of a wall/boundary. To begin with, every time my AI hits a wall, it makes a reference to that position (x,y). When it hits the same wall three times, it uses linear check points to 'imagine' there is a wall going through these coordinates. I want to now prevent my AI from going into that wall again. To detect if my coordinates make a straight line, i use: private boolean collinear(double x1, double y1, double x2, double y2, double x3, double y3) { return (y1 - y2) * (x1 - x3) == (y1 - y3) * (x1 - x2); } This returns true is the given points are linear to one another. So my problems are: How do I determine whether my robot is approaching the wall from its current trajectory? Instead of Java 'imagining' theres a line from 1, to 3. But to 'imagine' a line all the way through these linear coordinantes, until infinity (or close). I have a feeling this is going to require some confusing trigonometry? (REPOST: http://stackoverflow.com/questions/13542592/java-using-linear-coordinates-to-check-against-ai)

    Read the article

  • Laser range finder, what language to use? Beginner advice

    - by DrOnline
    I hope this is the right place. I am a programming beginner, and I want to make a laser range finder, and I need advice about how to proceed etc. In a few weeks I will get a lot of dirt cheap 3-5V lasers and some cheap usb webcams. I will point the laser and webcam in parallel, and somehow use trigonometry and programming to determined distance. I have seen online that others made done it this way, I have purposefully not looked at the details too much because I want to develop it on my own, and learn, but I know the general outline. I have a general idea of how to proceed. The program loads in a picture from the webcam, and I dunno how images work really, but I imagine there is a format that is basically an array of RGB values.. is this right? I will load in the red values, and find the most red one. I know the height difference between the laser and the cam. I know the center dot in the image, I know the redmost dot. I'm sure there's some way to figure out some range there. TO THE POINT: 1) Is my reasoning sound thus far, especially in terms of image analysis? I don't need complete solutions, just general points 2) What I need to figure out, is what platform to use. I have an arduino... apparently, I've read it's too weak to process images. Read that online. I know some C I know some Python I have Matlab. Which is the best option? I do not need high sampling rates, I have not decided on whether it should be automated or whether I should make a GUI with a button to press for samples. I will keep it simple and expand I think. I also do not need it to be super accurate, I'm just having fun here. Advice!

    Read the article

  • Is there an algorithm for determining how much daylight there is?

    - by Pharaun
    Is there a function/algorithm that allows me to input the latitude and the approximate orbital position of the earth in so that I can determine how long the sun is up? IE during the winter it would show that the sun is only up a few hours in the far north hemisphere. I did some basic Google search and didn't find much so I was thinking that I might have to do some trigonometry that would allow me to calculate how much the earth is inclined or not toward the sun then use that information along with the latitude to figure out how much sunshine a site would be getting.

    Read the article

  • .NET Ascertaining mouse is on line drawn between two arbitrary points

    - by johnc
    I have an arrow drawn between two objects on a Winform. What would be the simplest way to determine that my mouse is currently hovering over, or near, this line. I have considered testing whether the mouse point intersects a square defined and extrapolated by the two points, however this would only be feasible if the two points had very similar x or y values. I am thinking, also, this problem is probably more in the realms of linear algebra rather than simple trigonometry, and whilst I do remember the simpler aspects of matrices, this problem is beyond my knowledge of linear algebra. On the other hand, if a .NET library can cope with the function, even better.

    Read the article

  • Fastest way to find the rotation of a vector

    - by kriss
    I have two 2D vectors, say u and v, defined by cartesian coordinates. Imagine that vectors are needles of a clock. I'm looking for the fastest way to find out, using python, if v is after or before u (or in other words find out in wich half plane is v, regarding to position of u). For the purpose of the problem if vectors are aligned answer should be before. It seems easy using some trigonometry, but I believe there should be a faster way using coordinates only. My test case: def after(u, v): """code here""" after((4,2), (6, 1)) : True after((4,2), (3, 3)) : False after((4,2), (2, 1)) : False after((4,2), (3, -3)) : True after((4,2), (-2, -5)) : True after((4,2), (-4, -2)) : False

    Read the article

  • Centre of a circle that intersects two points

    - by Jason
    Given two points in a 2D plane, and a circle of radius r that intersects both of those points, what would be the formula to calculate the centre of that circle? I realise there would two places the circle can be positioned. I would want the circle whose centre is encountered first in a clockwise direction when sweeping the line that joins the two points around one of those points, starting from an arbitrary angle. I guess that is the next stage in my problem, after I find an answer for the first part. I'm hoping the whole calculation can be done without trigonometry for speed. I'm starting with integer coordinates and will end with integer coordinates, if that helps.

    Read the article

  • The View-Matrix and Alternative Calculations

    - by P. Avery
    I'm working on a radiosity processor in DirectX 9. The process requires that the camera be placed at the center of a mesh face and a 'screenshot' be taken facing 5 different directions...forward...up...down...left...right... ...The problem is that when the mesh face is facing up( look vector: 0, 1, 0 )...a view matrix cannot be determined using standard trigonometry functions: Matrix4 LookAt( Vector3 eye, Vector3 target, Vector3 up ) { // The "look-at" vector. Vector3 zaxis = normal(target - eye); // The "right" vector. Vector3 xaxis = normal(cross(up, zaxis)); // The "up" vector. Vector3 yaxis = cross(zaxis, xaxis); // Create a 4x4 orientation matrix from the right, up, and at vectors Matrix4 orientation = { xaxis.x, yaxis.x, zaxis.x, 0, xaxis.y, yaxis.y, zaxis.y, 0, xaxis.z, yaxis.z, zaxis.z, 0, 0, 0, 0, 1 }; // Create a 4x4 translation matrix by negating the eye position. Matrix4 translation = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -eye.x, -eye.y, -eye.z, 1 }; // Combine the orientation and translation to compute the view matrix return ( translation * orientation ); } The above function comes from http://3dgep.com/?p=1700... ...Is there a mathematical approach to this problem? Edit: A problem occurs when setting the view matrix to up or down directions, here is an example of the problem when facing down: D3DXVECTOR4 vPos( 3, 3, 3, 1 ), vEye( 1.5, 3, 3, 1 ), vLook( 0, -1, 0, 1 ), vRight( 1, 0, 0, 1 ), vUp( 0, 0, 1, 1 ); D3DXMATRIX mV, mP; D3DXMatrixPerspectiveFovLH( &mP, D3DX_PI / 2, 1, 0.5f, 2000.0f ); D3DXMatrixIdentity( &mV ); memcpy( ( void* )&mV._11, ( void* )&vRight, sizeof( D3DXVECTOR3 ) ); memcpy( ( void* )&mV._21, ( void* )&vUp, sizeof( D3DXVECTOR3 ) ); memcpy( ( void* )&mV._31, ( void* )&vLook, sizeof( D3DXVECTOR3 ) ); memcpy( ( void* )&mV._41, ( void* )&(-vEye), sizeof( D3DXVECTOR3 ) ); D3DXVec4Transform( &vPos, &vPos, &( mV * mP ) ); Results: vPos = D3DXVECTOR3( 1.5, -6, -0.5, 0 ) - this vertex is not properly processed by shader as the homogenous w value is 0 it cannot be normalized to a position within device space...

    Read the article

  • Collision detection - Smooth wall sliding, no bounce effect

    - by Joey
    I'm working on a basic collision detection system that provides point - OBB collision detection. I have around 200 cubes in my environment and I check (for now) each of them in turn and see if it collides. If it does I return the colliding face's normal, save the old player position and do some trigonometry to return a new player position for my wall sliding. edit I'll define my meaning of wall sliding: If a player walks in a vertical slope and has a slight horizontal rotation to the left or the right and keeps walking forward in the wall the player should slide a little to the right/left while continually walking towards the wall till he left the wall. Thus, sliding along the wall. Everything works fine and with multiple objects as well but I still have one problem I can't seem to figure out: smooth wall sliding. In my current implementation sliding along the walls make my player bounce like a mad man (especially noticable with gravity on and moving forward). I have a velocity/direction vector, a normal vector from the collided plane and an old and new player position. First I negate the normal vector and get my new velocity vector by substracting the inverted normal from my direction vector (which is the vector to slide along the wall) and I add this vector to my new Player position and recalculate the direction vector (in case I have multiple collisions). I know I am missing some step but I can't seem to figure it out. Here is my code for the collision detection (run every frame): Vector direction; Vector newPos(camera.GetOriginX(), camera.GetOriginY(), camera.GetOriginZ()); direction = newPos - oldPos; // Direction vector // Check for collision with new position for(int i = 0; i < NUM_OBJECTS; i++) { Vector normal = objects[i].CheckCollision(newPos.x, newPos.y, newPos.z, direction.x, direction.y, direction.z); if(normal != Vector::NullVector()) { // Get inverse normal (direction STRAIGHT INTO wall) Vector invNormal = normal.Negative(); Vector wallDir = direction - invNormal; // We know INTO wall, and DIRECTION to wall. Substract these and you got slide WALL direction newPos = oldPos + wallDir; direction = newPos - oldPos; } } Any help would be greatly appreciated! FIX I eventually got things up and running how they should thanks to Krazy, I'll post the updated code listing in case someone else comes upon this problem! for(int i = 0; i < NUM_OBJECTS; i++) { Vector normal = objects[i].CheckCollision(newPos.x, newPos.y, newPos.z, direction.x, direction.y, direction.z); if(normal != Vector::NullVector()) { Vector invNormal = normal.Negative(); invNormal = invNormal * (direction * normal).Length(); // Change normal to direction's length and normal's axis Vector wallDir = direction - invNormal; newPos = oldPos + wallDir; direction = newPos - oldPos; } }

    Read the article

  • Simulating 3D 'cards' with just orthographic rendering

    - by meds
    I am rendering textured quads from an orthographic perspective and would like to simulate 'depth' by modifying UVs and the vertex positions of the quads four points (top left, top right, bottom left, bottom right). I've found if I make the top left and bottom right corners y position be the same I don't get a linear 'skew' but rather a warped one where the texture covering the top triangle (which makes up the quad) seems to get squashed while the bottom triangles texture looks normal. I can change UVs, any of the four points on the quad (but only in 2D space, it's orthographic projection anyway so 3D space won't matter much). So basically I'm trying to simulate perspective on a two dimensional quad in orthographic projection, any ideas? Is it even mathematically possible/feasible? ideally what I'd like is a situation where I can set an x/y rotation as well as a virtual z 'position' (which simulates z depth) through a function and see it internally calclate the positions/uvs to create the 3D effect. It seems like this should all be mathematical where a set of 2D transforms can be applied to each corner of the quad to simulate depth, I just don't know how to make it happen. I'd guess it requires trigonometry or something, I'm trying to crunch the math but not making much progress. here's what I mean: Top left is just the card, center is the card with a y rotation of X degrees and right most is a card with an x and y rotation of different degrees.

    Read the article

  • Drawing an honeycomb with as3

    - by vitto
    Hi, I'm trying to create an honeycomb with as3 but I have some problem on cells positioning. I've already created the cells (not with code) and for cycled them to a funcion and send to it the parameters which what I thought was need (the honeycomb cell is allready on a sprite container in the center of the stage). to see the structure of the cycle and which parameters passes, please see the example below, the only thing i calculate in placeCell is the angle which I should obtain directly inside tha called function Note: the angle is reversed but it isn't important, and the color are useful in example only for visually divide cases. My for cycle calls placeCell and passes cell, current_case, counter (index) and the honeycomb cell_lv (cell level). I thought it was what i needed but I'm not skilled in geometry and trigonometry, so I don't know how to position cells correctly: function placeCell (cell:Sprite, current_case:int, counter:int, cell_lv:int):void { var margin:int = 2; var angle:Number = (360 / (cell_lv * 6)) * (current_case + counter); var radius:Number = (cell.width + margin) * cell_lv; cell.x = radius * Math.cos (angle); cell.y = radius * Math.sin (angle); trace ("LV " + cell_lv + " current_case " + current_case + " counter " + counter + " angle " + angle + " radius " + radius) } how can I do to solve it?

    Read the article

  • why do we need advanced knowledge of mathematics & physics for programming?

    - by Sumeet
    Guys, I have been very good in mathematics and physics in my schools and colleges. Right now I am a programmer. Even in the colleges I have to engrossed my self into computers and programming things all the time. As I used to like it very much. But I have always felt the lack of advanced mathematics and physics in all the work I have done (Programs). Programming never asked me any advanced mathematics and physics knowledge in what I was very good. It always ask u some optimized loops, and different programming technologies which has never been covered in advanced mathematics and physics. Even at the time of selection in big College , such a kind of advanced knowledge is required. Time by time I got out of touch of all that facts and concepts (advanced mathematics and physics). And now after, 5 years in job I found it hard to resolve Differentiations and integrations from Trigonometry. Which sometimes make me feel like I have wasted time in those concepts because they are never used. (At that time I knew that I am going to be a programmer) If one need to be a programmer why do all this advanced knowledge is required. One can go with elementry knowledge a bit more. You never got to think like scientists and R&D person in your Schols and colleges for being a programmer? Just think and let me know your thoughts. I must be wrong somewhere in what I think , but not able to figure that out..? Regards Sumeet

    Read the article

  • Plotting an Arc in Discrete Steps

    - by phobos51594
    Good afternoon, Background My question relates to the plotting of an arbitrary arc in space using discrete steps. It is unique, however, in that I am not drawing to a canvas in the typical sense. The firmware I am designing is for a gcode interpreter for a CNC mill that will translate commands into stepper motor movements. Now, I have already found a similar question on this very site, but the methodology suggested (Bresenham's Algorithm) appears to be incompatable for moving an object in space, as it only relies on the calculation of one octant of a circle which is then mirrored about the remaining axes of symmetry. Furthermore, the prescribed method of calculation an arc between two arbitrary angles relies on trigonometry (I am implementing on a microcontroller and would like to avoid costly trig functions, if possible) and simply not taking the steps that are out of the range. Finally, the algorithm only is designed to work in one rotational direction (e.g. counterclockwise). Question So, on to the actual question: Does anyone know of a general-purpose algorithm that can be used to "draw" an arbitrary arc in discrete steps while still giving respect to angular direction (CW / CCW)? The final implementation will be done in C, but the language for the purpose of the question is irrelevant. Thank you in advance. References S.O post on drawing a simple circle using Bresenham's Algorithm: "Drawing" an arc in discrete x-y steps Wiki page describing Bresenham's Algorithm for a circle http://en.wikipedia.org/wiki/Midpoint_circle_algorithm Gcode instructions to be implemented (see. G2 and G3) http://linuxcnc.org/docs/html/gcode.html

    Read the article

  • Scientific Algorithms that can produce imagery, pseudocode perhaps?

    - by Ross
    Hello, I have a client who are based in the field of mathematics. We are developing, amongst other things, a website. I like to create a mock-up of a drawing tool that an produce some imagery in the background based on some scientific algorithms. The intention being that the may client, later, may create there own. (They use emacs for everything, great client.) I'm look for an answer of where or what to go looking for. Not code specific, pseudocode even, as we can adapt and have not yet settled on a platform. I'm afraid my mathematic stops at the power of two and some trigonometry. Appreciated if they're are any mathematics related students/academics how could enlighten me? What to search for will be accepted? Edit: To summarise/clarify, I want to draw pretty pictures (the design perspective). I want them to have some context (i.e. not just for the sake of pretty images but have some explanation available). In essence I would to create a rendering engine which we can draw the images and we set the style parameters: line, colour, etc... But to pursue this option I want to experiment myself. Thanks Ross

    Read the article

  • iPhone: How to use CGContextConcatCTM for saving a transformed image properly?

    - by Irene
    I am making an iPhone application that loads an image from the camera, and then the user can select a second image from the library, move/scale/rotate that second image, and then save the result. I use two UIImageViews in IB as placeholders, and then apply transformations while touching/pinching. The problem comes when I have to save both images together. I use a rect of the size of the first image and pass it to UIGraphicsBeginImageContext. Then I tried to use CGContextConcatCTM but I can't understand how it works: CGRect rect = CGRectMake(0, 0, img1.size.width, img1.size.height); // img1 from camera UIGraphicsBeginImageContext(rect.size); // Start drawing CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextClearRect(ctx, rect); // Clear whole thing [img1 drawAtPoint:CGPointZero]; // Draw background image at 0,0 CGContextConcatCTM(ctx, img2.transform); // Apply the transformations of the 2nd image But what do I need to do next? What information is being held in the img2.transform matrix? The documentation for CGContextConcatCTM doesn't help me that much unfortunately.. Right now I'm trying to solve it by calculating the points and the angle using trigonometry (with the help of this answer), but since the transformation is there, there has to be an easier and more elgant way to do this, right?

    Read the article

  • Which of these algorithms is best for my goal?

    - by JonathonG
    I have created a program that restricts the mouse to a certain region based on a black/white bitmap. The program is 100% functional as-is, but uses an inaccurate, albeit fast, algorithm for repositioning the mouse when it strays outside the area. Currently, when the mouse moves outside the area, basically what happens is this: A line is drawn between a pre-defined static point inside the region and the mouse's new position. The point where that line intersects the edge of the allowed area is found. The mouse is moved to that point. This works, but only works perfectly for a perfect circle with the pre-defined point set in the exact center. Unfortunately, this will never be the case. The application will be used with a variety of rectangles and irregular, amorphous shapes. On such shapes, the point where the line drawn intersects the edge will usually not be the closest point on the shape to the mouse. I need to create a new algorithm that finds the closest point to the mouse's new position on the edge of the allowed area. I have several ideas about this, but I am not sure of their validity, in that they may have far too much overhead. While I am not asking for code, it might help to know that I am using Objective C / Cocoa, developing for OS X, as I feel the language being used might affect the efficiency of potential methods. My ideas are: Using a bit of trigonometry to project lines would work, but that would require some kind of intense algorithm to test every point on every line until it found the edge of the region... That seems too resource intensive since there could be something like 200 lines that would have each have to have as many as 200 pixels checked for black/white.... Using something like an A* pathing algorithm to find the shortest path to a black pixel; however, A* seems resource intensive, even though I could probably restrict it to only checking roughly in one direction. It also seems like it will take more time and effort than I have available to spend on this small portion of the much larger project I am working on, correct me if I am wrong and it would not be a significant amount of code (100 lines or around there). Mapping the border of the region before the application begins running the event tap loop. I think I could accomplish this by using my current line-based algorithm to find an edge point and then initiating an algorithm that checks all 8 pixels around that pixel, finds the next border pixel in one direction, and continues to do this until it comes back to the starting pixel. I could then store that data in an array to be used for the entire duration of the program, and have the mouse re-positioning method check the array for the closest pixel on the border to the mouse target position. That last method would presumably execute it's initial border mapping fairly quickly. (It would only have to map between 2,000 and 8,000 pixels, which means 8,000 to 64,000 checked, and I could even permanently store the data to make launching faster.) However, I am uncertain as to how much overhead it would take to scan through that array for the shortest distance for every single mouse move event... I suppose there could be a shortcut to restrict the number of elements in the array that will be checked to a variable number starting with the intersecting point on the line (from my original algorithm), and raise/lower that number to experiment with the overhead/accuracy tradeoff. Please let me know if I am over thinking this and there is an easier way that will work just fine, or which of these methods would be able to execute something like 30 times per second to keep mouse movement smooth, or if you have a better/faster method. I've posted relevant parts of my code below for reference, and included an example of what the area might look like. (I check for color value against a loaded bitmap that is black/white.) // // This part of my code runs every single time the mouse moves. // CGPoint point = CGEventGetLocation(event); float tX = point.x; float tY = point.y; if( is_in_area(tX,tY, mouse_mask)){ // target is inside O.K. area, do nothing }else{ CGPoint target; //point inside restricted region: float iX = 600; // inside x float iY = 500; // inside y // delta to midpoint between iX,iY and tX,tY float dX; float dY; float accuracy = .5; //accuracy to loop until reached do { dX = (tX-iX)/2; dY = (tY-iY)/2; if(is_in_area((tX-dX),(tY-dY),mouse_mask)){ iX += dX; iY += dY; } else { tX -= dX; tY -= dY; } } while (abs(dX)>accuracy || abs(dY)>accuracy); target = CGPointMake(roundf(tX), roundf(tY)); CGDisplayMoveCursorToPoint(CGMainDisplayID(),target); } Here is "is_in_area(int x, int y)" : bool is_in_area(NSInteger x, NSInteger y, NSBitmapImageRep *mouse_mask){ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSUInteger pixel[4]; [mouse_mask getPixel:pixel atX:x y:y]; if(pixel[0]!= 0){ [pool release]; return false; } [pool release]; return true; }

    Read the article

  • Scared of Calculus - Required to pass Differential Calculus as part of my Computer science major

    - by ke3pup
    Hi guys I'm finishing my Computer science degree in university but my fear of maths (lack of background knowledge) made me to leave all my maths units til' the very end which is now. i either take them on and pass or have to give up. I've passed all my programming units easily but knowing my poor maths skills won't do i've been staying clear of the maths units. I have to pass Differential Calculus and Linear Algebra first. With a help of book named "Linear Algebra: A Modern Introduction" i'm finding myself on track and i think i can pass the Linear Algebra unit. But with differential calculus i can't find a book to help me. They're either too advanced or just too simple for what i have to learn. The things i'm required to know for this units are: Set notation, the real number line, Complex numbers in cartesian form. Complex plane, modulus. Complex numbers in polar form. De Moivre’s Theorem. Complex powers and nth roots. Definition of ei? and ez for z complex. Applications to trigonometry. Revision of domain and range of a function Working in R3. Curves and surfaces. Functions of 2 variables. Level curves.Partial derivatives and tangent planes. The derivative as a difference quotient. Geometric significance of the derivative. Discussion of limit. Higher order partial derivatives. Limits of f(x,y). Continuity. Maxima and minima of f(x,y). The chain rule. Implicit differentiation. Directional derivatives and the gradient. Limit laws, l’Hoˆpital’s rule, composition law. Definition of sinh and cosh and their inverses. Taylor polynomials. The remainder term. Taylor series. Is there a book to help me get on track with the above? Being a student i can't buy too many books hence why i'm looking for a book that covers topics I need to know. The University library has a fairly limited collection which i took as loan but didn't find useful as it was too complex.

    Read the article

  • Detecting Acceleration in a car (iPhone Accelerometer)

    - by TheGazzardian
    Hello, I am working on an iPhone app where we are trying to calculate the acceleration of a moving car. Similar apps have accomplished this (Dynolicious), but the difference is that this app is designed to be used during general city driving, not on a drag strip. This leads us to one big concern that Dynolicious was luckily able to avoid: hills. Yes, hills. There are two important stages to this: calibration, and actual driving. Our initial run was simple and suffered the consequences. During the calibration stage, I took the average force on the phone, and during running, I just subtracted the average force from the current force to get the current acceleration this frame. The problem with this is that the typical car receives much more force than just the forward force - everything from turning to potholes was causing the values to go out of sync with what was really happening. The next run was to add the condition that the iPhone must be oriented in such a way that the screen was facing toward the back of the car. Using this method, I attempted to follow only force on the z-axis, but this obviously lead to problems unless the iPhone was oriented directly upright, because of gravity. Some trigonometry later, and I had managed to work gravity out of the equation, so that the car was actually being read very, very well by the iPhone. Until I hit a slope. As soon as the angle of the car changed, suddenly I was receiving accelerations and decelerations that didn't make sense, and we were once again going out of sync. Talking with someone a lot smarter than me at math lead to a solution that I have been trying to implement for longer than I would like to admit. It's steps are as follows: 1) During calibration, measure gravity as a vector instead of a size. Store that vector. 2) When the car initially moves forward, take the vector of motion and subtract gravity. Use this as the forward momentum. (Ignore, for now, the user cases where this will be difficult and let's concentrate on the math :) 3) From the forward vector and the gravity vector, construct a plane. 4) Whenever a force is received, project it onto said plane to get rid of sideways force/etc. 5) Then, use that force, the known magnitude of gravity, and the known direction of forward motion to essentially solve a triangle to get the forward vector. The problem that is causing the most difficulty in this new system is not step 5, which I have gotten to the point where all the numbers look as they should. The difficult part is actually the detection of the forward vector. I am selecting vectors whose magnitude exceeds gravity, and from there, averaging them and subtracting gravity. (I am doing some error checking to make sure that I am not using a force just because the iPhone accelerometer was off by a bit, which happens more frequently than I would like). But if I plot these vectors that I am using, they actually vary by an angle of about 20-30 degrees, which can lead to some strong inaccuracies. The end result is that the app is even more inaccurate now than before. So basically - all you math and iPhone brains out there - any glaring errors? Any potentially better solutions? Any experience that could be useful at all? Award: offering a bounty of $250 to the first answer that leads to a solution.

    Read the article

  • Ball to Ball Collision - Detection and Handling

    - by Simucal
    With the help of the Stack Overflow community I've written a pretty basic-but fun physics simulator. You click and drag the mouse to launch a ball. It will bounce around and eventually stop on the "floor". My next big feature I want to add in is ball to ball collision. The ball's movement is broken up into a x and y speed vector. I have gravity (small reduction of the y vector each step), I have friction (small reduction of both vectors each collision with a wall). The balls honestly move around in a surprisingly realistic way. I guess my question has two parts: What is the best method to detect ball to ball collision? Do I just have an O(n^2) loop that iterates over each ball and checks every other ball to see if it's radius overlaps? What equations do I use to handle the ball to ball collisions? Physics 101 How does it effect the two balls speed x/y vectors? What is the resulting direction the two balls head off in? How do I apply this to each ball? Handling the collision detection of the "walls" and the resulting vector changes were easy but I see more complications with ball-ball collisions. With walls I simply had to take the negative of the appropriate x or y vector and off it would go in the correct direction. With balls I don't think it is that way. Some quick clarifications: for simplicity I'm ok with a perfectly elastic collision for now, also all my balls have the same mass right now, but I might change that in the future. In case anyone is interested in playing with the simulator I have made so far, I've uploaded the source here (EDIT: Check the updated source below). Edit: Resources I have found useful 2d Ball physics with vectors: 2-Dimensional Collisions Without Trigonometry.pdf 2d Ball collision detection example: Adding Collision Detection Success! I have the ball collision detection and response working great! Relevant code: Collision Detection: for (int i = 0; i < ballCount; i++) { for (int j = i + 1; j < ballCount; j++) { if (balls[i].colliding(balls[j])) { balls[i].resolveCollision(balls[j]); } } } This will check for collisions between every ball but skip redundant checks (if you have to check if ball 1 collides with ball 2 then you don't need to check if ball 2 collides with ball 1. Also, it skips checking for collisions with itself). Then, in my ball class I have my colliding() and resolveCollision() methods: public boolean colliding(Ball ball) { float xd = position.getX() - ball.position.getX(); float yd = position.getY() - ball.position.getY(); float sumRadius = getRadius() + ball.getRadius(); float sqrRadius = sumRadius * sumRadius; float distSqr = (xd * xd) + (yd * yd); if (distSqr <= sqrRadius) { return true; } return false; } public void resolveCollision(Ball ball) { // get the mtd Vector2d delta = (position.subtract(ball.position)); float d = delta.getLength(); // minimum translation distance to push balls apart after intersecting Vector2d mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d); // resolve intersection -- // inverse mass quantities float im1 = 1 / getMass(); float im2 = 1 / ball.getMass(); // push-pull them apart based off their mass position = position.add(mtd.multiply(im1 / (im1 + im2))); ball.position = ball.position.subtract(mtd.multiply(im2 / (im1 + im2))); // impact speed Vector2d v = (this.velocity.subtract(ball.velocity)); float vn = v.dot(mtd.normalize()); // sphere intersecting but moving away from each other already if (vn > 0.0f) return; // collision impulse float i = (-(1.0f + Constants.restitution) * vn) / (im1 + im2); Vector2d impulse = mtd.multiply(i); // change in momentum this.velocity = this.velocity.add(impulse.multiply(im1)); ball.velocity = ball.velocity.subtract(impulse.multiply(im2)); } Source Code: Complete source for ball to ball collider. Binary: Compiled binary in case you just want to try bouncing some balls around. If anyone has some suggestions for how to improve this basic physics simulator let me know! One thing I have yet to add is angular momentum so the balls will roll more realistically. Any other suggestions? Leave a comment!

    Read the article

  • creating a 3d plane using Frank Luna's technique

    - by numerical25
    I am creating a 3d plane that lays on the x and z axis. and has hills that extend on the y axis. bulk of the code looks like this float PeaksAndValleys::getHeight(float x, float z)const { return 0.3f*( z*sinf(0.1f*x) + x*cosf(0.1f*z) ); } void PeaksAndValleys::init(ID3D10Device* device, DWORD m, DWORD n, float dx) { md3dDevice = device; mNumRows = m; mNumCols = n; mNumVertices = m*n; mNumFaces = (m-1)*(n-1)*2; // Create the geometry and fill the vertex buffer. std::vector<Vertex> vertices(mNumVertices); float halfWidth = (n-1)*dx*0.5f; float halfDepth = (m-1)*dx*0.5f; for(DWORD i = 0; i < m; ++i) { float z = halfDepth - i*dx; for(DWORD j = 0; j < n; ++j) { float x = -halfWidth + j*dx; // Graph of this function looks like a mountain range. float y = getHeight(x,z); vertices[i*n+j].pos = D3DXVECTOR3(x, y, z); // Color the vertex based on its height. if( y < -10.0f ) vertices[i*n+j].color = BEACH_SAND; else if( y < 5.0f ) vertices[i*n+j].color = LIGHT_YELLOW_GREEN; else if( y < 12.0f ) vertices[i*n+j].color = DARK_YELLOW_GREEN; else if( y < 20.0f ) vertices[i*n+j].color = DARKBROWN; else vertices[i*n+j].color = WHITE; } } D3D10_BUFFER_DESC vbd; vbd.Usage = D3D10_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex) * mNumVertices; vbd.BindFlags = D3D10_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vertices[0]; HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mVB)); // Create the index buffer. The index buffer is fixed, so we only // need to create and set once. std::vector<DWORD> indices(mNumFaces*3); // 3 indices per face // Iterate over each quad and compute indices. int k = 0; for(DWORD i = 0; i < m-1; ++i) { for(DWORD j = 0; j < n-1; ++j) { indices[k] = i*n+j; indices[k+1] = i*n+j+1; indices[k+2] = (i+1)*n+j; indices[k+3] = (i+1)*n+j; indices[k+4] = i*n+j+1; indices[k+5] = (i+1)*n+j+1; k += 6; // next quad } } D3D10_BUFFER_DESC ibd; ibd.Usage = D3D10_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(DWORD) * mNumFaces*3; ibd.BindFlags = D3D10_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &indices[0]; HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mIB)); } My question pretains to the cosf and sinf. I am formiluar with trigonometry and I understand sin, cosine, and tangent. but I am not formiluar with cosf and sinf and what they do. From looking at this example. they have alot to do with finding a y value.

    Read the article

  • How to find vector for the quaternion from X Y Z rotations

    - by can poyrazoglu
    I am creating a very simple project on OpenGL and I'm stuck with rotations. I am trying to rotate an object indepentdently in all 3 axes: X, Y, and Z. I've had sleepless nights due to the "gimbal lock" problem after rotating about one axis. I've then learned that quaternions would solve my problem. I've researched about quaternions and implementd it, but I havent't been able to convert my rotations to quaternions. For example, if I want to rotate around Z axis 90 degrees, I just create the {0,0,1} vector for my quaternion and rotate it around that axis 90 degrees using the code here: http://iphonedevelopment.blogspot.com/2009/06/opengl-es-from-ground-up-part-7_04.html (the most complicated matrix towards the bottom) That's ok for one vector, but, say, I first want to rotate 90 degrees around Z, then 90 degrees around X (just as an example). What vector do I need to pass in? How do I calculate that vector. I am not good with matrices and trigonometry (I know the basics and the general rules, but I'm just not a whiz) but I need to get this done. There are LOTS of tutorials about quaternions, but I seem to understand none (or they don't answer my question). I just need to learn to construct the vector for rotations around more than one axis combined. UPDATE: I've found this nice page about quaternions and decided to implement them this way: http://www.cprogramming.com/tutorial/3d/quaternions.html Here is my code for quaternion multiplication: void cube::quatmul(float* q1, float* q2, float* resultRef){ float w = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3]; float x = q1[0]*q2[1] + q1[1]*q2[0] + q1[2]*q2[3] - q1[3]*q2[2]; float y = q1[0]*q2[2] - q1[1]*q2[3] + q1[2]*q2[0] + q1[3]*q2[1]; float z = q1[0]*q2[3] + q1[1]*q2[2] - q1[2]*q2[1] + q1[3]*q2[0]; resultRef[0] = w; resultRef[1] = x; resultRef[2] = y; resultRef[3] = z; } Here is my code for applying a quaternion to my modelview matrix (I have a tmodelview variable that is my target modelview matrix): void cube::applyquat(){ float& x = quaternion[1]; float& y = quaternion[2]; float& z = quaternion[3]; float& w = quaternion[0]; float magnitude = sqrtf(w * w + x * x + y * y + z * z); if(magnitude == 0){ x = 1; w = y = z = 0; }else if(magnitude != 1){ x /= magnitude; y /= magnitude; z /= magnitude; w /= magnitude; } tmodelview[0] = 1 - (2 * y * y) - (2 * z * z); tmodelview[1] = 2 * x * y + 2 * w * z; tmodelview[2] = 2 * x * z - 2 * w * y; tmodelview[3] = 0; tmodelview[4] = 2 * x * y - 2 * w * z; tmodelview[5] = 1 - (2 * x * x) - (2 * z * z); tmodelview[6] = 2 * y * z - 2 * w * x; tmodelview[7] = 0; tmodelview[8] = 2 * x * z + 2 * w * y; tmodelview[9] = 2 * y * z + 2 * w * x; tmodelview[10] = 1 - (2 * x * x) - (2 * y * y); tmodelview[11] = 0; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadMatrixf(tmodelview); glMultMatrixf(modelview); glGetFloatv(GL_MODELVIEW_MATRIX, tmodelview); glPopMatrix(); } And my code for rotation (that I call externally), where quaternion is a class variable of the cube: void cube::rotatex(int angle){ float quat[4]; float ang = angle * PI / 180.0; quat[0] = cosf(ang / 2); quat[1] = sinf(ang/2); quat[2] = 0; quat[3] = 0; quatmul(quat, quaternion, quaternion); applyquat(); } void cube::rotatey(int angle){ float quat[4]; float ang = angle * PI / 180.0; quat[0] = cosf(ang / 2); quat[1] = 0; quat[2] = sinf(ang/2); quat[3] = 0; quatmul(quat, quaternion, quaternion); applyquat(); } void cube::rotatez(int angle){ float quat[4]; float ang = angle * PI / 180.0; quat[0] = cosf(ang / 2); quat[1] = 0; quat[2] = 0; quat[3] = sinf(ang/2); quatmul(quat, quaternion, quaternion); applyquat(); } I call, say rotatex, for 10-11 times for rotating only 1 degree, but my cube gets rotated almost 90 degrees after 10-11 times of 1 degree, which doesn't make sense. Also, after calling rotation functions in different axes, My cube gets skewed, gets 2 dimensional, and disappears (a column in modelview matrix becomes all zeros) irreversibly, which obviously shouldn't be happening with a correct implementation of the quaternions.

    Read the article

< Previous Page | 1 2 3