Search Results

Search found 841 results on 34 pages for 'angle osaxon'.

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

  • C# - Angle between two 2d vectors, diff between two methods?

    - by Sean Ochoa
    Hey all. I've got this code snippet, and I'm wondering why the results of the first method differ from the results of the second method, given the same input? public double AngleBetween_1(vector a, vector b) { var dotProd = a.Dot(b); var lenProd = Len*b.Len; var divOperation = dotProd/lenProd; return Math.Acos(divOperation) * (180.0 / Math.PI); } public double AngleBetween_2(vector a, vector b) { var dotProd = a.Dot(b); var lenProd = Len*b.Len; var divOperation = dotProd/lenProd; return (1/Math.Cos(divOperation)) * (180.0 / Math.PI); }

    Read the article

  • camera captured image default rotating with 90 degree angle.

    - by kamiomar
    Dear, currently i am using android Api 4. my camera initializing code is follow: public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Now that the size is known, set up the camera parameters and begin // the preview. Parameters parameters = camera.getParameters(); parameters.set("jpeg-quality", 100); parameters.set("orientation", "portrait"); parameters.set("picture-size", "320X430"); parameters.set("rotation", 0); parameters.setPictureFormat(PixelFormat.JPEG); camera.setParameters(parameters); camera.startPreview(); } i set the orientation portrait, camera preview working appropriately. but when i captured the image ,its rotating the image with 90 degree.In the landscape orientation its working perfectly. so how i can capture normal image using portrait orientation. thanks.

    Read the article

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

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

    Read the article

  • How to calculate end-point at a given center plus an radius and angle?

    - by mystify
    I'm trying to do some basic quartz core drawing with arcs, but have an F in math ;-) I have a point: CGPoint center = CGPointMake(100.0f, 100.0f); CGFloat radius = 50.0f; CGFloat startAngle = 20.0f / 180.0f * M_PI; CGFloat endAngle = 150.0f / 180.0f * M_PI; CGContextAddArc(c, center.x, center.y, radius, startAngle, endAngle, 0); Now I want to draw a little dot on the middle of the arc. I mean, not the center point, but the little curve (arc) which is made up between the angles 20-150 degrees. I looked into quartz but unfortunately, there seems no helper function to calculate this. Probably some hardcore trigonometric logic with atan and stuff of this kind needed?

    Read the article

  • SteamCMD can't add files to my home directory

    - by Angle O'Saxon
    I'm trying to clean up the administration of some game servers I run on a Ubuntu box, part of which has been finally setting permissions properly so I can run the Steam console tool that controls updates and such. I had been running it as root using sudo, but I changed the permissions so that I can start it as a regular user rather than root. That bit seems to work fine, but now when SteamCMD actually starts, it errors with the following output ./steam.sh: line 24: /home/angleosaxon/.steampid: Permission denied Installing breakpad exception handler for appid(steam)/version(1334262703) SteamUpdater: Error: Couldn't create directory /home/angleosaxon/Steam/package, got error 13 [ 0%] Download complete. [----] Verifying installation... unlinked 0 orphaned pipes [----] !!! Fatal Error: Steam failed to load: *SteamStartEngine(0xbfa7cfa0) failed with error 1: Failed to open logfile /home/angleosaxon/Steam/steam.log Leaving aside the question of why it wants to add this information to my home directory, why is it getting access denied errors? As I understand it, since it's being run by my account, it operates with my permissions, so it should be able to read/write from my home directory, shouldn't it? This is the command I'm using to run it: /opt/steamcmd/steam.sh "+login UserAccount \"This is not my actual password.\"" +force_install_dir $ServerDir "+app_update 215360 validate" +quit

    Read the article

  • Allow non-sudo group to control Upstart job

    - by Angle O'Saxon
    I'm trying to set up an Upstart job to run on system startup, and that can also be started/stopped by members of a group other than sudo. With a previous version, I usedupdate-rc.d and scripts stored in /etc/init.d/ to get this working by adding %Group ALL = NOPASSWD: /etc/init.d/scriptname to my sudoers file, but I can't seem to get an equivalent working for Upstart. I tried adding %Group ALL = NOPASSWD: /sbin/initctl start jobname to the sudoers file, but trying to run the command start jobname produces this error: start: Rejected send message, 1 matched rules; type="method_call", sender=":1.21" (uid=1000 pid=5148 comm="start jobname " interface="com.ubuntu.Upstart0_6.Job" member="Start" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init") As near as I can tell, that's a complaint about how my user account isn't given the power to send 'Start' messages in the D-Bus config file for Upstart. I haven't been able to actually find any information on how to edit that file to give a group permission to access a specific service--does such an option exist? Is there a way to edit the Sudoers file so I can run the job without editing the config file? Am I better off just sticking with the previous version?

    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

  • Render 2 images that uses different shaders

    - by Code Vader
    Based on the giawa/nehe tutorials, how can I render 2 images with different shaders. I'm pretty new to OpenGl and shaders so I'm not completely sure whats happening in my code, but I think the shaders that is called last overwrites the first one. private static void OnRenderFrame() { // calculate how much time has elapsed since the last frame watch.Stop(); float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency; watch.Restart(); // use the deltaTime to adjust the angle of the cube angle += deltaTime; // set up the OpenGL viewport and clear both the color and depth bits Gl.Viewport(0, 0, width, height); Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); // use our shader program and bind the crate texture Gl.UseProgram(program); //<<<<<<<<<<<< TOP PYRAMID // set the transformation of the top_pyramid program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(top_pyramid, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(top_pyramidNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(top_pyramidUV, program, "vertexUV"); Gl.BindBuffer(top_pyramidTrianlges); // draw the textured top_pyramid Gl.DrawElements(BeginMode.Triangles, top_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<< CUBE // set the transformation of the cube program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(cube, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(cubeNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(cubeUV, program, "vertexUV"); Gl.BindBuffer(cubeQuads); // draw the textured cube Gl.DrawElements(BeginMode.Quads, cubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<<<< BOTTOM PYRAMID // set the transformation of the bottom_pyramid program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(bottom_pyramid, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(bottom_pyramidNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(bottom_pyramidUV, program, "vertexUV"); Gl.BindBuffer(bottom_pyramidTrianlges); // draw the textured bottom_pyramid Gl.DrawElements(BeginMode.Triangles, bottom_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<<<<< STAR Gl.Disable(EnableCap.DepthTest); Gl.Enable(EnableCap.Blend); Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One); Gl.BindTexture(starTexture); //calculate the camera position using some fancy polar co-ordinates Vector3 position = 20 * new Vector3(Math.Cos(phi) * Math.Sin(theta), Math.Cos(theta), Math.Sin(phi) * Math.Sin(theta)); Vector3 upVector = ((theta % (Math.PI * 2)) > Math.PI) ? Vector3.Up : Vector3.Down; program_2["view_matrix"].SetValue(Matrix4.LookAt(position, Vector3.Zero, upVector)); // make sure the shader program and texture are being used Gl.UseProgram(program_2); // loop through the stars, drawing each one for (int i = 0; i < stars.Count; i++) { // set the position and color of this star program_2["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(stars[i].dist, 0, 0)) * Matrix4.CreateRotationZ(stars[i].angle)); program_2["color"].SetValue(stars[i].color); Gl.BindBufferToShaderAttribute(star, program_2, "vertexPosition"); Gl.BindBufferToShaderAttribute(starUV, program_2, "vertexUV"); Gl.BindBuffer(starQuads); Gl.DrawElements(BeginMode.Quads, starQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); // update the position of the star stars[i].angle += (float)i / stars.Count * deltaTime * 2 * rotate_stars; stars[i].dist -= 0.2f * deltaTime * rotate_stars; // if we've reached the center then move this star outwards and give it a new color if (stars[i].dist < 0f) { stars[i].dist += 5f; stars[i].color = new Vector3(generator.NextDouble(), generator.NextDouble(), generator.NextDouble()); } } Glut.glutSwapBuffers(); } The same goes for the textures, whichever one I mention last gets applied to both object?

    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

  • Is it safe to call a function to intialize a class in a ctor list?

    - by Michael Dorgan
    I have Angle class that I want initialized to a random value. The Angle constructor can accept an int from a random() function. Is it safe to place this call in the ctor list: foo::foo() : Angle(random(0xFFFF)) {...} or do I have to do it in the body of the constructor? foo::foo() { Angle = Angle(random(0xFFFF)); ...} If it matters, the foo class is derived from another class and does have virtual methods. In addition, no exception handling is allowed in our app.

    Read the article

  • Calculating skew of text OpenCV

    - by Nick
    I am trying to calculate the skew of text in an image so I can correct it for the best OCR results. Currently this is the function I am using: double compute_skew(Mat &img) { // Binarize cv::threshold(img, img, 225, 255, cv::THRESH_BINARY); // Invert colors cv::bitwise_not(img, img); cv::Mat element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 3)); cv::erode(img, img, element); std::vector<cv::Point> points; cv::Mat_<uchar>::iterator it = img.begin<uchar>(); cv::Mat_<uchar>::iterator end = img.end<uchar>(); for (; it != end; ++it) if (*it) points.push_back(it.pos()); cv::RotatedRect box = cv::minAreaRect(cv::Mat(points)); double angle = box.angle; if (angle < -45.) angle += 90.; cv::Point2f vertices[4]; box.points(vertices); for(int i = 0; i < 4; ++i) cv::line(img, vertices[i], vertices[(i + 1) % 4], cv::Scalar(255, 0, 0), 1, CV_AA); return angle; } When I look at then angle in debug I get 0.000000 However when I give it this image I get proper results of a skew of about 16 degrees: How can I properly detect the skew in the first image?

    Read the article

  • Silverlight TemplateBinding to RotateTransform

    - by Trog Dog
    I am trying to create the simplest Silverlight templated control, and I can't seem to get TemplateBinding to work on the Angle property of a RotateTransform. Here's the ControlTemplate from generic.xaml: <ControlTemplate TargetType="local:CtlKnob"> <Grid x:Name="grid" RenderTransformOrigin="0.5,0.5"> <Grid.RenderTransform> <TransformGroup> <RotateTransform Angle="{TemplateBinding Angle}"/> <!-- This does not work --> <!-- <RotateTransform Angle="70"/> --> <!-- This works --> </TransformGroup> </Grid.RenderTransform> <Ellipse Stroke="#FFB70404" StrokeThickness="19"/> <Ellipse Stroke="White" StrokeThickness="2" Height="16" VerticalAlignment="Top" HorizontalAlignment="Center" Width="16" Margin="0,2,0,0"/> </Grid> </ControlTemplate> Here's the C#: using System.Windows; using System.Windows.Controls; namespace CtlKnob { public class CtlKnob : Control { public CtlKnob() { this.DefaultStyleKey = typeof(CtlKnob); } public static readonly DependencyProperty AngleProperty = DependencyProperty.Register("Angle", typeof(double), typeof(CtlKnob), null); public double Angle { get { return (double)GetValue(AngleProperty); } set { SetValue(AngleProperty,value); } } } }

    Read the article

  • Optimally place a pie slice in a rectangle.

    - by Lisa
    Given a rectangle (w, h) and a pie slice with start angle and end angle, how can I place the slice optimally in the rectangle so that it fills the room best (from an optical point of view, not mathematically speaking)? I'm currently placing the pie slice's center in the center of the rectangle and use the half of the smaller of both rectangle sides as the radius. This leaves plenty of room for certain configurations. Examples to make clear what I'm after, based on the precondition that the slice is drawn like a unit circle: A start angle of 0 and an end angle of PI would lead to a filled lower half of the rectangle and an empty upper half. A good solution here would be to move the center up by 1/4*h. A start angle of 0 and an end angle of PI/2 would lead to a filled bottom right quarter of the rectangle. A good solution here would be to move the center point to the top left of the rectangle and to set the radius to the smaller of both rectangle sides. This is fairly easy for the cases I've sketched but it becomes complicated when the start and end angles are arbitrary. I am searching for an algorithm which determines center of the slice and radius in a way that fills the rectangle best. Pseudo code would be great since I'm not a big mathematician.

    Read the article

  • Why is my arrow texture being drawn in odd places?

    - by tyjkenn
    This is a script I wrote that places an arrow on the screen, pointing to an enemy off-screen, or, if the enemy is on-screen, it places an arrow hovering above the enemy. Everything seems to work, except for some odd reason, I see random arrows floating around, often skewed and resized (which I really don't understand, because I only rotate and place in this script). Even when I only have one enemy in the scene, I still see these random arrows. It should only be drawing one per enemy. Note: when all enemies are removed, no arrows appear. var arrow : Texture; var cam : Camera; var dim : int = 30; function OnGUI() { var objects = GameObject.FindGameObjectsWithTag("Enemy"); for(var ob : GameObject in objects) { var pos = cam.WorldToViewportPoint(ob.transform.position); if(gameObject.GetComponent(FollowCamera).target != null){ var tar = gameObject.GetComponent(FollowCamera).target.parent; } if(pos.z>1 && ob.transform != tar){ var xDiff = (pos.x*cam.pixelWidth)-(cam.pixelWidth/2); var yDiff = (pos.y*cam.pixelHeight)-(cam.pixelHeight/2); var angle = Mathf.Rad2Deg*Mathf.Atan(yDiff/xDiff)+180; if(xDiff>0) angle += 180; var dist = Mathf.Sqrt(xDiff*xDiff + yDiff*yDiff); var slope = yDiff/xDiff; var camSlope = cam.pixelHeight/cam.pixelWidth; var theX = -1000.0; var theY = -1000.0; var mult = 0; var temp; if(Mathf.Abs(xDiff)>(cam.pixelWidth/2)||Mathf.Abs(yDiff)>(cam.pixelHeight/2)){ //touching right if(slope<camSlope && slope>-camSlope) { if(xDiff>(cam.pixelWidth/2)) { theX = cam.pixelWidth - (dim/2); mult = -1; }else if(xDiff<-(cam.pixelWidth/2)) { theX = (dim/2); mult = 1; } temp = ((cam.pixelWidth/2)*yDiff)/xDiff; theY =(cam.pixelHeight/2)+(mult*temp); } else{ if(yDiff>(cam.pixelHeight/2)) { theY = (dim/2); mult = 1; }else if(yDiff<-(cam.pixelHeight/2)) { theY = cam.pixelHeight - (dim/2); mult = -1; } temp = ((cam.pixelHeight/2)*xDiff)/yDiff; theX =(cam.pixelWidth/2)+(mult*temp); } } else { angle = -90; theX = (cam.pixelWidth/2)+xDiff; theY = (cam.pixelHeight/2)-yDiff-dim; } GUIUtility.RotateAroundPivot(-angle, Vector2(theX, theY)); Graphics.DrawTexture(Rect(theX-(dim/2),theY-(dim/2),dim,dim),arrow,null); GUIUtility.RotateAroundPivot(angle, Vector2(theX, theY)); } } }

    Read the article

  • Simple thruster like behaviour when rotating sprite

    - by ensamgud
    I'm prototyping some 2D game concepts with XNA and have added some basic keyboard inputs to control a triangle sprite. When I press key up the sprite accelerates in it's current facing direction, when I release the key it brakes down. For rotation, when I press left/right keys I rotate the sprite. Currently the sprite immedately changes direction when I rotate it. What I want is for it to keep moving in the same direction when I rotate, until I hit key up, adding thrust in whatever direction the sprite is pointing at. This would simulate thrusters on a classic space shooter like Asteroids. I'm adding an image to describe the behaviour I'm after and some code samples of how I'm doing things at the moment. This is my player struct, holding information of the sprite. public struct PlayerData { public Vector2 Position; // where to draw the sprite public Vector2 Direction; // travel direction of sprite public float Angle; // rotation of sprite public float Velocity; public float Acceleration; public float Decelleration; public float RotationAcceleration; public float RotationDecceleration; public float TopSpeed; public float Scale; } This is how I'm currently handling thrusting / braking (when pressing/releasing key up) (simplified, removed some bounds checking etc): player.Velocity += player.Acceleration * 0.1f; player.Velocity -= player.Acceleration * 0.1f; And when I rotate the sprite left and right: player.Angle -= player.RotationAcceleration * 0.1f; player.Angle += player.RotationAcceleration * 0.1f; This runs in the update loop, keeps the direction updated and updates the position: Vector2 up = new Vector2(0f, -1f); Matrix rotMatrix = Matrix.CreateRotationZ(player.Angle); player.Direction = Vector2.Transform(up, rotMatrix); player.Direction *= player.Velocity; player.Position += player.Direction; I am following along various beginner tutorials and haven't found any describing this, but I have tried some on my own without success. Do I need to change my velocity and acceleration fields to Vectors instead of floats to accomplish this type of movement? I realise my Angle and the Direction vector is currently tied together and I need to disconnect these somehow to be able to rotate freely without changing the direction of the movement, but I can't quite figure out how to do this while keeping the acceleration/decceleration functional. Would appreciate an explanation rather than pure code samples. Thanks,

    Read the article

  • Turtle Graphics as a Haskell Monad

    - by iliis
    I'm trying to implement turtle graphis in Haskell. The goal is to be able to write a function like this: draw_something = do fordward 100 right 90 forward 100 ... and then have it produce a list of points (maybe with additional properties): > draw_something (0,0) 0 -- start at (0,0) facing east (0 degrees) [(0,0), (0,100), (-100,100), ...] I have all this working in a 'normal' way, but I fail to implement it as a Haskell Monad and use the do-notation. The basic code: data State a = State (a, a) a -- (x,y), angle deriving (Show, Eq) initstate :: State Float initstate = State (0.0,0.0) 0.0 -- constrain angles to 0 to 2*pi fmod :: Float -> Float fmod a | a >= 2*pi = fmod (a-2*pi) | a < 0 = fmod (a+2*pi) | otherwise = a forward :: Float -> State Float -> [State Float] forward d (State (x,y) angle) = [State (x + d * (sin angle), y + d * (cos angle)) angle] right :: Float -> State Float -> [State Float] right d (State pos angle) = [State pos (fmod (angle+d))] bind :: [State a] -> (State a -> [State a]) -> [State a] bind xs f = xs ++ (f (head $ reverse xs)) ret :: State a -> [State a] ret x = [x] With this I can now write > [initstate] `bind` (forward 100) `bind` (right (pi/2)) `bind` (forward 100) [State (0.0,0.0) 0.0,State (0.0,100.0) 0.0,State (0.0,100.0) 1.5707964,State (100.0,99.99999) 1.5707964] And get the expected result. However I fail to implement this as an instance of Monad. instance Monad [State] where ... results in `State' is not applied to enough type arguments Expected kind `*', but `State' has kind `* -> *' In the instance declaration for `Monad [State]' And if I wrap the list in a new object data StateList a = StateList [State a] instance Monad StateList where return x = StateList [x] I get Couldn't match type `a' with `State a' `a' is a rigid type variable bound by the type signature for return :: a -> StateList a at logo.hs:38:9 In the expression: x In the first argument of `StateList', namely `[x]' In the expression: StateList [x] I tried various other versions but I never got it to run as I'd like to. What am I doing wrong? What do I understand incorrectly?

    Read the article

  • Follow point of interest by applying torque

    - by azymm
    Given a body with an orientation angle and a point of interest or targetAngle, is there an elegant solution for keeping the body oriented towards the point of interest by applying torque or impulses? I have a naive solution working below, but the effect is pretty 'wobbly', it'll overshoot each time, slowly getting closer to the target angle - undesirable effect in my case. I'd like to find a solution that is more intelligent - that can accelerate to near the target angle then decelerate and stop right at the target angle (or within a small range). If it helps, I'm using box2d and the body is a rectangle. def gameloop(dt): targetAngle = get_target_angle() bodyAngle = get_body_angle() deltaAngle = targetAngle - bodyAngle if deltaAngle > PI: deltaAngle = targetAngle - (bodyAngle + 2.0 * PI) if deltaAngle < -PI: deltaAngle = targetAngle - (bodyAngle - 2.0 * PI) # multiply by 2, for stronger reaction deltaAngle = deltaAngle * 2.0; body.apply_torque(deltaAngle); One other thing, when body has no linear velocity, the above solution works ok. But when the body has some linear velocity, the solution above causes really wonky movement. Not sure why, but would appreciate any hints as to why that might be.

    Read the article

  • How to I get a rotated sprite to move left or right?

    - by rphello101
    Using Java/Slick 2D, I'm using the mouse to rotate a sprite on the screen and the directional keys (in this case, WASD) to move the spite. Forwards and backwards is easy, just position += cos(ang)*speed or position -= cos(ang)*speed. But how do I get the sprite to move left or right? I'm thinking it has something to do with adding 90 degrees to the angle or something. Any ideas? Rotation code: int mX = Mouse.getX(); int mY = HEIGHT - Mouse.getY(); int pX = sprite.x+sprite.image.getWidth()/2; int pY = sprite.y+sprite.image.getHeight()/2; double mAng; if(mX!=pX){ mAng = Math.toDegrees(Math.atan2(mY - pY, mX - pX)); if(mAng==0 && mX<=pX) mAng=180; } else{ if(mY>pY) mAng=90; else mAng=270; } sprite.angle = mAng; sprite.image.setRotation((float) mAng); And the movement code (delta is change in time): Input input = gc.getInput(); Vector2f direction = new Vector2f(); Vector2f velocity = new Vector2f(); direction.x = (float) Math.cos(Math.toRadians(sprite.angle)); direction.y = (float) Math.sin(Math.toRadians(sprite.angle)); if(direction.length()>0) direction = direction.normalise(); //On a separate note, what does this line of code do? velocity.x = (float) (direction.x * sprite.moveSpeed); velocity.y = (float) (direction.y * sprite.moveSpeed); if(input.isKeyDown(sprite.up)){ sprite.x += velocity.x*delta; sprite.y += velocity.y*delta; }if (input.isKeyDown(sprite.down)){ sprite.x -= velocity.x*delta; sprite.y -= velocity.y*delta; }if (input.isKeyDown(sprite.left)){ //??? }if (input.isKeyDown(sprite.right)){ //??? }

    Read the article

  • 360 snake movement

    - by Darius Janavicius
    I'm trying to do 360 degree snake game in actionscript 3. Here is my movement code: //head movement head.x += snake_speed*Math.cos((head.rotation) * (Math.PI /180)); head.y += snake_speed*Math.sin((head.rotation) * (Math.PI /180)); if (dir == "left") head.rotation -= snake_speed*2; if (dir == "right") head.rotation +=snake_speed*2; //Body part movement for(var i:int = body_parts.length-1; i>0; i--) { var angle = (body_parts[i-1].rotation)*(Math.PI/180); body_parts[i].y = body_parts[i-1].y - (25 * Math.sin(angle)); body_parts[i].x = body_parts[i-1].x - (25 * Math.cos(angle)); body_parts[i].rotation = body_parts[i-1].rotation; } With this code head moves just like I want it to move, but body parts have the same angle as head and it looks wrong. What I want to achieve is to make body parts to move like in game "Ultimate snake". Here is a link to that game: http://armorgames.com/play/387/ultimate-snake P.S. I saw similar question here "How to approach 360 degree snake" but didnt understand the answer :/

    Read the article

  • Can't get sprite to rotate correctly?

    - by rphello101
    I'm attempting to play with graphics using Java/Slick 2d. I'm trying to get my sprite to rotate to wherever the mouse is on the screen and then move accordingly. I figured the best way to do this was to keep track of the angle the sprite is at since I have to multiply the cosine/sine of the angle by the move speed in order to get the sprite to go "forwards" even if it is, say, facing 45 degrees in quadrant 3. However, before I even worry about that, I'm having trouble even getting my sprite to rotate in the first place. Preliminary console tests showed that this code worked, but when applied to the sprite, it just kind twitches. Anyone know what's wrong? int mX = Mouse.getX(); int mY = HEIGHT - Mouse.getY(); int pX = sprite.x; int pY = sprite.y; int tempY, tempX; double mAng, pAng = sprite.angle; double angRotate=0; if(mX!=pX){ tempY=pY-mY; tempX=mX-pX; mAng = Math.toDegrees(Math.atan2(Math.abs((tempY)),Math.abs((tempX)))); if(mAng==0 && mX<=pX) mAng=180; } else{ if(mY>pY) mAng=270; else mAng=90; } //Calculations if(mX<pX&&mY<pY){ //If in Q2 mAng = 180-mAng; } if(mX<pX&&mY>pY){ //If in Q3 mAng = 180+mAng; } if(mX>pX&&mY>pY){ //If in Q4 mAng = 360-mAng; } angRotate = mAng-pAng; sprite.angle = mAng; sprite.image.setRotation((float)angRotate);

    Read the article

  • Delaying a Foreach loop half a second

    - by Sigh-AniDe
    I have created a game that has a ghost that mimics the movement of the player after 10 seconds. The movements are stored in a list and i use a foreach loop to go through the commands. The ghost mimics the movements but it does the movements way too fast, in split second from spawn time it catches up to my current movement. How do i slow down the foreach so that it only does a command every half a second? I don't know how else to do it. Please help this is what i tried : The foreach runs inside the update method DateTime dt = DateTime.Now; foreach ( string commandDirection in ghostMovements ) { int mapX = ( int )( ghostPostition.X / scalingFactor ); int mapY = ( int )( ghostPostition.Y / scalingFactor ); // If the dt is the same as current time if ( dt == DateTime.Now ) { if ( commandDirection == "left" ) { switch ( ghostDirection ) { case ghostFacingUp: angle = 1.6f; ghostDirection = ghostFacingRight; Program.form.direction = ""; dt.AddMilliseconds( 500 );// add half a second to dt break; case ghostFacingRight: angle = 3.15f; ghostDirection = ghostFacingDown; Program.form.direction = ""; dt.AddMilliseconds( 500 ); break; case ghostFacingDown: angle = -1.6f; ghostDirection = ghostFacingLeft; Program.form.direction = ""; dt.AddMilliseconds( 500 ); break; case ghostFacingLeft: angle = 0.0f; ghostDirection = ghostFacingUp; Program.form.direction = ""; dt.AddMilliseconds( 500 ); break; } } } }

    Read the article

  • I am looking to create realistic car movement using vectors

    - by bobthemac
    I have goggled how to do this and found this http://www.helixsoft.nl/articles/circle/sincos.htm I have had a go at it but most of the functions that were showed didn't work I just got errors because they didn't exist. I have looked at the cos and sin functions but don't understand how to use them or how to get the car movement working correctly using vectors. I have no code because I am not sure what to do sorry. Any help is appreciated. EDIT: I have restrictions that I must use the TL engine for my game, I am not allowed to add any sort of physics engine. It must be programmed in c++. Here is a sample of what i got from trying to follow what was done in the link I provided. if(myEngine->KeyHeld(Key_W)) { length += carSpeedIncrement; } if(myEngine->KeyHeld(Key_S)) { length -= carSpeedIncrement; } if(myEngine->KeyHeld(Key_A)) { angle -= carSpeedIncrement; } if(myEngine->KeyHeld(Key_D)) { angle += carSpeedIncrement; } carVolocityX = cos(angle); carVolocityZ = cos(angle); car->MoveX(carVolocityX * frameTime); car->MoveZ(carVolocityZ * frameTime);

    Read the article

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