Search Results

Search found 434 results on 18 pages for 'cos'.

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

  • Is there an easy way to type in common math symbols?

    - by srcspider
    Disclaimer: I'm sure someone is going to moan about easy-of-use, for the purpose of this question consider readability to be the only factor that matters So I found this site that converts to easting northing, it's not really important what that even means but here's how the piece of javascript looks. /** * Convert Ordnance Survey grid reference easting/northing coordinate to (OSGB36) latitude/longitude * * @param {OsGridRef} gridref - easting/northing to be converted to latitude/longitude * @returns {LatLonE} latitude/longitude (in OSGB36) of supplied grid reference */ OsGridRef.osGridToLatLong = function(gridref) { var E = gridref.easting; var N = gridref.northing; var a = 6377563.396, b = 6356256.909; // Airy 1830 major & minor semi-axes var F0 = 0.9996012717; // NatGrid scale factor on central meridian var f0 = 49*Math.PI/180, ?0 = -2*Math.PI/180; // NatGrid true origin var N0 = -100000, E0 = 400000; // northing & easting of true origin, metres var e2 = 1 - (b*b)/(a*a); // eccentricity squared var n = (a-b)/(a+b), n2 = n*n, n3 = n*n*n; // n, n², n³ var f=f0, M=0; do { f = (N-N0-M)/(a*F0) + f; var Ma = (1 + n + (5/4)*n2 + (5/4)*n3) * (f-f0); var Mb = (3*n + 3*n*n + (21/8)*n3) * Math.sin(f-f0) * Math.cos(f+f0); var Mc = ((15/8)*n2 + (15/8)*n3) * Math.sin(2*(f-f0)) * Math.cos(2*(f+f0)); var Md = (35/24)*n3 * Math.sin(3*(f-f0)) * Math.cos(3*(f+f0)); M = b * F0 * (Ma - Mb + Mc - Md); // meridional arc } while (N-N0-M >= 0.00001); // ie until < 0.01mm var cosf = Math.cos(f), sinf = Math.sin(f); var ? = a*F0/Math.sqrt(1-e2*sinf*sinf); // nu = transverse radius of curvature var ? = a*F0*(1-e2)/Math.pow(1-e2*sinf*sinf, 1.5); // rho = meridional radius of curvature var ?2 = ?/?-1; // eta = ? var tanf = Math.tan(f); var tan2f = tanf*tanf, tan4f = tan2f*tan2f, tan6f = tan4f*tan2f; var secf = 1/cosf; var ?3 = ?*?*?, ?5 = ?3*?*?, ?7 = ?5*?*?; var VII = tanf/(2*?*?); var VIII = tanf/(24*?*?3)*(5+3*tan2f+?2-9*tan2f*?2); var IX = tanf/(720*?*?5)*(61+90*tan2f+45*tan4f); var X = secf/?; var XI = secf/(6*?3)*(?/?+2*tan2f); var XII = secf/(120*?5)*(5+28*tan2f+24*tan4f); var XIIA = secf/(5040*?7)*(61+662*tan2f+1320*tan4f+720*tan6f); var dE = (E-E0), dE2 = dE*dE, dE3 = dE2*dE, dE4 = dE2*dE2, dE5 = dE3*dE2, dE6 = dE4*dE2, dE7 = dE5*dE2; f = f - VII*dE2 + VIII*dE4 - IX*dE6; var ? = ?0 + X*dE - XI*dE3 + XII*dE5 - XIIA*dE7; return new LatLonE(f.toDegrees(), ?.toDegrees(), GeoParams.datum.OSGB36); } I found that to be a really nice way of writing an algorythm, at least as far as redability is concerned. Is there any way to easily write the special symbols. And by easily write I mean NOT copy/paste them.

    Read the article

  • error: switch quantity not an integer

    - by nikeunltd
    I have researched my issue all over StackOverflow and multi-google links, and I am still confused. I figured the best thing for me is ask... Im creating a simple command line calculator. Here is my code so far: const std::string Calculator::SIN("sin"); const std::string Calculator::COS("cos"); const std::string Calculator::TAN("tan"); const std::string Calculator::LOG( "log" ); const std::string Calculator::LOG10( "log10" ); void Calculator::set_command( std::string cmd ) { for(unsigned i = 0; i < cmd.length(); i++) { cmd[i] = tolower(cmd[i]); } command = cmd; } bool Calculator::is_legal_command() const { switch(command) { case TAN: case SIN: case COS: case LOG: case LOG10: return true; break; default: return false; break; } } the error i get is: Calculator.cpp: In member function 'bool Calculator::is_trig_command() const': Calculator.cpp: error: switch quantity not an integer Calculator.cpp: error: 'Calculator::TAN' cannot appear in a constant-expression Calculator.cpp: error: 'Calculator::SIN' cannot appear in a constant-expression Calculator.cpp: error: 'Calculator::COS' cannot appear in a constant-expression The mighty internet, it says strings are allowed to be used in switch statements. Thanks everyone, I appreciate your help.

    Read the article

  • android DES decrypt file : pad block corrupted

    - by Kenny Chang
    public class TestDES { Key key; public TestDES(String str) { getKey(str); } public void getKey(String strKey) { try { KeyGenerator _generator = KeyGenerator.getInstance("DES"); _generator.init(new SecureRandom(strKey.getBytes())); this.key = _generator.generateKey(); _generator = null; } catch (Exception e) { throw new RuntimeException("Error initializing SqlMap class. Cause: " + e); } } public void decrypt(String file, String dest) throws Exception { Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, this.key); InputStream is = new FileInputStream(file); OutputStream out = new FileOutputStream(dest); CipherOutputStream cos = new CipherOutputStream(out, cipher); byte[] buffer = new byte[1024 * 1024 * 6]; int r; while ((r = is.read(buffer)) >= 0) { cos.write(buffer, 0, r); } cos.close();a out.close(); is.close(); } } The code works well on PC JAVA Program, but not on android.The error "pad block corrupted" happended at 'cos.close();' LogCat shows:" 03-10 07:43:04.431: WARN/System.err(23765): java.io.IOException: pad block corrupted 03-10 07:43:04.460: WARN/System.err(23765): at javax.crypto.CipherOutputStream.close(CipherOutputStream.java:157) "

    Read the article

  • MATLAB intersection of 2 surfaces

    - by caglarozdag
    Hi everyone, I consider myself a beginner in MATLAB so bear with me if the answer to my question is an obvious one. Phi=0:pi/100:2*pi; Theta=0:pi/100:2*pi; [PHI,THETA]=meshgrid(Phi,Theta); R=(1 + cos(PHI).*cos(PHI)).*(1 + cos(THETA).*cos(THETA)); [X,Y,Z]=sph2cart(THETA,PHI,R); surf(X,Y,Z); %display hold on; x1=-4:.1:4; [X1,Y1] = meshgrid(x1); a=1.8; b=0; c=3; d=0; Z1=(d- a * X1 - b * Y1)/c; shading flat; surf(X1,Y1,Z1); I have written this code which plots a 3d cartesian plot of a plane intersecting a peanut shaped object at an angle. I need to get the intersection of these on 2D (going to be the outline of a peanut, but a bit skewed since the intersection happens at an angle), but don't know how. Thanks

    Read the article

  • OpenGL - drawing 2D polygons shapes with texture

    - by plonkplonk
    I am trying to make a few effects in a C+GL game. So far I draw all my sprites as a quad, and it works. However, I am trying to make a large ring appear at times, with a texture following that ring, as it takes less memory than a quad with the ring texture inside. The type of ring I want to make is not a round-shaped GL mesh ring (the "tube" type) but a "paper" 2D ring. That way I can modify the "width" of the ring, getting more of the effect than a simple quad+ring texture. So far all my attempts have been...kind of ridiculous, as I don't understand GL's coordinates too well (and I can't really understand the available documentation...I am just a designer with no coder help or background. A n00b, basically). glBegin(GL_POLYGON); for(i = 0;i < 360; i += 10){ glTexCoord2f(0, 0); glVertex2f(Cos(i)*(H-10),Sin(i)H); glTexCoord2f(0, HP); glVertex2f(Sin(i)(H-10),Cos(i)*(H-10)); glTexCoord2f(WP, HP); glVertex2f(Cos(i)H,Sin(i)(H-10)); glTexCoord2f(WP, 0); glVertex2f(Sin(i)*H,Cos(i)*H); } glEnd(); This is my last attempt, and it seems to generate a "sunburst" from the right edge of the circle instead of a ring. It's an amusing effect but definitely not what I want. Other results included the circle looking exactly the same as the quad textured (aka drawing a sprite literally) or something that looked like a pop-art filter, by working on this train of thought. Seems like my logic here is entirely flawed, so, what would be the easiest way to obtain such a ring? No need to reply in code, just some guidance for a non-math-skilled user...

    Read the article

  • Drawing Quadratic Bezier circles with a given radius: how to determine control points

    - by Casey
    Just to clarify; the code below works, but I don't understand where the formula for the variable "controlRadius" comes from. I wrote this function by dissecting an example I found elsewhere, but I can't find any explanation and the original code comments were not able to be translated. Thanks in advance //returns an array of quadratic Bezier segments public static function generateCircularQuadraticBezierSegments(radius:Number, numControlPoints:uint, centerX:Number, centerY:Number):Array { var segments:Array = []; var arcLength:Number = 2 * Math.PI / numControlPoints; var controlRadius:Number; var segment:QuadraticBezierSegment; for (var i:int = 0; i < numControlPoints; i++) { var startX:Number = centerX + radius * Math.cos(arcLength * i); var startY:Number = centerY + radius * Math.sin(arcLength * i); //control radius formula //where does it come from, why does it work? controlRadius = radius / Math.cos(arcLength * .5); //the control point is plotted halfway between the arcLength and uses the control radius var controlX:Number = centerX + controlRadius * Math.cos(arcLength * (i + 1) - arcLength * .5); var controlY:Number = centerY + controlRadius * Math.sin(arcLength * (i + 1) - arcLength * .5); var endX:Number = centerX + radius * Math.cos(arcLength * (i + 1)); var endY:Number = centerY + radius * Math.sin(arcLength * (i + 1)); segment = new QuadraticBezierSegment(new Point(startX, startY), new Point(controlX, controlY), new Point(endX, endY)); segments.push(segment); } return segments; }

    Read the article

  • How to calculate short & long distance via Haversine?

    - by Jeroen
    Hi, I am looking for a way to calculate the distance between 2 points on the globe. We've been told to use Haversine, which works fine to calculate the shortest distance between the 2 points. Now, I'd like to calculate the "long distance" between to points. So suppose you have 2 cities, A in the west and B in the east. I want to know the distance from B to A if I would travel eastwards around the globe and then reach A coming from the west. I've tried changing a couple of things in the haversine function, but doesn't seem to work. Anyone know how I can simply do this using small adjustments to the haversine function? This is what I'm using now: lat1, lat2, lng1, lng2 are in radians part1 = sin(lat2) * sin(lat1); part2 = cos(lat2) * cos(lat1) * cos(lng1 - lng2); distance = EARTH_RADIUS * acos(part1 + part2); Tnx Jeroen

    Read the article

  • Fastest distance lookup given latitude/longitude?

    - by Ryan Detzel
    I currently have just under a million locations in a mysql database all with longitude and latitude information. With this I use another lat/lng to find the distance of certain places in the database but it's not as fast as I want it to be especially with 100+ hits a second. Is there a faster formula or possibly a faster system other than mysql for this? The formula I'm using is this. select name, ( 3959 * acos( cos( radians(42.290763) ) * cos( radians( locations.lat ) ) * cos( radians( locations.lng ) - radians(-71.35368) ) + sin( radians(42.290763) ) * sin( radians( locations.lat ) ) ) ) AS distance from locations where active = 1 HAVING distance < 10 ORDER BY distance;

    Read the article

  • Optimising SQL distance query

    - by Alex
    I'm running an MySQL query that returns results based on location. However I have noticed recently that its really slowing down my PHP app. I used CodeIgniter and the profiler shows the query taking 4.2seconds. The geoname table has 500,000 rows. I have some indexes on the key columns, how else can speed up this query? Here is my SQL: SELECT `products`.`product_name`, `geoname`.`geonameid`, `geoname`.`latitude`, `geoname`.`longitude`, `products`.`product_id`, AVG(ratings.vote) as rating, count(comments.comment_id) as total_comments, (6371 * acos(cos(radians(38.7666667)) * cos(radians(geoname.latitude)) * cos(radians(geoname.longitude) - radians(-3.3833333)) + sin(radians(38.7666667)) * sin(radians(geoname.latitude)))) AS distance FROM (`foods`) JOIN `geoname` ON `geoname`.`geonameid` = `products`.`geoname_id` LEFT JOIN `ratings` ON `ratings`.`var_id` = `products`.`product_id` LEFT JOIN `comments` ON `comments`.`var_id` = `products `.`product_id` WHERE `products`.`product_id` != 82 GROUP BY `products`.`product_id` HAVING `distance` < 99 ORDER BY `distance` LIMIT 10

    Read the article

  • Directional Map Search

    - by Rooneyl
    Hello, I am trying so write a bit of code that will search for a given point on a map, but in a given arc of a compass bearing. e.g. 45 degress (north-east), 20 degrees either side. So far I have got a SQL command that will give me the results in a given radius, need some help on how to filter it to a direction. SELECT * FROM (SELECT `place1_id`, `place2_id`, ( 6371 * acos( cos( radians(search_latitude) ) * cos( radians( `location_lat` ) ) * cos( radians( `location_long` ) - radians(search_longitude) ) + sin( radians(search_latitude) ) * sin( radians( `location_lat` ) ) ) ) AS `distance` FROM `place` ORDER BY distance) AS `places` WHERE `places`.`distance` < search_radius AND `places`.`place2_id` = ? Will I be able to do this (if possible) all in SQL, or will it need a bit of PHP applying to it? Any and all help much appreciated!

    Read the article

  • Filter zipcodes by proximity in Django with the Spherical Law of Cosines

    - by spiffytech
    I'm trying to handle proximity search for a basic store locater in Django. Rather than haul PostGIS around with my app just so I can use GeoDjango's distance filter, I'd like to use the Spherical Law of Cosines distance formula in a model query. I'd like all of the calculations to be done in the database in one query, for efficiency. An example MySQL query from The Internet implementing the Spherical Law of Cosines like this: SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM stores HAVING distance < 25 ORDER BY distance LIMIT 0 , 20; The query needs to reference the Zipcode ForeignKey for each store's lat/lng values. How can I make all of this work in a Django model query?

    Read the article

  • calculate distance with linq or subsonic C# MVC

    - by minus4
    i have this MySQL statement from a search page, the user enters there postcode and it finds the nearest stiocklist within 15 MIles of the entered postcode. SELECT * , ( ( ACOS( SIN( "+SENTLNG +" * PI( ) /180 ) * SIN( s_lat * PI( ) /180 ) + COS( " + SENTLNG +" * PI( ) /180 ) * COS( s_lat * PI( ) /180 ) * COS( ( " + SENTLANG + " - s_lng ) * PI( ) /180 ) ) *180 / PI( ) ) *60 * 1.1515 ) AS distance_miles FROM new_stockists WHERE s_lat IS NOT NULL HAVING distance_miles <15 ORDER BY distance_miles ASC LIMIT 0 , 15 but now i am using linq and subsonic and not got a clue how do do this in linq or subsonic your help would be much appreciated, please also not that i have to sent in a dynamic from address, thats the postcode mentioned at the top of the page, i do a call to google to get then lng and lat from them for the postcode given.

    Read the article

  • calculate distance with linq or subsonic

    - by minus4
    i have this MySQL statement from a search page, the user enters there postcode and it finds the nearest stiocklist within 15 MIles of the entered postcode. SELECT * , ( ( ACOS( SIN( "+SENTLNG +" * PI( ) /180 ) * SIN( s_lat * PI( ) /180 ) + COS( " + SENTLNG +" * PI( ) /180 ) * COS( s_lat * PI( ) /180 ) * COS( ( " + SENTLANG + " - s_lng ) * PI( ) /180 ) ) *180 / PI( ) ) *60 * 1.1515 ) AS distance_miles FROM new_stockists WHERE s_lat IS NOT NULL HAVING distance_miles <15 ORDER BY distance_miles ASC LIMIT 0 , 15 but now i am using linq and subsonic and not got a clue how do do this in linq or subsonic your help would be much appreciated, please also not that i have to sent in a dynamic from address, thats the postcode mentioned at the top of the page, i do a call to google to get then lng and lat from them for the postcode given.

    Read the article

  • Rails: Converting from MySQL to PostGres breaks Geokit Distance Calculations???

    - by Kevin
    I recently switched my database from MySQL to PostGres. I also use GeoKit. When I started my app up with the new database already seeded, I get the following error: PGError: ERROR: function radians(character varying) does not exist LINE 1: ...COS(0.661045389762993)*COS(-2.12957994527573)*COS(RADIANS(ti... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Anyone know why this is breaking now? I know GeoKit still works because it's still performing the geocoding in the model per ticket when the database is seeded, it just won't do the distance calculations correctly.

    Read the article

  • Table alias -- Unkown column in field list

    - by Jason
    Hi all, I have a sql query which is executing a LEFT JOIN on 2 tables in which some of the columns are ambiguous. I can prefix the joined tables but when I try to prefix one of the columns from the table in the FROM clause, it tells me Unknown column. I even tried giving that table an alias like so ...From points AS p and using "p" to prefix the tables but that didn't work either. Can someone tell me what I'm doing wrong. Here is my query: SELECT point_title, point_url, address, city, state, zip_code, phone, `points`.`lat`, `points`.`longi`, featured, kmlno, image_url, category.title, category_id, point_id, lat, longi, reviews.star_points, reviews.review_id, count(reviews.point_id) as totals FROM (SELECT *, ( 3959 * acos( cos( radians('37.7717185') ) * cos( radians( lat ) ) * cos( radians( longi ) - radians('-122.4438929') ) + sin( radians('37.7717185') ) * sin( radians( lat ) ) ) ) AS distance FROM points HAVING distance < '25') as distResults LEFT JOIN category USING ( category_id ) LEFT JOIN reviews USING ( point_id ) WHERE (point_title LIKE '%Playgrounds%' OR category.title LIKE '%Playgrounds%') GROUP BY point_id ORDER BY totals DESC, distance LIMIT 0 , 10

    Read the article

  • how to exit recursive math formula and still get an answer

    - by calccrypto
    i wrote this python code, which from wolfram alpha says that its supposed to return the factorial of any positive value (i probably messed up somewhere), integer or not: from math import * def double_factorial(n): if int(n) == n: n = int(n) if [0,1].__contains__(n): return 1 a = (n&1) + 2 b = 1 while a<=n: b*=a a+= 2 return float(b) else: return factorials(n/2) * 2**(n/2) *(pi/2)**(.25 *(-1+cos(n * pi))) def factorials(n): return pi**(.5 * sin(n*pi)**2) * 2**(-n + .25 * (-1 + cos(2*n*pi))) * double_factorial(2*n) the problem is , say i input pi to 6 decimal places. 2*n will not become a float with 0 as its decimals any time soon, so the equation turns out to be pi**(.5 * sin(n*pi)**2) * 2**(-n + .25 * (-1 + cos(2*n*pi))) * double_factorial(loop(loop(loop(...))))) how would i stop the recursion and still get the answer? ive had suggestions to add an index to the definitions or something, but the problem is, if the code stops when it reaches an index, there is still no answer to put back into the previous "nests" or whatever you call them

    Read the article

  • How to find distance between two geopoints in c using calculateDistance(const CWaypoint& wp)

    - by Harsha
    void getAllDataByPointer(string *pname,double *platitude, double *plongitude); void getAllDataByReference(string &pname,double &platitude, double &plongitude); double calculateDistance(const CWaypoint& wp); void print(int format); bool less(const CWaypoint& wp_right); CWaypoint add(const CWaypoint& wp_right); These are the functions I am using. I have the values as output but how to call the latitude values of two different cities so that I can use the following formula distance = ERADIUS * (acos(sin(latitude_1)*sin(latitude_2) + cos(latitude_1) * cos(latitude_2)*cos(longitude_2 - longitude_1)));

    Read the article

  • How to implement line of sight restriction in actionscript?

    - by Michiel Standaert
    I have a problem with a game i am programming. I am making some sort of security game and i would like to have some visual line of sight. The problem is that i can't restrict my line of sight so my cops can't see through the walls. Below you find the design, in which they can look through windows, but not walls. Further below you find an illustration of what my problem is exactly. this is what it looks like now. As you can see, the cops can see through walls. This is the map i would want to use to restrict the line of sight. So the way i am programming the line of sight now is just by calculating some points and drawing the sight accordingly, as shown below. Note that i also check for a hittest using bitmapdata to check whether or not my player has been spotted by any of the cops. private function setSight(e:Event=null):Boolean { g = copCanvas.graphics; g.clear(); for each(var cop:Cop in copCanvas.getChildren()) { var _angle:Number = cop.angle; var _radians:Number = (_angle * Math.PI) / 180; var _radius:Number = 50; var _x1:Number = cop.x + (cop.width/2); var _y1:Number = cop.y + (cop.height/2); var _baseX:Number = _x1 + (Math.cos(_radians) * _radius); var _baseY:Number = _y1 - (Math.sin(_radians) * _radius); var _x2:Number = _baseX + (25 * Math.sin(_radians)); var _y2:Number = _baseY + (25 * Math.cos(_radians)); var _x3:Number = _baseX - (25 * Math.sin(_radians)); var _y3:Number = _baseY - (25 * Math.cos(_radians)); g.beginFill(0xff0000, 0.3); g.moveTo(_x1, _y1); g.lineTo(_x2, _y2); g.lineTo(_x3, _y3); g.endFill(); } var _cops:BitmapData = new BitmapData(width, height, true, 0); _cops.draw(copCanvas); var _bmpd:BitmapData = new BitmapData(10, 10, true, 0); _bmpd.draw(me); if(_cops.hitTest(new Point(0, 0), 10, _bmpd, new Point(me.x, me.y), 255)) { gameover.alpha = 1; setTimeout(function():void{ gameover.alpha = 0; }, 5000); stop(); return true; } return false; } So now my question is: Is there someone who knows how to restrict the view so that the cops can't look through the walls? Thanks a lot in advance. ps: i have already looked at this tutorial by emanuele feronato, but i can't use the code to restric the visual line of sight.

    Read the article

  • morph a sphere to a cube and a a cube to a sphere with GLSL

    - by nkint
    hi i'm getting started with glsl with quartz composer. i have a patch with a particle system in which each particle is mapped into a sphere with a blend value. with blend=0 particles are in random positions, blend=1 particles are in the sphere. the code is here: vec3 sphere(vec2 domain) { vec3 range; range.x = radius * cos(domain.y) * sin(domain.x); range.y = radius * sin(domain.y) * sin(domain.x); range.z = radius * cos(domain.x); return range; } // in main: normal = sphere(p0); * blend + gl_Normal * (1.0 - blend); i'd like the particle to be on a cube if blend=0 i've tried to find but i can't figure out some parametric equation for the cube. mayebe it is not the right way?

    Read the article

  • Circular Bullet Spread not Even

    - by SoulBeaver
    I'm creating a bullet shooter much in the style of Touhou. Right now I want to have a very simple circular shot being fired from the enemy. See this picture: As you can see, the spacing is very uneven, which isn't very good if you want to survive. The code I'm using is this: private function shoot() : void { const BULLETS_PER_WAVE : int = 72; var interval : Number = BULLETS_PER_WAVE / 360; for (var i : int = 0; i < BULLETS_PER_WAVE; ++i { var xSpeed : Number = GameConstants.BULLET_NORMAL_SPEED_X * Math.sin(i * interval); var ySpeed : Number = GameConstants.BULLET_NORMAL_SPEED_Y * Math.cos(i * interval); BulletFactory.createNormalBullet(bulletColor_, alice_.center, xSpeed, ySpeed); } canShoot_ = false; cooldownTimer_.start(); } I imagine my mistake is in the sin, cos functions, but I'm not entirely sure what's wrong.

    Read the article

  • Euler angles to Cartesian Coordinates for use with gluLookAt

    - by notrodash
    I have searched all of the internet but just couldn't find the answer. I am using LibGDX and this is part of my code that loops over and over: public void render() { GL11 gl = Gdx.gl11; float centerX = (float)Math.cos(yaw) * (float)Math.cos(pitch); float centerY = (float)Math.sin(yaw) * (float)Math.cos(pitch); float centerZ = (float)Math.sin(pitch); System.out.println(centerX+" "+centerY+" "+centerZ+" ~ "+GDXRacing.camera.position.x+" "+GDXRacing.camera.position.y+" "+GDXRacing.camera.position.z); Gdx.glu.gluLookAt(gl, GDXRacing.camera.position.x, GDXRacing.camera.position.y, GDXRacing.camera.position.z, centerX, centerY, centerZ, 0, 1, 0); if(Gdx.input.isKeyPressed(Keys.A)) { yaw--; } if(Gdx.input.isKeyPressed(Keys.D)) { yaw++; } } I might just be bad at the math, but I dont get it. Does someone have a good explanation and an idea about how to deal with this? I am trying to make a first person camera. By the way, the camera is translated by +10 on the Z axis. Currently when I run the application, this is what I get: Watch video in browser | Download video (for those who cant download the video, everything shakes in a clockwise/anticlockwise action, depending on if I increase or decrease the Yaw value) -Thank you. [edit] and with this code: public void render() { GL11 gl = Gdx.gl11; float centerX = (float)(MathUtils.cosDeg(yaw)*4); float centerY = 0; float centerZ = (float)(MathUtils.sinDeg(yaw)*4); System.out.println(centerX+" "+centerY+" "+centerZ+" ~ "+GDXRacing.camera.position.x+" "+GDXRacing.camera.position.y+" "+GDXRacing.camera.position.z); Gdx.glu.gluLookAt(gl, GDXRacing.camera.position.x, GDXRacing.camera.position.y, GDXRacing.camera.position.z, centerX, centerY, centerZ, 0, 1, 0); if(Gdx.input.isKeyPressed(Keys.A)) { yaw--; } if(Gdx.input.isKeyPressed(Keys.D)) { yaw++; } } it slowly swings from the left to the right. This approach worked for turning left and right for 2d games though. What am I doing wrong?

    Read the article

  • Rotation matrix for a 3D vector

    - by Shashwat
    I have a direction vector on which I have to apply some rotation to align it to positive z-axis. To use Matrix.CreateRotationX(angle) of XNA, I need the angle for which I'd have to compute cos or tan inverse. I think this is a complex task to do. Also, eventually those are also converted to sin(angle) and cos(angle) in the matrix. Is there any inbuilt way to create rotation matrix from a 3D vector? However, I can write the function but still asking if there is one already there.

    Read the article

  • Help with calculation to steer ship in 3d space

    - by Aaron Anodide
    I'm a beginner using XNA to try and make a 3D Asteroids game. I'm really close to having my space ship drive around as if it had thrusters for pitch and yaw. The problem is I can't quite figure out how to translate the rotations, for instance, when I pitch forward 45 degrees and then start to turn - in this case there should be rotation being applied to all three directions to get the "diagonal yaw" - right? I thought I had it right with the calculations below, but they cause a partly pitched forward ship to wobble instead of turn.... :( Here's current (almost working) calculations for the Rotation acceleration: float accel = .75f; // Thrust +Y / Forward if (currentKeyboardState.IsKeyDown(Keys.I)) { this.ship.AccelerationY += (float)Math.Cos(this.ship.RotationZ) * accel; this.ship.AccelerationX += (float)Math.Sin(this.ship.RotationZ) * -accel; this.ship.AccelerationZ += (float)Math.Sin(this.ship.RotationX) * accel; } // Rotation +Z / Yaw if (currentKeyboardState.IsKeyDown(Keys.J)) { this.ship.RotationAccelerationZ += (float)Math.Cos(this.ship.RotationX) * accel; this.ship.RotationAccelerationY += (float)Math.Sin(this.ship.RotationX) * accel; this.ship.RotationAccelerationX += (float)Math.Sin(this.ship.RotationY) * accel; } // Rotation -Z / Yaw if (currentKeyboardState.IsKeyDown(Keys.K)) { this.ship.RotationAccelerationZ += (float)Math.Cos(this.ship.RotationX) * -accel; this.ship.RotationAccelerationY += (float)Math.Sin(this.ship.RotationX) * -accel; this.ship.RotationAccelerationX += (float)Math.Sin(this.ship.RotationY) * -accel; } // Rotation +X / Pitch if (currentKeyboardState.IsKeyDown(Keys.F)) { this.ship.RotationAccelerationX += accel; } // Rotation -X / Pitch if (currentKeyboardState.IsKeyDown(Keys.D)) { this.ship.RotationAccelerationX -= accel; } I'm combining that with drawing code that does a rotation to the model: public void Draw(Matrix world, Matrix view, Matrix projection, TimeSpan elsapsedTime) { float seconds = (float)elsapsedTime.TotalSeconds; // update velocity based on acceleration this.VelocityX += this.AccelerationX * seconds; this.VelocityY += this.AccelerationY * seconds; this.VelocityZ += this.AccelerationZ * seconds; // update position based on velocity this.PositionX += this.VelocityX * seconds; this.PositionY += this.VelocityY * seconds; this.PositionZ += this.VelocityZ * seconds; // update rotational velocity based on rotational acceleration this.RotationVelocityX += this.RotationAccelerationX * seconds; this.RotationVelocityY += this.RotationAccelerationY * seconds; this.RotationVelocityZ += this.RotationAccelerationZ * seconds; // update rotation based on rotational velocity this.RotationX += this.RotationVelocityX * seconds; this.RotationY += this.RotationVelocityY * seconds; this.RotationZ += this.RotationVelocityZ * seconds; Matrix translation = Matrix.CreateTranslation(PositionX, PositionY, PositionZ); Matrix rotation = Matrix.CreateRotationX(RotationX) * Matrix.CreateRotationY(RotationY) * Matrix.CreateRotationZ(RotationZ); model.Root.Transform = rotation * translation * world; model.CopyAbsoluteBoneTransformsTo(boneTransforms); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = boneTransforms[mesh.ParentBone.Index]; effect.View = view; effect.Projection = projection; effect.EnableDefaultLighting(); } mesh.Draw(); } }

    Read the article

  • KXML library Problem

    - by Hesham
    i'm working j2me with netbeans platform and i had a problem while i was trying to read a XML file and i added the library kxml.zip to my project's libraries and i used some of it's functions, there r no errors or red lines in the code, but the problem is that i cant run the project cos it come up with errors while compiling and all these errors are on the kxml functions, so any on can help me through this cos i really dont know what to do to make it run properly

    Read the article

  • Rotate triangle so that its tip points in the direction of the point on the screen that we last touched

    - by Sid
    OpenGL ES - Android. Hello all, I am unable to rotate the triangle accordingly in such a way that its tip always points to my finger. What i did : Constructed a triangle in by GL.GL_TRIANGLES. Added touch events to it. I can rotate the triangle along my Z-axis successfully. Even made the vector class for it. What i need : Each time when I touch the screen, I want to rotate the triangle to face the touch point. Need some help. Here's what i implemented. I wonder that where i am going wrong? My code : public class Graphic2DTriangle { private FloatBuffer vertexBuffer; private ByteBuffer indexBuffer; private float[] vertices = { -1.0f,-1.0f, 0.0f, 2.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f }; private byte[] indices = { 0, 1, 2 }; public Graphic2DTriangle() { ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4); vbb.order(ByteOrder.nativeOrder()); // Use native byte order vertexBuffer = vbb.asFloatBuffer(); // Convert byte buffer to float vertexBuffer.put(vertices); // Copy data into buffer vertexBuffer.position(0); // Rewind // Setup index-array buffer. Indices in byte. indexBuffer = ByteBuffer.allocateDirect(indices.length); indexBuffer.put(indices); indexBuffer.position(0); } public void draw(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer); gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_BYTE, indexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } } My SurfaceView class where i've done some Touch Events. public class BallThrowGLSurfaceView extends GLSurfaceView{ MySquareRender _renderObj; View _viewObj; float oldX,oldY,dX,dY; final float TOUCH_SCALE_FACTOR = 0.6f; Vector2 touchPos = new Vector2(); float angle=0; public BallThrowGLSurfaceView(Context context) { super(context); // TODO Auto-generated constructor stub _renderObj = new MySquareRender(context); this.setRenderer(_renderObj); this.setRenderMode(RENDERMODE_WHEN_DIRTY); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub touchPos.x = event.getX(); touchPos.y = event.getY(); Log.i("Co-ord", touchPos.x+"hh"+touchPos.y); switch(event.getAction()){ case MotionEvent.ACTION_MOVE : dX = touchPos.x - oldX; dY = touchPos.y - oldY; if(touchPos.y > getHeight()/2){ dX = dX*-1; } if(touchPos.x < getWidth()/2){ dY = dY*-1; } _renderObj.mAngle += (dX+dY) * TOUCH_SCALE_FACTOR; requestRender(); Log.i("AngleCo-ord", _renderObj.mAngle +"hh"); } oldX = touchPos.x; oldY = touchPos.y; Log.i("OldCo-ord", oldX+" hh "+oldY); return true; } } Last but not the least. My vector2 class. public class Vector2 { public static float TO_RADIANS = (1 / 180.0f) * (float) Math.PI; public static float TO_DEGREES = (1 / (float) Math.PI) * 180; public float x, y; public Vector2() { } public Vector2(float x, float y) { this.x = x; this.y = y; } public Vector2(Vector2 other) { this.x = other.x; this.y = other.y; } public Vector2 cpy() { return new Vector2(x, y); } public Vector2 set(float x, float y) { this.x = x; this.y = y; return this; } public Vector2 set(Vector2 other) { this.x = other.x; this.y = other.y; return this; } public Vector2 add(float x, float y) { this.x += x; this.y += y; return this; } public Vector2 add(Vector2 other) { this.x += other.x; this.y += other.y; return this; } public Vector2 sub(float x, float y) { this.x -= x; this.y -= y; return this; } public Vector2 sub(Vector2 other) { this.x -= other.x; this.y -= other.y; return this; } public Vector2 mul(float scalar) { this.x *= scalar; this.y *= scalar; return this; } public float len() { return FloatMath.sqrt(x * x + y * y); } public Vector2 nor() { float len = len(); if (len != 0) { this.x /= len; this.y /= len; } return this; } public float angle() { float angle = (float) Math.atan2(y, x) * TO_DEGREES; if (angle < 0) angle += 360; return angle; } public Vector2 rotate(float angle) { float rad = angle * TO_RADIANS; float cos = FloatMath.cos(rad); float sin = FloatMath.sin(rad); float newX = this.x * cos - this.y * sin; float newY = this.x * sin + this.y * cos; this.x = newX; this.y = newY; return this; } public float dist(Vector2 other) { float distX = this.x - other.x; float distY = this.y - other.y; return FloatMath.sqrt(distX * distX + distY * distY); } public float dist(float x, float y) { float distX = this.x - x; float distY = this.y - y; return FloatMath.sqrt(distX * distX + distY * distY); } public float distSquared(Vector2 other) { float distX = this.x - other.x; float distY = this.y - other.y; return distX * distX + distY * distY; } public float distSquared(float x, float y) { float distX = this.x - x; float distY = this.y - y; return distX * distX + distY * distY; } } PS : i am able to handle the touch events. I can rotate the triangle with the touch of my finger. But i want that ONE VERTEX of the triangle should point at my finger position respective of the position of my finger.

    Read the article

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