Search Results

Search found 25 results on 1 pages for 'radian'.

Page 1/1 | 1 

  • read angles in radian and convert them in degrees/minutes/seconds

    - by Amadou
    n=0; disp('This program performs an angle conversion'); disp('input data set to a straight line. Enter the name'); disp('of the file containing the input Lambda in radian: '); filename = input(' ','s'); [fid,msg] = fopen(filename,'rt'); if fid < 0 disp(msg); else A=textscan(fid, '%g',1); while ~feof(fid) Lambda = A(1); n = n + 1; A = textscan(fid, '%f',1); end fclose(fid); end Alpha=Lambda*180/pi; fprintf('Angle converted from radian to degree/minutes/seconds:\n'); fprintf('Alpha =%12d\n',Alpha); fprintf('No of angles =%12d\n',n);

    Read the article

  • WebGL First Person Camera - Matrix issues

    - by Ryan Welsh
    I have been trying to make a WebGL FPS camera.I have all the inputs working correctly (I think) but when it comes to applying the position and rotation data to the view matrix I am a little lost. The results can be viewed here http://thistlestaffing.net/masters/camera/index.html and the code here var camera = { yaw: 0.0, pitch: 0.0, moveVelocity: 1.0, position: [0.0, 0.0, -70.0] }; var viewMatrix = mat4.create(); var rotSpeed = 0.1; camera.init = function(canvas){ var ratio = canvas.clientWidth / canvas.clientHeight; var left = -1; var right = 1; var bottom = -1.0; var top = 1.0; var near = 1.0; var far = 1000.0; mat4.frustum(projectionMatrix, left, right, bottom, top, near, far); viewMatrix = mat4.create(); mat4.rotateY(viewMatrix, viewMatrix, camera.yaw); mat4.rotateX(viewMatrix, viewMatrix, camera.pitch); mat4.translate(viewMatrix, viewMatrix, camera.position); } camera.update = function(){ viewMatrix = mat4.create(); mat4.rotateY(viewMatrix, viewMatrix, camera.yaw); mat4.rotateX(viewMatrix, viewMatrix, camera.pitch); mat4.translate(viewMatrix, viewMatrix, camera.position); } //prevent camera pitch from going above 90 and reset yaw when it goes over 360 camera.lockCamera = function(){ if(camera.pitch > 90.0){ camera.pitch = 90; } if(camera.pitch < -90){ camera.pitch = -90; } if(camera.yaw <0.0){ camera.yaw = camera.yaw + 360; } if(camera.yaw >360.0){ camera.yaw = camera.yaw - 0.0; } } camera.translateCamera = function(distance, direction){ //calculate where we are looking at in radians and add the direction we want to go in ie WASD keys var radian = glMatrix.toRadian(camera.yaw + direction); //console.log(camera.position[3], radian, distance, direction); //calc X coord camera.position[0] = camera.position[0] - Math.sin(radian) * distance; //calc Z coord camera.position[2] = camera.position [2] - Math.cos(radian) * distance; console.log(camera.position [2] - (Math.cos(radian) * distance)); } camera.rotateUp = function(distance, direction){ var radian = glMatrix.toRadian(camera.pitch + direction); //calc Y coord camera.position[1] = camera.position[1] + Math.sin(radian) * distance; } camera.moveForward = function(){ if(camera.pitch!=90 && camera.pitch!=-90){ camera.translateCamera(-camera.moveVelocity, 0.0); } camera.rotateUp(camera.moveVelocity, 0.0); } camera.moveBack = function(){ if(camera.pitch!=90 && camera.pitch!=-90){ camera.translateCamera(-camera.moveVelocity, 180.0); } camera.rotateUp(camera.moveVelocity, 180.0); } camera.moveLeft = function(){ camera.translateCamera(-camera.moveVelocity, 270.0); } camera.moveRight = function(){ camera.translateCamera(-camera.moveVelocity, 90.0); } camera.lookUp = function(){ camera.pitch = camera.pitch + rotSpeed; camera.lockCamera(); } camera.lookDown = function(){ camera.pitch = camera.pitch - rotSpeed; camera.lockCamera(); } camera.lookLeft = function(){ camera.yaw= camera.yaw - rotSpeed; camera.lockCamera(); } camera.lookRight = function(){ camera.yaw = camera.yaw + rotSpeed; camera.lockCamera(); } . If there is no problem with my camera then I am doing some matrix calculations within my draw function where a problem might be. //position cube 1 worldMatrix = mat4.create(); mvMatrix = mat4.create(); mat4.translate(worldMatrix, worldMatrix, [-20.0, 0.0, -30.0]); mat4.multiply(mvMatrix, worldMatrix, viewMatrix); setShaderMatrix(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.vertexAttribPointer(shaderProgram.attPosition, 3, gl.FLOAT, false, 8*4,0); gl.vertexAttribPointer(shaderProgram.attTexCoord, 2, gl.FLOAT, false, 8*4, 3*4); gl.vertexAttribPointer(shaderProgram.attNormal, 3, gl.FLOAT, false, 8*4, 5*4); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, myTexture); gl.uniform1i(shaderProgram.uniSampler, 0); gl.useProgram(shaderProgram); gl.drawArrays(gl.TRIANGLES, 0, vertexBuffer.numItems); //position cube 2 worldMatrix = mat4.create(); mvMatrix = mat4.create(); mat4.multiply(mvMatrix, worldMatrix, viewMatrix); mat4.translate(worldMatrix, worldMatrix, [40.0, 0.0, -30.0]); setShaderMatrix(); gl.drawArrays(gl.TRIANGLES, 0, vertexBuffer.numItems); //position cube 3 worldMatrix = mat4.create(); mvMatrix = mat4.create(); mat4.multiply(mvMatrix, worldMatrix, viewMatrix); mat4.translate(worldMatrix, worldMatrix, [20.0, 0.0, -100.0]); setShaderMatrix(); gl.drawArrays(gl.TRIANGLES, 0, vertexBuffer.numItems); camera.update();

    Read the article

  • Can anyone explain this snippet of Javascript?

    - by karthick6891
    Can anyone explain the following code? Forget the sine and cosine parts. Is it trying to build a space for the object? objectsInScene = new Array(); for (var i=space; i<180; i+=space) { for (var angle=0; angle<360; angle+=space) { var object = {}; var x = Math.sin(radian*i)*radius; object.x = Math.cos(angle*radian)*x; object.y = Math.cos(radian*i)*radius; object.z = Math.sin(angle*radian)*x; objectsInScene.push(object); } }

    Read the article

  • Can anyone explain this pience of snippet?

    - by karthick6891
    Can anyone explain the following code,forget the sin and cosine parts..Is it trying to build a space for the object objectsInScene = new Array(); for (var i=space; i<180; i+=space) { for (var angle=0; angle<360; angle+=space) { var object = {}; var x = Math.sin(radian*i)*radius; object.x = Math.cos(angle*radian)*x; object.y = Math.cos(radian*i)*radius; object.z = Math.sin(angle*radian)*x; objectsInScene.push(object); } }

    Read the article

  • Gwibber on Ubuntu doesn't open

    - by Radian
    Gwibber Doesn't open . When I tried to Open it from Command Line I got this error ** (gwibber:3752): WARNING **: Trying to register gtype 'WnckWindowState' as enum when in fact it is of type 'GFlags' ** (gwibber:3752): WARNING **: Trying to register gtype 'WnckWindowActions' as enum when in fact it is of type 'GFlags' ** (gwibber:3752): WARNING **: Trying to register gtype 'WnckWindowMoveResizeMask' as enum when in fact it is of type 'GFlags' No dbus monitor yet Updating... ERROR:dbus.proxies:Introspect error on com.Gwibber.Service:/com/gwibber/Service: dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NoReply: Message did not receive a reply (timeout by message bus) Traceback (most recent call last): File "/usr/bin/gwibber", line 67, in client.Client() File "/usr/lib/python2.6/dist-packages/gwibber/client.py", line 447, in init self.w = GwibberClient() File "/usr/lib/python2.6/dist-packages/gwibber/client.py", line 29, in init self.model = gwui.Model() File "/usr/lib/python2.6/dist-packages/gwibber/gwui.py", line 43, in init self.services = json.loads(self.daemon.GetServices()) File "/usr/lib/pymodules/python2.6/dbus/proxies.py", line 68, in call return self._proxy_method(*args, **keywords) File "/usr/lib/pymodules/python2.6/dbus/proxies.py", line 140, in call **keywords) File "/usr/lib/pymodules/python2.6/dbus/connection.py", line 620, in call_blocking message, timeout) dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NoReply: Message did not receive a reply (timeout by message bus) I tried to remove it and to Install again but It has the same error It was Working probably , then suddenly it didn't

    Read the article

  • Ubuntu dpkg error , after crash and filesystem error recovery

    - by Radian
    Ubuntu recently crashed , causing it's partition damaged ( which is EXT4) and Ubuntu was unable to boot , because it couldn't mount anything , only displays Busybox So I used the Live CD to run fsck on the partition, which fixed it , but deleted some nodes Now Ubuntu is working , but some files were missing , for example I lost the Panels configurations and Chromium's Extensions The Most Annoying problem , that there is some files corrupted , for example when I try to install any program, I got this (Reading database ... 95%dpkg: unrecoverable fatal error, aborting: files list file for package 'libservlet2.4-java' is missing final newline I tried these commands dpkg --configure -a apt-get -f install and from GUI , Synaptic Package Manager Fix Broken Packages So this file "libservlet2.4-java" Does anyone knows what it does ! and where it's location ? and how can I fix/get-correct-version-of it ? Also , is there any way I could tell Ubuntu to Check for ALL it's file , and if there is something corrupted it should recover it form the CD ?

    Read the article

  • Starting and stopping X11 and LXDE from command line

    - by Radian
    I have a Raspberry Pi with Debian Wheezy (Raspbian) and so far I've managed to learn quite a lot about Linux just playing around, but I have a few questions for all you seasoned Linux pros out there. 1) From command line, if I execute startx, X11 will launch followed by LXDE. If I had a monitor connected, I'm imagining I would see a transition from command line to the desktop environment. Can I launch X11 first with x, then start LXDE on top of X11 afterwards with /etc/init.d/lxdm start (is this correct?) and get to the same result as startx? 2) Instead, let's say I executed /etc/init.d/lxdm start alone, would X11 start automatically (since LXDE relies on X11)? 3) From desktop, if I CTRL+ALT+F1 to get back to command line, then I should be able to shutdown LXDE using /etc/init.d/lxdm stop. Does X11 automatically close with the termination of LXDE? 4) What is the proper/safe way to shutdown X11? Thanks

    Read the article

  • When is a>a true ?

    - by Cricri
    Right, I think I really am living a dream. I have the following piece of code which I compile and run on an AIX machine: AIX 3 5 PowerPC_POWER5 processor type IBM XL C/C++ for AIX, V10.1 Version: 10.01.0000.0003 #include <stdio.h> #include <math.h> #define RADIAN(x) ((x) * acos(0.0) / 90.0) double nearest_distance(double radius,double lon1, double lat1, double lon2, double lat2){ double rlat1=RADIAN(lat1); double rlat2=RADIAN(lat2); double rlon1=lon1; double rlon2=lon2; double a=0,b=0,c=0; a = sin(rlat1)*sin(rlat2)+ cos(rlat1)*cos(rlat2)*cos(rlon2-rlon1); printf("%lf\n",a); if (a > 1) { printf("aaaaaaaaaaaaaaaa\n"); } b = acos(a); c = radius * b; return radius*(acos(sin(rlat1)*sin(rlat2)+ cos(rlat1)*cos(rlat2)*cos(rlon2-rlon1))); } int main(int argc, char** argv) { nearest_distance(6367.47,10,64,10,64); return 0; } Now, the value of 'a' after the calculation is reported as being '1'. And, on this AIX machine, it looks like 1 1 is true as my 'if' is entered !!! And my acos of what I think is '1' returns NanQ since 1 is bigger than 1. May I ask how that is even possible ? I do not know what to think anymore ! The code works just fine on other architectures where 'a' really takes the value of what I think is 1 and acos(a) is 0.

    Read the article

  • Finetuning movement based on gradual rotation towards a target

    - by A.B.
    I have an object which moves towards a target destination by gradually adjusting its facing while moving forwards. If the target destination is in a "blind spot", then the object is incapable of reaching it. This problem is ilustrated in the picture below. When the arrow is ordered to move to point A, it will only end up circling around it (following the red circle) because it is not able to adjust its rotation quickly enough. I'm interested in a solution where the movement speed is multiplied by a number from 0.1 to 1 in proportion to necessity. The problem is, how do I calculate whether it is necessary in the first place? How do I calculate an appropriate multiplier that is neither too small nor too large? void moveToPoint(sf::Vector2f destination) { if (destination == position) return; auto movement_distance = distanceBetweenPoints(position, destination); desired_rotation = angleBetweenPoints(position, destination); /// Check whether rotation should be adjusted if (rotation != desired_rotation) { /// Check whether the object can achieve the desired rotation within the next adjustment of its rotation if (Radian::isWithinDistance(rotation, desired_rotation, rotation_speed)) { rotation = desired_rotation; } else { /// Determine whether to increment or decrement rotation in order to achieve desired rotation if (Radian::convert(desired_rotation - rotation) > 0) { /// Increment rotation rotation += rotation_speed; } else { /// Decrement rotation rotation -= rotation_speed; } } } if (movement_distance < movement_speed) { position = destination; } else { position.x = position.x + movement_speed*cos(rotation); position.y = position.y + movement_speed*sin(rotation); } updateGraphics(); }

    Read the article

  • Free Offline Map Provider (and not OpenStreetMap)

    - by Radian
    I am making for my Graduation Project a low price Navigation device, using Android as Operating System I tried the Native Google's Map-view Control, but it works only Online .. and of-course I want to store maps for offline navigation So.. I want a map provider (like OpenStreetMap) that : I can use offline Contain Searchable Street names (not only a rendered image) for commercial use Free or at low price The problem with OpenStreetMap that it doesn't provide detailed map for most cities in Egypt.

    Read the article

  • how to get Processor ID using Kernel32.dll

    - by Radian
    Hi, I want to know if there is an Entry point for kernel32.dll , that is related to any processor data (ID , Serial , etc ... ) and I tried to Google it but I didn't find good results . Note: I already know WMI , but I need something related to Kernel !

    Read the article

  • Free Offline Map Provider (and not OpenStreetMaps)

    - by Radian
    I am making for my Graduation Project a low price Navigation device, using Android as Operating System I tried the Native Google's Map-view Control, but it works only Online .. and of-course I want to store maps for offline navigation So.. I want a map provider (like OpenStreetMaps) that : I can use offline Contain Searchable Street names (not only a rendered image) for commercial use Free or at low price The problem with OpenStreetMaps that it doesn't provide detailed map for most cities in Egypt.

    Read the article

  • Is there any valid reason radians are used as the inputs to trig function in many modern languages?

    - by johnmortal
    Is there any pressing reason trig functions should use radian inputs in modern programming languages? As far as I know radians are typically ugly to deal with except in three cases: (1) You want to compute an arc length and you know the angle of the arc and (2) You need to do symbolic calculus with trig functions (3) certain infinite series expansion look prettier if the input is in radians. None of these scenarios seem like a worthy justification for every programming language I am familiar with using radian inputs for Sin, Cos, Tangent, etc... The third one sounds good because it might mean one gets faster computations using radians (very slightly faster- the cost of one additional floating point multiplication ) , but I am dubious even of that because most commonly the developer had to take an extra step to put the angle in radians in the first place. The other two are ridiculous justifications for all the added obscurity.

    Read the article

  • Ruby Doesn't Recognize Alias Method

    - by Jesse J
    I'm trying to debug someone else's code and having trouble figuring out what's wrong. When I run rake, one of the errors I get is: 2) Error: test_math(TestRubyUnits): NoMethodError: undefined method `unit_sin' for CMath:Module /home/user/ruby-units/lib/ruby_units/math.rb:21:in `sin' This is the function that calls the method: assert_equal Math.sin(pi), Math.sin("180 deg".unit) And this is what the class looks like: module Math alias unit_sin sin def sin(n) Unit === n ? unit_sin(n.to('radian').scalar) : unit_sin(n) end alias unit_cos cos def cos(n) Unit === n ? unit_cos(n.to('radian').scalar) : unit_cos(n) end ... module_function :unit_sin module_function :sin module_function :unit_cos module_function :cos ... end (The ellipsis means "more of the same"). As far as I can see, this is valid Ruby code. Is there something I'm missing here that's causing the error, or could the error be coming from something else? Update: I'm wondering if the problem has to do with namespaces. This code is attempting to extend CMath, so perhaps the alias and/or module_function isn't actually getting into CMath, or something like that....

    Read the article

  • Ruby Alias and module_function

    - by Jesse J
    I'm trying to debug someone else's code and having trouble figuring out what's wrong. When I run rake, one of the errors I get is: 2) Error: test_math(TestRubyUnits): NoMethodError: undefined method `unit_sin' for CMath:Module /home/user/ruby-units/lib/ruby_units/math.rb:21:in `sin' This is the function that calls the method: assert_equal Math.sin(pi), Math.sin("180 deg".unit) And this is what the class looks like: module Math alias unit_sin sin def sin(n) Unit === n ? unit_sin(n.to('radian').scalar) : unit_sin(n) end alias unit_cos cos def cos(n) Unit === n ? unit_cos(n.to('radian').scalar) : unit_cos(n) end ... module_function :unit_sin module_function :sin module_function :unit_cos module_function :cos ... end (The ellipsis means "more of the same"). As far as I can see, this is valid Ruby code. Is there something I'm missing here that's causing the error, or could the error be coming from something else? Update: I'm wondering if the problem has to do with namespaces. This code is attempting to extend CMath, so perhaps the alias and/or module_function isn't actually getting into CMath, or something like that....

    Read the article

  • Limit the amount a camera can pitch

    - by ChocoMan
    I'm having problems trying to limit the range my camera can pitch. Currently my camera can pitch around a model without restriction, but having a hard time trying to find the value of the degree/radian the camera is currently at after pitching. Here is what I got so far: // Moves camera with thumbstick Pitch = pController.ThumbSticks.Right.Y * MathHelper.ToRadians(speedAngleMAX); // Pitch Camera around model public void cameraPitch(float pitch) { pitchAngle = ModelLoad.camTarget - ModelLoad.CameraPos; axisPitch = Vector3.Cross(Vector3.Up, pitchAngle); // pitch constrained to model's orientation axisPitch.Normalize(); ModelLoad.CameraPos = Vector3.Transform(ModelLoad.CameraPos - ModelLoad.camTarget, Matrix.CreateFromAxisAngle(axisPitch, pitch)) + ModelLoad.camTarget; } I've tried restraining the Y-camera position of ModelLoad.CameraPos.Y, but doing so gave me some unwanted results.

    Read the article

  • I need to write a program that reads angles in radians from an input disk and converts them in degre

    - by Amadou
    Write a program that reads angles in radians from an input disk le and converts them into degrees, minutes, and seconds. Output should be written into another le. A sample input le could be: # this is a comment # your program should be able to skip comment lines # and blank lines # input radian numbers could be seperated by blanks 0.0 1.0 # or by a newline 3.141593 6.0

    Read the article

  • Happy Tau Day! (Or: How Some Mathematicians Think We Should Retire Pi) [Video]

    - by Jason Fitzpatrick
    When you were in school you learned all about Pi and its relationship to circles and turn-based geometry. Some mathematicians are rallying for a new lesson, on about Tau. Michael Hartl is a mathematician on a mission, a mission to get people away from using Pi and to start using Tau. His manifesto opens: Welcome to The Tau Manifesto. This manifesto is dedicated to one of the most important numbers in mathematics, perhaps the most important: the circle constant relating the circumference of a circle to its linear dimension. For millennia, the circle has been considered the most perfect of shapes, and the circle constant captures the geometry of the circle in a single number. Of course, the traditional choice of circle constant is p—but, as mathematician Bob Palais notes in his delightful article “p Is Wrong!”,1 p is wrong. It’s time to set things right. Why is Pi wrong? Among the arguments is that Tau is the ration of a circumference to the radius of a circle and defining circles by their radius is more natural and that Pi is a 2-factor number but with Tau everything is based of a single unit–three quarters of a turn around a Tau-defined circle is simply three quarters of a Tau radian. Watch the video above to see the Tau sequence (which begins 6.2831853071…) turned into a musical composition. For more information about Tau hit up the link below to read the manifesto. The Tau Manifesto [TauDay] HTG Explains: Photography with Film-Based CamerasHow to Clean Your Dirty Smartphone (Without Breaking Something)What is a Histogram, and How Can I Use it to Improve My Photos?

    Read the article

  • c++ How to use angular velocity that derived from inertia and force(torque) in 3d

    - by user1217203
    I am relatively new to game development. May my terminology and description are not appropriate. Please excuse my poor phrasing and help me by giving advice on how to question better if this question seems less fitting. I really appreciate your efforts. Hi. I am having hard time interpreting the set of values I have. I have inertia and force(torque) in terms of x y z. FYI I used x and y coordinates as my ground, flat coordinates and z as my up/down. I am assuming that since f = ma, that angular acceleration must be a = f / m. So I divide my torque by inertia. Then I add those x y z values to my angular velocity variable's x y z. However these x y z values confuse me. Don't I need angle/sec or radian/sec sort of values in order to apply rotation? The x y z values I have seemed to not say anything about radians or angular movement. Question : If I have ( 1, 2, 3 ) or any ( x, y, z ) as my angular velocity, how do I actually apply it as angular movement? FYI Here I am pasting my code : float mass = 100; float devidedMass = 1.0/12 * mass; Vec3 innertia( devidedMass* (_box._size.z*_box._size.z + _box._size.x*_box._size.x), devidedMass* (_box._size.y*_box._size.y + _box._size.x*_box._size.x), devidedMass* (_box._size.y*_box._size.y + _box._size.z*_box._size.z )); box._angAccel += forceAng/innertia; box._angVelo += box._angAccel; box._angAccel.allZero(); source of my inertia calculation http://www.health.uottawa.ca/biomech/courses/apa4311/solids.pdf

    Read the article

  • using NetBeans for rotate a figure in a label [migrated]

    - by user134812
    I was reading this post: http://forums.netbeans.org/post-8864.html and what I have done so far is to make a jFrame in NetBeans, on it I have drawn a jPanel and inisde the panel I have drawn a jLabel on it and use the icon property to put an image on it; until now all is so far so good. I would like to make a program that everytime I click on the figure it rotates it to the right. Actually I have found the following code: public class RotateImage extends JPanel{ // Declare an Image object for us to use. Image image; // Create a constructor method public RotateImage(){ super(); // Load an image to play with. image = Toolkit.getDefaultToolkit().getImage("Duke_Blocks.gif"); } public void paintComponent(Graphics g){ Graphics2D g2d=(Graphics2D)g; // Create a Java2D version of g. g2d.translate(170, 0); // Translate the center of our coordinates. g2d.rotate(1); // Rotate the image by 1 radian. g2d.drawImage(image, 0, 0, 200, 200, this); } but for what I see this code is for making the panel and other components from scratch, for my purposes it is not so good because I need to put several figures on my jFrame. Could somebody can give me a hint how to do this?

    Read the article

  • Android drawCircle's are not always 360 degrees

    - by user329999
    When I call drawCircle (ex. canvas.drawCircle(x, y, r, mPaint);) and I use Paint Style STROKE to initialize param #4 mPaint, the result doesn't quite make a full 360 degree (2*PI radian) circle in all cases. Sometimes you get a full circle (as I would expect) and sometimes only an arc. Does someone have an idea what would cause this to happen? I don't know what cases work and which don't (yet). I've noticed the ones that don't work seem to be the larger circles I'm drawing (100.0 radius). Could be size related. I am using floating point for x, y and r. I could try rounding to the nearest int when in the drawing code.

    Read the article

  • Optimizing transition/movement smoothness for a 2D flash game.

    - by Tom
    Update 6: Fenomenas suggested me to re-create everything as simple as possible. I had my doubts that this would make any difference as the algorithm remains the same, and performance did not seem to be the issue. Anyway, it was the only suggestion I got so here it is: 30 FPS: http://www.feedpostal.com/test/simple/30/SimpleMovement.html 40 FPS: http://www.feedpostal.com/test/simple/40/SimpleMovement.html 60 FPS: http://www.feedpostal.com/test/simple/60/SimpleMovement.html 100 FPS: http://www.feedpostal.com/test/simple/100/SimpleMovement.html The code: package { import flash.display.Sprite; import flash.events.Event; import flash.events.KeyboardEvent; import flash.utils.getTimer; [SWF(width="800", height="600", frameRate="40", backgroundColor="#000000")] public class SimpleMovement extends Sprite { private static const TURNING_SPEED:uint = 180; private static const MOVEMENT_SPEED:uint = 400; private static const RADIAN_DIVIDE:Number = Math.PI/180; private var playerObject:Sprite; private var shipContainer:Sprite; private var moving:Boolean = false; private var turningMode:uint = 0; private var movementTimestamp:Number = getTimer(); private var turningTimestamp:Number = movementTimestamp; public function SimpleMovement() { //step 1: create player object playerObject = new Sprite(); playerObject.graphics.lineStyle(1, 0x000000); playerObject.graphics.beginFill(0x6D7B8D); playerObject.graphics.drawRect(0, 0, 25, 50); //make it rotate around the center playerObject.x = 0 - playerObject.width / 2; playerObject.y = 0 - playerObject.height / 2; shipContainer = new Sprite(); shipContainer.addChild(playerObject); shipContainer.x = 100; shipContainer.y = 100; shipContainer.rotation = 180; addChild(shipContainer); //step 2: install keyboard hook when stage is ready addEventListener(Event.ADDED_TO_STAGE, stageReady, false, 0, true); //step 3: install rendering update poll addEventListener(Event.ENTER_FRAME, updatePoller, false, 0, true); } private function updatePoller(event:Event):void { var newTime:Number = getTimer(); //turning if (turningMode != 0) { var turningDeltaTime:Number = newTime - turningTimestamp; turningTimestamp = newTime; var rotation:Number = TURNING_SPEED * turningDeltaTime / 1000; if (turningMode == 1) shipContainer.rotation -= rotation; else shipContainer.rotation += rotation; } //movement if (moving) { var movementDeltaTime:Number = newTime - movementTimestamp; movementTimestamp = newTime; var distance:Number = MOVEMENT_SPEED * movementDeltaTime / 1000; var rAngle:Number = shipContainer.rotation * RADIAN_DIVIDE; //convert degrees to radian shipContainer.x += distance * Math.sin(rAngle); shipContainer.y -= distance * Math.cos(rAngle); } } private function stageReady(event:Event):void { //install keyboard hook stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown, false, 0, true); stage.addEventListener(KeyboardEvent.KEY_UP, keyUp, false, 0, true); } private final function keyDown(event:KeyboardEvent):void { if ((event.keyCode == 87) && (!moving)) //87 = W { movementTimestamp = getTimer(); moving = true; } if ((event.keyCode == 65) && (turningMode != 1)) //65 = A { turningTimestamp = getTimer(); turningMode = 1; } else if ((event.keyCode == 68) && (turningMode != 2)) //68 = D { turningTimestamp = getTimer(); turningMode = 2; } } private final function keyUp(event:KeyboardEvent):void { if ((event.keyCode == 87) && (moving)) moving = false; //87 = W if (((event.keyCode == 65) || (event.keyCode == 68)) && (turningMode != 0)) turningMode = 0; //65 = A, 68 = D } } } The results were as I expected. Absolutely no improvement. I really hope that someone has another suggestion as this thing needs fixing. Also, I doubt it's my system as I have a pretty good one (8GB RAM, Q9550 QuadCore intel, ATI Radeon 4870 512MB). Also, everyone else I asked so far had the same issue with my client. Update 5: another example of a smooth flash game just to demonstrate that my movement definitely is different! See http://www.spel.nl/game/bumpercraft.html Update 4: I traced the time before rendering (EVENT.RENDER) and right after rendering (EVENT.ENTER_FRAME), the results: rendering took: 14 ms rendering took: 14 ms rendering took: 12 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 14 ms rendering took: 12 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 14 ms rendering took: 12 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 14 ms rendering took: 14 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 24 ms rendering took: 18 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 232 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms rendering took: 14 ms rendering took: 16 ms rendering took: 12 ms rendering took: 14 ms rendering took: 12 ms The range is 12-16 ms. During these differences, the shocking/warping/flickering movement was already going on. There is also 1 peak of 232ms, at this time there was a relatively big warp. This is however not the biggest problme, the biggest problem are the continuous small warps during normal movement. Does this give anyone a clue? Update 3: After testing, I know that the following factors are not causing my problem: Bitmap's quality - changed with photoshop to an uglier 8 colours optimized graphic, no improvement at all. Constant rotation of image while turning - disabled it, no improvement at all Browser rendering - tried to use the flash player standalone, no improvement at all I am 100% convinced that the problem lies in either my code or in my algorithm. Please, help me out. It has been almost two weeks (1 week that I asked this question on SO) now and I still have to get my golden answer. Update 1: see bottom for full flex project source and a live demo demonstrating my problem. I'm working on a 2d flash game. Player ships are created as an object: ships[id] = new GameShip(); When movement and rotation information is available, this is being directed to the corresponding ship: ships[id].setMovementMode(1); //move forward Now, within this GameShip object movement works using the "Event.ENTER_FRAME" event: addEventListener(Event.ENTER_FRAME, movementHandler); The following function is then being run: private final function movementHandler(event:Event):void { var newTimeStamp:uint = UtilLib.getTimeStamp(); //set current timeStamp var distance:Number = (newTimeStamp - movementTimeStamp) / 1000 * movementSpeed; //speed = x pixels forward every 1 second movementTimeStamp = newTimeStamp; //update old timeStamp var diagonalChange:Array = getDiagonalChange(movementAngle, distance); //the diagonal position update based on angle and distance charX += diagonalChange[0]; charY += diagonalChange[1]; if (shipContainer) { //when the container is ready to be worked with shipContainer.x = charX; shipContainer.y = charY; } } private final function getDiagonalChange(angle:Number, distance:Number):Array { var rAngle:Number = angle * Math.PI/180; //convert degrees to radian return [Math.sin(rAngle) * distance, (Math.cos(rAngle) * distance) * -1]; } When the object is no longer moving, the event listener will be removed. The same method is being used for rotation. Everything works almost perfect. I've set the project's target FPS to 100 and created a FPS counter. According to the FPS counter, the average FPS in firefox is around 100, while the top is 1000 and the bottom is 22. I think that the bottom and top FPSs are only happening during the initialization of the client (startup). The problem is that the ship appears to be almost perfectly smooth, while it should be just that without the "almost" part. It's almost as if the ship is "flickering" very very fast, you can't actually see it but it's hard to focus on the object while it's moving with your eyes. Also, every now and then, there seems to be a bit of a framerate spike, as if the client is skipping a couple of frames, you then see it quickly warp. It is very difficult to explain what the real problem is, but in general it's that the movement is not perfectly smooth. So, do you have any suggestions on how to make the movement or transition of objects perfectly smooth? Update 1: I re-created the client to demonstrate my problem. Please check it out. The client: http://feedpostal.com/test/MovementTest.html The Actionscript Project (full source): http://feedpostal.com/test/MovementTest.rar An example of a smooth flash game (not created by me): http://www.gamesforwork.com/games/swf/Mission%20Racing_august_10th_2009.swf It took me a pretty long time to recreate this client side version, I hope this will help with solving the problem. Please note: yes, it is actually pretty smooth. But it is definitely not smooth enough.

    Read the article

  • How to remove an object from the canvas?

    - by Marius Jonsson
    Hello there, I am making this script that will rotate a needle on a tachometer using canvas. I am a newbie to this canvas. This is my code: function startup() { var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var meter = new Image(); meter.src = 'background.png'; var pin = new Image(); pin.src = 'needle.png'; context.drawImage(meter,0,0); context.translate(275,297); for (var frm = 0; frm < 6000; frm++){ var r=frm/1000; //handle here var i=r*36-27; //angle of rotation from value of r and span var angleInRadians = 3.14159265 * i/180; //converting degree to radian context.rotate(angleInRadians); //rotating by angle context.drawImage(pin,-250,-3); //adjusting pin center at meter center } } Here is the script in action: http://www.kingoslo.com/instruments/ The problem is, as you can see, that the red needle is not removed beetween each for-loop. What I need to do is to clear the canvas for the pin object between each cycle of the loop. How do I do this? Thanks. Kind regards, Marius

    Read the article

  • JS: Why isn't this variable available to the other functions?

    - by Marius Jonsson
    Hello there, I've am trying to make a canvas animation: var context; var meter; var pin; function init() { var meter = new Image(); var pin = new Image(); var context = document.getElementById('canvas').getContext('2d'); meter.src = 'background.png'; pin.src = 'needle.png'; context.drawImage(meter,0,0); context.translate(275,297); context.save(); setTimeout(startup,500); } function startup() { var r=2; // set rpm here. var i=r*36-27; var angleInRadians = 3.14159265 * i/180; //converting degree to radian context.rotate(angleInRadians); //rotating by angle context.drawImage(pin,-250,-3); //adjusting pin center at meter center context.restore(); } You can see the script at http://www.kingoslo.com/instruments/ With firebug I get error saying that context is undefined, which I think is strange. Thanks. Kind regards, Marius

    Read the article

1