Search Results

Search found 20273 results on 811 pages for 'network camera'.

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

  • OpenGL camera moves faster than player

    - by opiop65
    I have a side scroller game made in OpenGL, and I'm trying to center the player in the viewport when he moves. I know how to do it: cameraX = Width / 2 / TileSize - playerPosX cameraY = Height / 2 / TileSize - playerPosY However, I have a problem. The player and "camera" move, but the player moves faster than the "camera" scrolls. So, the player can actually move out of the screen. Some code, this is how I translate the camera: public Camera(){ } public void update(Player p){ glTranslatef(-p.getPos().x - Main.WIDTH / 64 / 2, -p.getPos().y - Main.HEIGHT / 64 / 2, 1); } Here's how I move the player: public void update(){ if(Keyboard.isKeyDown(Keyboard.KEY_D)){ this.move(MOVESPEED, 0); } if(Keyboard.isKeyDown(Keyboard.KEY_A)){ this.move(-MOVESPEED, 0); } } The move method: public void move(float x, float y){ this.getPos().set(this.getPos().x + x, this.getPos().y + y); } And then after I move the player, I update the player's geometry, which shouldn't matter. What am I doing wrong here, this seems like such a simple problem, yet it doesn't work!

    Read the article

  • Moving player in direciton camera is facing

    - by Samurai Fox
    I have a 3rd person camera which can rotate around the player. My problem is that wherever camera is facing, players forward is always the same direction. For example when camera is facing the right side of the player, when I press button to move forward, I want player to turn to the left and make that the "new forward". My camera script so far: using UnityEngine; using System.Collections; public class PlayerScript : MonoBehaviour { public float RotateSpeed = 150, MoveSpeed = 50; float DeltaTime; void Update() { DeltaTime = Time.deltaTime; transform.Rotate(0, Input.GetAxis("LeftX") * RotateSpeed * DeltaTime, 0); transform.Translate(0, 0, -Input.GetAxis("LeftY") * MoveSpeed * DeltaTime); } } public class CameraScript : MonoBehaviour { public GameObject Target; public float RotateSpeed = 170, FollowDistance = 20, FollowHeight = 10; float RotateSpeedPerTime, DesiredRotationAngle, DesiredHeight, CurrentRotationAngle, CurrentHeight, Yaw, Pitch; Quaternion CurrentRotation; void LateUpdate() { RotateSpeedPerTime = RotateSpeed * Time.deltaTime; DesiredRotationAngle = Target.transform.eulerAngles.y; DesiredHeight = Target.transform.position.y + FollowHeight; CurrentRotationAngle = transform.eulerAngles.y; CurrentHeight = transform.position.y; CurrentRotationAngle = Mathf.LerpAngle(CurrentRotationAngle, DesiredRotationAngle, 0); CurrentHeight = Mathf.Lerp(CurrentHeight, DesiredHeight, 0); CurrentRotation = Quaternion.Euler(0, CurrentRotationAngle, 0); transform.position = Target.transform.position; transform.position -= CurrentRotation * Vector3.forward * FollowDistance; transform.position = new Vector3(transform.position.x, CurrentHeight, transform.position.z); Yaw = Input.GetAxis("Right Horizontal") * RotateSpeedPerTime; Pitch = Input.GetAxis("Right Vertical") * RotateSpeedPerTime; transform.Translate(new Vector3(Yaw, -Pitch, 0)); transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z); transform.LookAt(Target.transform); } }

    Read the article

  • How do I create a camera?

    - by Morphex
    I am trying to create a generic camera class for a game engine, which works for different types of cameras (Orbital, GDoF, FPS), but I have no idea how to go about it. I have read about quaternions and matrices, but I do not understand how to implement it. Particularly, it seems you need "Up", "Forward" and "Right" vectors, a Quaternion for rotations, and View and Projection matrices. For example, an FPS camera only rotates around the World Y and the Right Axis of the camera; the 6DoF rotates always around its own axis, and the orbital is just translating for a set distance and making it look always at a fixed target point. The concepts are there; implementing this is not trivial for me. SharpDX seems to have has already Matrices and Quaternions implemented, but I don't know how to use them to create a camera. Can anyone point me on what am I missing, what I got wrong? I would really enjoy if you could give a tutorial, some piece of code, or just plain explanation of the concepts.

    Read the article

  • Quaternion LookAt for camera

    - by Homar
    I am using the following code to rotate entities to look at points. glm::vec3 forwardVector = glm::normalize(point - position); float dot = glm::dot(glm::vec3(0.0f, 0.0f, 1.0f), forwardVector); float rotationAngle = (float)acos(dot); glm::vec3 rotationAxis = glm::normalize(glm::cross(glm::vec3(0.0f, 0.0f, 1.0f), forwardVector)); rotation = glm::normalize(glm::quat(rotationAxis * rotationAngle)); This works fine for my usual entities. However, when I use this on my Camera entity, I get a black screen. If I flip the subtraction in the first line, so that I take the forward vector to be the direction from the point to my camera's position, then my camera works but naturally my entities rotate to look in the opposite direction of the point. I compute the transformation matrix for the camera and then take the inverse to be the View Matrix, which I pass to my OpenGL shaders: glm::mat4 viewMatrix = glm::inverse( cameraTransform->GetTransformationMatrix() ); The orthographic projection matrix is created using glm::ortho. What's going wrong?

    Read the article

  • World Location issues with camera and particle

    - by Joe Weeks
    I have a bit of a strange question, I am adapting the existing code base including the tile engine as per the book: XNA 4.0 Game Development by example by Kurt Jaegers, particularly the aspect that I am working on is the part about the 2D platformer in the last couple of chapters. I am creating a platformer which has a scrolling screen (similar to an old school screen chase), I originally did not have any problems with this aspect as it is simply a case of updating the camera position on the X axis with game time, however I have since added a particle system to allow the players to fire weapons. This particle shot is updated via the world position, I have translated everything correctly in terms of the world position when the collisions are checked. The crux of the problem is that the collisions only work once the screen is static, whilst the camera is moving to follow the player, the collisions are offset and are hitting blocks that are no longer there. My collision for particles is as follows (There are two vertical and horizontal): protected override Vector2 horizontalCollisionTest(Vector2 moveAmount) { if (moveAmount.X == 0) return moveAmount; Rectangle afterMoveRect = CollisionRectangle; afterMoveRect.Offset((int)moveAmount.X, 0); Vector2 corner1, corner2; // new particle world alignment code. afterMoveRect = Camera.ScreenToWorld(afterMoveRect); // end. if (moveAmount.X < 0) { corner1 = new Vector2(afterMoveRect.Left, afterMoveRect.Top + 1); corner2 = new Vector2(afterMoveRect.Left, afterMoveRect.Bottom - 1); } else { corner1 = new Vector2(afterMoveRect.Right, afterMoveRect.Top + 1); corner2 = new Vector2(afterMoveRect.Right, afterMoveRect.Bottom - 1); } Vector2 mapCell1 = TileMap.GetCellByPixel(corner1); Vector2 mapCell2 = TileMap.GetCellByPixel(corner2); if (!TileMap.CellIsPassable(mapCell1) || !TileMap.CellIsPassable(mapCell2)) { moveAmount.X = 0; velocity.X = 0; } return moveAmount; } And the camera is pretty much the same as the one in the book... with this added (as an early test). public static void Update(GameTime gameTime) { position.X += 1; }

    Read the article

  • OpenGL: Move camera regardless of rotation

    - by Markus
    For a 2D board game I'd like to move and rotate an orthogonal camera in coordinates given in a reference system (window space), but simply can't get it to work. The idea is that the user can drag the camera over a surface, rotate and scale it. Rotation and scaling should always be around the center of the current viewport. The camera is set up as: gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(-width/2, width/2, -height/2, height/2, nearPlane, farPlane); where width and height are equal to the viewport's width and height, so that 1 unit is one pixel when no zoom is applied. Since these transformations usually mean (scaling and) translating the world, then rotating it, the implementation is: gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); gl.glRotatef(rotation, 0, 0, 1); // e.g. 45° gl.glTranslatef(x, y, 0); // e.g. +10 for 10px right, -2 for 2px down gl.glScalef(zoomFactor, zoomFactor, zoomFactor); // e.g. scale by 1.5 That however has the nasty side effect that translations are transformed as well, that is applied in world coordinates. If I rotate around 90° and translate again, X and Y axis are swapped. If I reorder the transformations so they read gl.glTranslatef(x, y, 0); gl.glScalef(zoomFactor, zoomFactor, zoomFactor); gl.glRotatef(rotation, 0, 0, 1); the translation will be applied correctly (in reference space, so translation along x always visually moves the camera sideways) but rotation and scaling are now performed around origin. It shouldn't be too hard, so what is it I'm missing?

    Read the article

  • Apply Quaternion to Camera in libGDX

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

    Read the article

  • Camera changes view when controller connected

    - by ChocoMan
    I have a weird situation. I have a model set to 0 for X,Y and Z. My camera's position is set to: 0 (X-value, but updates when the model moves around) the model's height + 20f (about the same level as the model's shoulders) 25f (behind the model) Without the controller plugged in, everything looks fine as I want it. But as soon as I plug the controller in, the camera aims to the sky! But when I unplug the controller, the camera is back to what it should be. Does anyone have any insight as to what may cause this from plugging a controller in?

    Read the article

  • Unity3D 3.5 pro - Moving the camera vs setting draw distance

    - by stoicfury
    I move the camera mostly via right-click + WASD, sometimes with [shift] if I want it to move faster. Occasionally, instead of moving my camera, it alters the draw distance / FOV / some visual aspect of the editing scene that causes trees and other object to disappear when I scroll enough, and eventually even the terrain starts disappearing. It is not m "zooming out". My camera does not move, the width and height of the FOV stays the same (one might say the depth is being altered though). What key am I hitting to cause this to happen, and is it possible to disable it? side note: "keybinds" is probably the most spot-on tag for this question but it doesn't exist (surprisingly) and I lack the rep to create it.

    Read the article

  • How can I track a falling ball with a camera?

    - by Jason
    I have been trying to get my camera to follow a falling ball but with no success. here is the code float cameraY = (FrustumHeight / 2)+((ball.getPosition().y) /2) - (FrustumHeight /2); if (cameraY < FrustumHeight/2 ) cameraY = FrustumHeight/2; camera.position.set(0f,cameraY, 0f); Gdx.app.log("test",camera.position.toString()); camera.update(); camera.apply(Gdx.gl10); batch.setProjectionMatrix(camera.combined); batch.begin(); batch.draw(backgroundRegion, camera.position.x - FrustumWidth / 2, -cameraY - (FrustumHeight/2) , 320, 480); batch.draw(ballTexture, (camera.position.x - FrustumWidth / 2) + ball.getPosition().x,-cameraY + ball.getPosition().y - (FrustumHeight/2) , 32, 32); I'm sure I am doing this completely wrong - what is the correct way to do this?

    Read the article

  • camera preview portrait problem in android application

    - by sujitjitu
    Hi this is my code for simple camera application in android .i have copied it from unlocking android e-book . Everything is working fine in emulator but when i am installing it in device the camera preview is working only in landscape mode. I have tried many thing but could not find any solution. Please see the code below and if you have any solution for it than it will be helpful to me. this is the code....... public class SimpleCamera extends Activity implements SurfaceHolder.Callback { private Camera camera; private boolean isPreviewRunning = false; private SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS"); private SurfaceView surfaceView; private SurfaceHolder surfaceHolder; private Uri targetResource = Media.EXTERNAL_CONTENT_URI; public void onCreate(Bundle icicle) { super.onCreate(icicle); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().setFormat(PixelFormat.TRANSLUCENT); setContentView(R.layout.main); surfaceView = (SurfaceView)findViewById(R.id.surface); surfaceHolder = surfaceView.getHolder(); surfaceHolder.getSurface(); // Surface.setOrientation(Display.DEFAULT_DISPLAY,Surface.ROTATION_180); //didn't work at all surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public boolean onCreateOptionsMenu(android.view.Menu menu) { MenuItem item = menu.add(0, 0, 0, "View Pictures"); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(Intent.ACTION_VIEW, targetResource); startActivity(intent); return true; } }); return true; } protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } Camera.PictureCallback mPictureCallbackRaw = new Camera.PictureCallback() { public void onPictureTaken(byte[] data, Camera c) { camera.startPreview(); } }; Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback() { public void onShutter() { } }; public boolean onKeyDown(int keyCode, KeyEvent event) { ImageCaptureCallback camDemo = null; if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { try { String filename = timeStampFormat.format(new Date()); ContentValues values = new ContentValues(); values.put(Media.TITLE, filename); values.put(Media.DESCRIPTION, "Image from Android Emulator"); Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); camDemo = new ImageCaptureCallback( getContentResolver().openOutputStream(uri)); } catch(Exception ex ){ } } if (keyCode == KeyEvent.KEYCODE_BACK) { return super.onKeyDown(keyCode, event); } if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { camera.takePicture(mShutterCallback, mPictureCallbackRaw, camDemo); return true; } return false; } protected void onResume() { Log.e(getClass().getSimpleName(), "onResume"); super.onResume(); } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } protected void onStop() { super.onStop(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (isPreviewRunning) { camera.stopPreview(); } Camera.Parameters p = camera.getParameters(); p.setPreviewSize(w,h); //p.set("rotation","90"); // it didn't work //P.setRotation(90); // only work in 2.0 or later SDK but i am using 1.5 camera.setParameters(p); try { camera.setPreviewDisplay(holder); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } camera.startPreview(); isPreviewRunning = true; } public void surfaceCreated(SurfaceHolder holder) { camera = Camera.open(); } public void surfaceDestroyed(SurfaceHolder holder) { camera.stopPreview(); isPreviewRunning = false; camera.release(); } } any help will be appreciated..

    Read the article

  • Architectural advice - web camera remote access

    - by Alan Hollis
    I'm looking for architectural advice. I have a client who I've built a website for which essentially allows users to view their web cameras remotely. The current flow of data is as follows: User opens page to view web camera image. Javascript script polls url on server ( appended with unique timestamp ) every 1000ms Ftp connection is enabled for the cameras ftp user. Web camera opens ftp connection to server. Web camera begins taking photos. Web camera sends photo to ftp server. On image url request: Server reads latest image on hard drive uploaded via ftp for camera. Server deleted any older images from the server. This is working okay at the moment for a small amount of users/cameras ( about 10 users and around the same amount of cameras), but we're starting to worrying about the scalability of this approach. My original plan was instead of having the files read from the server, the web server would open up an ftp connection to the web server and read the latest images directly from there meaning we should have been able to scale horizontally fairly easily. But ftp connection establishment times were too slow ( mainly due to the fact that PHP out of the ox is unable to persist ftp connections ) and so we abandoned this approach and went straight for reading from the hard drive. The firmware provider for the cameras state they're able to build a http client which instead of using ftp to upload the image could post the image to a web server. This seems plausible enough to me, but I'm looking for some architectural advice. My current thought is a simple Nginx/PHP/Redis stack. Web camera issues post requests of latest image to Nginx/PHP and the latest image for that camera is stored in Redis. The clients can then pull the latest image from Redis which should be extremely quick as the images will always be stored in memory. The data flow would then become: User opens page to view web camera image. Javascript script polls url on server ( appended with unique timestamp ) every 1000ms Camera is sent an http request to start posting images to a provided url Web camera begins taking photos. Web camera sends post requests to server as fast as it can On image url request: Server reads latest image from redis Server tells redis to delete later image My questions are: Are there any greater overheads of transferring images via HTTP instead of FTP? Is there a simple way to calculate how many potential cameras we could have streaming at once? Is there any way to prevent potentially DOS'ing our own servers due to web camera requests? Is Redis a good solution to this problem? Should I abandon PHP/Ngix combination and go for something else? Is this proposed solution actually any good? Will adding HTTPs to the mix cause posting the image to become too slow? Thanks in advance Alan

    Read the article

  • Stage3D: Camera pans the whole screen

    - by Thomas Versteeg
    I am trying to create a 2D Stage3D game where you can move the camera around the level in an RTS style. I thought about using Orthographic Matrix3D functions for this but when I try to scroll the whole "stage" also scrolls. This is the Camera code: public function Camera2D(width:int, height:int, zoom:Number = 1) { resize(width, height); _zoom = zoom; } public function resize(width:Number, height:Number):void { _width = width; _height = height; _projectionMatrix = makeMatrix(0, width, 0, height); _recalculate = true; } protected function makeMatrix(left:Number, right:Number, top:Number, bottom:Number, zNear:Number = 0, zFar:Number = 1):Matrix3D { return new Matrix3D(Vector.<Number>([ 2 / (right - left), 0, 0, 0, 0, 2 / (top - bottom), 0, 0, 0, 0, 1 / (zFar - zNear), 0, 0, 0, zNear / (zNear - zFar), 1 ])); } public function get viewMatrix():Matrix3D { if (_recalculate) { _recalculate = false; _viewMatrix.identity(); _viewMatrix.appendTranslation( -_width / 2 - _x, -_height / 2 - y, 0); _viewMatrix.appendScale(_zoom, _zoom, 1); _renderMatrix.identity(); _renderMatrix.append(_viewMatrix); _renderMatrix.append(_projectionMatrix); } return _renderMatrix; } And the camera is send directly to the GPU with: c3d.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, cameraMatrix, true); And these are the shaders: ------Vertex Shader------ m44 op, va0, vc0 mov v0, va1.xy mov v0.z, va0.z ------Fragment Shader------ tex ft0, v0, fs0 <2d,linear,nomip> mov oc, ft1 Here is a example and here are two screenshots to show what I mean: How do I only let the inside of the stage3D scroll and not the whole stage?

    Read the article

  • Roll a DIY Camera Jib for $25

    - by Jason Fitzpatrick
    Video gear is expensive; save your pennies by building a DIY camera jib for smooth camera movement on a budget. Over at Oliva tech they explain just how few parts you need to build their DIY jib: The guys here at the studio mocked up a simple DIY jib that is not only ridiculously inexpensive to piece together, but also very straight forward. The point of this jib was to get a very wide range of motion from top to bottom with only a few feet of 0.75? square tube, 1? angled aluminum, 1/4? nuts and bolts, and nylon washers is all you’ll need to put the jib together. This light weight jib can be used on small portable tripods, but will require a fluid head for panning left and right. Hit up the link below for a detailed parts list and build guide. How to Make a DIY Camera Jib [via Make] How to Own Your Own Website (Even If You Can’t Build One) Pt 1 What’s the Difference Between Sleep and Hibernate in Windows? Screenshot Tour: XBMC 11 Eden Rocks Improved iOS Support, AirPlay, and Even a Custom XBMC OS

    Read the article

  • Keep 3d model facing the camera at all angles

    - by Sparky41
    I'm trying to keep a 3d plane facing the camera at all angles but while i have some success with this: Vector3 gunToCam = cam.cameraPosition - getWorld.Translation; Vector3 beamRight = Vector3.Cross(torpDirection, gunToCam); beamRight.Normalize(); Vector3 beamUp = Vector3.Cross(beamRight, torpDirection); shipeffect.beamWorld = Matrix.Identity; shipeffect.beamWorld.Forward = (torpDirection) * 1f; shipeffect.beamWorld.Right = beamRight; shipeffect.beamWorld.Up = beamUp; shipeffect.beamWorld.Translation = shipeffect.beamPosition; *Note: Logic not wrote by me i just found this rather useful It seems to only face the camera at certain angles. For example if i place the camera behind the plane you can see it that only Roll's around the axis like this: http://i.imgur.com/FOKLx.png (imagine if you are looking from behind where you have fired from. Any idea what to what the problem is (angles are not my specialty) shipeffect is an object that holds this class variables: public Texture2D altBeam; public Model beam; public Matrix beamWorld; public Matrix[] gunTransforms; public Vector3 beamPosition;

    Read the article

  • Mod a Swing Arm Lamp into an Adjustable Camera Stand

    - by Jason Fitzpatrick
    If you’re looking for a simple way to get a bird’s eye view to record your DIY projects or other table-based activities like gaming or tinkering, this simple modification to a swing-arm lamp offers a highly flexible camera mount on the cheap. IKEAHacker reader Stef needed an adjustable arm for his iPhone camera so he could record in a top-down-view for some drawing tutorials he was working on. Rather than shell out big bucks for a custom boom arm, he scrounged up a swing arm lamp with a broken shade in the as-is bin at his local IKEA. To mount the iPhone he simply attached a car mount for the iPhone to the swing arm and called it good. Hit up the link below for more pictures; even if you don’t have an IKEA nearby, swing arm lamps are cheap and easy to acquire. Forsa Camera Stand [IKEAHackers] How to Make Your Laptop Choose a Wired Connection Instead of Wireless HTG Explains: What Is Two-Factor Authentication and Should I Be Using It? HTG Explains: What Is Windows RT and What Does It Mean To Me?

    Read the article

  • How to make a player stay within bounds of world with 2D Camera

    - by Craig
    Im creating a simple top down survival game. At the moment, i have the sprite which is a ship and moves by rotating left or right then going forward in that direction. I have implemented a 2D camera, its always centered on the player. However, when i move towards the bounds of the world that the sprite is in it just keeps on going :( How to i sort it that it stops at the edge of the world and cant go beyond it? Cheers :) Below is the main game class using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace GamesCoursework_1 { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // player variables Texture2D Ship; Vector2 Ship_Position; float Ship_Rotation = 0.0f; Vector2 Ship_Origin; Vector2 Ship_Velocity; const float tangentialVelocity = 4f; float friction = 0.05f; static Point CameraViewport = new Point(800, 800); Camera2d cam = new Camera2d((int)CameraViewport.X, (int)CameraViewport.Y); //Size of world static Point worldSize = new Point(1600, 1600); // Screen variables static Point worldCenter = new Point(worldSize.X / 2, worldSize.Y / 2); Rectangle playerBounds = new Rectangle(CameraViewport.X / 2, CameraViewport.Y / 2, worldSize.X - CameraViewport.X, worldSize.Y - CameraViewport.Y); Rectangle worldBounds = new Rectangle(0, 0, worldSize.X, worldSize.Y); Texture2D background; public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = CameraViewport.X; graphics.PreferredBackBufferHeight = CameraViewport.Y; Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here Ship = Content.Load<Texture2D>("Ship"); Ship_Origin.X = Ship.Width / 2; Ship_Origin.Y = Ship.Height / 2; background = Content.Load<Texture2D>("aus"); Ship_Position = new Vector2(worldCenter.X, worldCenter.Y); cam.Pos = Ship_Position; cam.Zoom = 1f; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here Ship_Position = Ship_Velocity + Ship_Position; keyPressed(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null,null, cam.get_transformation(GraphicsDevice)); spriteBatch.Draw(background, Vector2.Zero, Color.White); spriteBatch.Draw(Ship, Ship_Position, Ship.Bounds, Color.White, Ship_Rotation, Ship_Origin, 1.0f, SpriteEffects.None, 0f); spriteBatch.End(); base.Draw(gameTime); } private void Ship_Move(Vector2 move) { Ship_Position += move; } private void keyPressed() { KeyboardState keyState; // Move right keyState = Keyboard.GetState(); if (keyState.IsKeyDown(Keys.Right)) { Ship_Rotation = Ship_Rotation + 0.1f; } if (keyState.IsKeyDown(Keys.Left)) { Ship_Rotation = Ship_Rotation - 0.1f; } if (keyState.IsKeyDown(Keys.Up)) { Ship_Velocity.X = (float)Math.Cos(Ship_Rotation) * tangentialVelocity; Ship_Velocity.Y = (float)Math.Sin(Ship_Rotation) * tangentialVelocity; if ((int)Ship_Position.Y < playerBounds.Bottom && (int)Ship_Position.Y > playerBounds.Top) cam._pos.Y = Ship_Position.Y; if ((int)Ship_Position.X > playerBounds.Left && (int)Ship_Position.X < playerBounds.Right) cam._pos.X = Ship_Position.X; //tried world bounds here if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, -tangentialVelocity * 2); if (!worldBounds.Contains(new Point((int)Ship_Position.X, (int)Ship_Position.Y))) Ship_Position -= new Vector2(0.0f, 2 * tangentialVelocity); } else if(Ship_Velocity != Vector2.Zero) { float i = Ship_Velocity.X; float j = Ship_Velocity.Y; Ship_Velocity.X = i -= friction * i; Ship_Velocity.Y = j -= friction * j; if ((int)Ship_Position.Y < playerBounds.Bottom && (int)Ship_Position.Y > playerBounds.Top) cam._pos.Y = Ship_Position.Y; if ((int)Ship_Position.X > playerBounds.Left && (int)Ship_Position.X < playerBounds.Right) cam._pos.X = Ship_Position.X; } if (keyState.IsKeyDown(Keys.Q)) { if (cam.Zoom < 2f) cam.Zoom += 0.05f; } if (keyState.IsKeyDown(Keys.A)) { if (cam.Zoom > 0.3f) cam.Zoom -= 0.05f; } } } } my 2d camera class using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace GamesCoursework_1 { public class Camera2d { protected float _zoom; // Camera Zoom public Matrix _transform; // Matrix Transform public Vector2 _pos; // Camera Position protected float _rotation; // Camera Rotation public int _viewportWidth, _viewportHeight; // viewport size public Camera2d(int ViewportWidth, int ViewportHeight) { _zoom = 1.0f; _rotation = 0.0f; _pos = Vector2.Zero; _viewportWidth = ViewportWidth; _viewportHeight = ViewportHeight; } // Sets and gets zoom public float Zoom { get { return _zoom; } set { _zoom = value; if (_zoom < 0.1f) _zoom = 0.1f; } // Negative zoom will flip image } public float Rotation { get { return _rotation; } set { _rotation = value; } } // Auxiliary function to move the camera public void Move(Vector2 amount) { _pos += amount; } // Get set position public Vector2 Pos { get { return _pos; } set { _pos = value; } } public Matrix get_transformation(GraphicsDevice graphicsDevice) { _transform = // Thanks to o KB o for this solution Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) * Matrix.CreateRotationZ(Rotation) * Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) * Matrix.CreateTranslation(new Vector3(_viewportWidth * 0.5f, _viewportHeight * 0.5f, 0)); return _transform; } } }

    Read the article

  • Photo transfer problems from camera

    - by warkior
    We have a digital camera (Cannon SX130 IS) which we often connect to the Ubuntu 12.10 desktop via USB in order to download the images. In past flavours of Linux (Mint 12 was most recent) it worked fine, however since upgrading to Ubuntu 12.10, the process fails after downloading a small number of the images. I can view the images which will be transferred in the preview window, and I can browse the camera file system to download the images manually, but if I just drag/drop the images over from camera to desktop, it freezes after 5-6 are copied over. I've been able to get around the problem by only copying 3-4 at a time, but when you have 100+ images to transfer, that gets really frustrating. Any advice on where I could start looking for answers, or how I could diagnose the source of the problem further? We have also had some issues with WireLess USB mice though it may not be related. I'm hoping my USB controller in the computer isn't dying... it's not that old. Also, it seems to work much better under Windows.

    Read the article

  • Picture rendered from above and below using an Orthographic camera do not match

    - by Roy T.
    I'm using an orthographic camera to render slices of a model (in order to voxelize it). I render each slice both from above and below in order to determine what is inside each slice. I am using an orthographic camera The model I render is a simple 'T' shape constructed from two cubes. The cubes have the same dimensions and have the same Y (height) coordinate. See figure 1 for a render of it in Blender. I render this model once directly from above and once directly from below. My expectation was that I would get exactly the same image (except for mirroring over the y-axis). However when I render using a very low resolution render target (25x25) the position (in pixels) of the 'T' is different when rendered from above as opposed to rendered from below. See figure 2 and 3. The pink blocks are not part of the original rendering but I've added them so you can easily count/see the differences. Figure 2: the T rendered from above Figure 3: the T rendered from below This is probably due to what I've read about pixel and texel coordinates which might be biased to the top-left as seen from the camera. Since I'm using the same 'up' vector for both of my camera's my bias only shows on the x-axis. I've tried to change the position of the camera and it's look-at by, what I thought, should be half a pixel. I've tried both shifting a single camera and shifting both cameras and while I see some effect I am not able to get a pixel-by-pixel perfect copy from both camera's. Here I initialize the camera and compute, what I believe to be, half pixel. boundsDimX and boundsDimZ is a slightly enlarged bounding box around the model which I also use as the width and height of the view volume of the orthographic camera. Matrix projection = Matrix.CreateOrthographic(boundsDimX, boundsDimZ, 0.5f, sliceHeight + 0.5f); Vector3 halfPixel = new Vector3(boundsDimX / (float)renderTarget.Width, 0, boundsDimY / (float)renderTarget.Height) * 0.5f; This is the code where I set the camera position and camera look ats // Position camera if (downwards) { float cameraHeight = bounds.Max.Y + 0.501f - (sliceHeight * i); Vector3 cameraPosition = new Vector3 ( boundsCentre.X, // possibly adjust by half a pixel? cameraHeight, boundsCentre.Z ); camera.Position = cameraPosition; camera.LookAt = new Vector3(cameraPosition.X, cameraHeight - 1.0f, cameraPosition.Z); } else { float cameraHeight = bounds.Max.Y - 0.501f - (sliceHeight * i); Vector3 cameraPosition = new Vector3 ( boundsCentre.X, cameraHeight, boundsCentre.Z ); camera.Position = cameraPosition; camera.LookAt = new Vector3(cameraPosition.X, cameraHeight + 1.0f, cameraPosition.Z); } Main Question Now you've seen all the problems and code you can guess it. My main question is. How do I align both camera's so that they each render exactly the same image (mirrored along the Y axis)? Figure 1 the original model rendered in blender

    Read the article

  • How to send raw data over a network?

    - by youllknow
    Hi everyone! I've same data stored in a byte-array. The data contains a IPv4 packet (which contains a udp-packet). I want to send these array raw over the network using C# (preferred) or C++. I don't want to use C#'s udp-client for example. Does anyone know how to perform this? Sorry for my bad English and thanks for your help in advance!!!

    Read the article

  • calculate camera up vector after glulookat()?

    - by carrots
    I'm just starting out teaching myself openGL and now adding openAL to the mix. I have some planets scattered around in 3D space and when I touch the screen, I'm assigning a sound to a random planet and then slowly and smoothly flying the "camera" over to look at it and listen to it. The animation/tweening part is working perfectly, but the openAL piece isn't quiet right. I move the camera around by doing a tiny translate() and gluLookAt() for every frame to keep things smooth (tweening the camera position and lookAt coords). The trouble seems to be with the stereo image I'm getting out of the headphones.. it seems like the left/right/up/down is mixed up sometimes after the camera rolls or spins. I am pretty sure the trouble is here: ALfloat listenerPos[]={camera->currentX,camera->currentY,camera->currentZ}; ALfloat listenerOri[]={camera->currentLookX, camera->currentLookY, camera->currentLookZ, 0.0,//Camera Up X <--- here 0.1,//Camera Up Y <--- here 0.0}//Camera Up Z <--- and here alListenerfv(AL_POSITION,listenerPos); alListenerfv(AL_ORIENTATION,listenerOri); I'm thinking I need to recompute the UP vector for the camera after each gluLookAt() to straighten out the audio positioning problem.. but after hours of googling and experimenting I'm stuck in math that suddenly got way over my head. 1) Am I right that I need to recalculate the up vector after each gluLookAt() i do? 2) If so, can someone please walk me though figuring out how to do that?

    Read the article

  • Camera Projection back Into 3D world, offset error

    - by Anthony
    I'm using XNA to simulate a robot in a 3D world and then do image analysis on what the camera sees. I have my camera looking down in front of the direction that the robot is going, and I have the robot detecting white pixels. I'm trying to take the white pixels that it finds and project them back into the 3D world so that I can see if it is actually detecting the correct pixels. I almost have it working, but there is an offset between where the white is in in the World and were I put my orange triangles (which represent what the robot things is white). /// <summary> /// Takes a bool map of and makes vertex positions based on the map. /// </summary> /// <param name="c"> The bool map</param> private void ProjectBoolMapOnGroundAnthony2(bool[,] c) { float triangleSize = 0.04f; // Point of interest in World W cordinate system. Vector3 pointOfInterest_W = Vector3.Zero; // Point of interest in Robot Cordinate system R Vector3 pointOfInterest_R = Vector3.Zero; // alpha is the angle from the robot camera to where it is looking in the center. //double alpha = Math.Atan(1.8f / 1); /// Matrix representation of the view determined by the position, target, and updirection. Matrix View = ((SimulationMain)Game).mainRobot.robotCameraView.View; /// Matrix representation of the view determined by the angle of the field of view (Pi/4), aspectRatio, nearest plane visible (1), and farthest plane visible (1200) Matrix Projection = ((SimulationMain)Game).mainRobot.robotCameraView.Projection; /// Matrix representing how the real world cordinates differ from that of the rendering by the camera. Matrix World = ((SimulationMain)Game).mainRobot.robotCameraView.World; Plane groundPlan = new Plane(Vector3.UnitZ, 0.0f); for (int x = 0; x < this.screenWidth; x++) { for (int y = 0; y < this.screenHeight; ) { if (c[x, y] == true && this.count1D < 62000) { int j = 1; Vector3 nearPlanePoint = Game.GraphicsDevice.Viewport.Unproject(new Vector3(x, y, 0), Projection, View, World); Vector3 farPlanePoint = Game.GraphicsDevice.Viewport.Unproject(new Vector3(x, y, 1), Projection, View, World); //Vector3 pointOfInterest_W = Vector3.in Ray ray = new Ray(nearPlanePoint, farPlanePoint); pointOfInterest_W = ray.Position + ray.Direction * (float) ray.Intersects(groundPlan); this.vertexArray2[this.count1D + 0].Position.X = pointOfInterest_W.X - triangleSize; this.vertexArray2[this.count1D + 0].Position.Y = pointOfInterest_W.Y - triangleSize * j; this.vertexArray2[this.count1D + 0].Position.Z = pointOfInterest_W.Z; this.vertexArray2[this.count1D + 0].Color = Color.DarkOrange; // Put another vertex a the position but +1 in the X direction triangleSize //this.vertexArray2[this.count1D + 1].Position.X = pointOnGroud.X + 3; //this.vertexArray2[this.count1D + 1].Position.Y = pointOnGroud.Y + j; this.vertexArray2[this.count1D + 1].Position.X = pointOfInterest_W.X; this.vertexArray2[this.count1D + 1].Position.Y = pointOfInterest_W.Y + triangleSize * j; this.vertexArray2[this.count1D + 1].Position.Z = pointOfInterest_W.Z; this.vertexArray2[this.count1D + 1].Color = Color.Red; // Put another vertex a the position but +1 in the X direction //this.vertexArray2[this.count1D + 0].Position.X = pointOnGroud.X; //this.vertexArray2[this.count1D + 0].Position.Y = pointOnGroud.Y + 3 + j; this.vertexArray2[this.count1D + 2].Position.X = pointOfInterest_W.X + triangleSize; this.vertexArray2[this.count1D + 2].Position.Y = pointOfInterest_W.Y - triangleSize * j; this.vertexArray2[this.count1D + 2].Position.Z = pointOfInterest_W.Z; this.vertexArray2[this.count1D + 2].Color = Color.Orange; this.count1D += 3; y += j; } else { y++; } } } } The world is a grass texture with lines on it. The world plane is normal at (0,0,1). Any ideas on why there is an offset? Any Ideas? Thanks for the help, Anthony G.

    Read the article

  • How to stop camera from rotating in 2.5d platformer

    - by Artem Suchkov
    I'm stuck with a problem: I can not make my camera stop rotating after character. What I already have tried: using empty game object with rigid body and locked rotation and make it parent of camera, while player being the parent of object. Also, I've tried using few scripts from web, that did not help. Right now I'm bad with using JS in Unity (can handle JS on website, but I dont know how to integrate it for now) and practicing the basics, making easy 2.5d platformer with basic features, so I can not write code for now.

    Read the article

  • Calculating 3D camera positions from a video

    - by Geotarget
    I need to calculate the 3D camera position and rotation for each frame in a given video. This is typically used for motion-tracking, and to insert 3D objects into a video. I'm currently using VideoTrace to calculate this for me, and I'm getting the data exported as a 3DS Maxscript file. However when I try to use the 3D camera rotations, I'm getting strange errors in my 3D calculations, as if there is an error with the 3x3 rotation matrices. Can you spot any error with the data itself? Or is it my other calculations that are erroneous? frame 1 rotation=(matrix3[-0.011938, 0.756018, -0.654442][-0.382040, -0.608284, -0.695727][-0.924068, 0.241718, 0.296091][0, 0, 0]).rotationpart position=[-0.767177, 0.308723, -0.232722] fov=57.352135 frame 2 rotation=(matrix3[-0.460922, -0.726580, -0.509541][-0.200163, 0.644491, -0.737947][ 0.864572, -0.238145, -0.442495][0, 0, 0]).rotationpart position=[-0.856630, 0.198654, -0.243853] fov=57.352135

    Read the article

  • How To Smoothly Animate From One Camera Position To Another

    - by www.Sillitoy.com
    The Question is basically self explanatory. I have a scene with many cameras and I'd like to smoothly switch from one to another. I am not looking for a cross fade effect but more to a camera moving and rotating the view in order to reach the next camera point of view and so on. To this end I have tried the following code: firstCamera.transform.position.x = Mathf.Lerp(firstCamera.transform.position.x, nextCamer.transform.position.x,Time.deltaTime*smooth); firstCamera.transform.position.y = Mathf.Lerp(firstCamera.transform.position.y, nextCamera.transform.position.y,Time.deltaTime*smooth); firstCamera.transform.position.z = Mathf.Lerp(firstCamera.transform.position.z, nextCamera.transform.position.z,Time.deltaTime*smooth); firstCamera.transform.rotation.x = Mathf.Lerp(firstCamera.transform.rotation.x, nextCamera.transform.rotation.x,Time.deltaTime*smooth); firstCamera.transform.rotation.z = Mathf.Lerp(firstCamera.transform.rotation.z, nextCamera.transform.rotation.z,Time.deltaTime*smooth); firstCamera.transform.rotation.y = Mathf.Lerp(firstCamera.transform.rotation.y, nextCamera.transform.rotation.y,Time.deltaTime*smooth); But the result is actually not that good.

    Read the article

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