Search Results

Search found 1061 results on 43 pages for 'movement'.

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

  • Extrapolation breaks collision detection

    - by user22241
    Before applying extrapolation to my sprite's movement, my collision worked perfectly. However, after applying extrapolation to my sprite's movement (to smooth things out), the collision no longer works. This is how things worked before extrapolation: However, after I implement my extrapolation, the collision routine breaks. I am assuming this is because it is acting upon the new coordinate that has been produced by the extrapolation routine (which is situated in my render call ). After I apply my extrapolation How to correct this behaviour? I've tried puting an extra collision check just after extrapolation - this does seem to clear up a lot of the problems but I've ruled this out because putting logic into my rendering is out of the question. I've also tried making a copy of the spritesX position, extrapolating that and drawing using that rather than the original, thus leaving the original intact for the logic to pick up on - this seems a better option, but it still produces some weird effects when colliding with walls. I'm pretty sure this also isn't the correct way to deal with this. I've found a couple of similar questions on here but the answers haven't helped me. This is my extrapolation code: public void onDrawFrame(GL10 gl) { //Set/Re-set loop back to 0 to start counting again loops=0; while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){ SceneManager.getInstance().getCurrentScene().updateLogic(); nextGameTick+=skipTicks; timeCorrection += (1000d/ticksPerSecond) % 1; nextGameTick+=timeCorrection; timeCorrection %=1; loops++; tics++; } extrapolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks; render(extrapolation); } Applying extrapolation render(float extrapolation){ //This example shows extrapolation for X axis only. Y position (spriteScreenY is assumed to be valid) extrapolatedPosX = spriteGridX+(SpriteXVelocity*dt)*extrapolation; spriteScreenPosX = extrapolationPosX * screenWidth; drawSprite(spriteScreenX, spriteScreenY); } Edit As I mentioned above, I have tried making a copy of the sprite's coordinates specifically to draw with.... this has it's own problems. Firstly, regardless of the copying, when the sprite is moving, it's super-smooth, when it stops, it's wobbling slightly left/right - as it's still extrapolating it's position based on the time. Is this normal behavior and can we 'turn it off' when the sprite stops? I've tried having flags for left / right and only extrapolating if either of these is enabled. I've also tried copying the last and current positions to see if there is any difference. However, as far as collision goes, these don't help. If the user is pressing say, the right button and the sprite is moving right, when it hits a wall, if the user continues to hold the right button down, the sprite will keep animating to the right, while being stopped by the wall (therefore not actually moving), however because the right flag is still set and also because the collision routine is constantly moving the sprite out of the wall, it still appear to the code (not the player) that the sprite is still moving, and therefore extrapolation continues. So what the player would see, is the sprite 'static' (yes, it's animating, but it's not actually moving across the screen), and every now and then it shakes violently as the extrapolation attempts to do it's thing....... Hope this help

    Read the article

  • XNA 2D Board game - trouble with the cursor

    - by Adorjan
    I just have started making a simple 2D board game using XNA, but I got stuck at the movement of the cursor. This is my problem: I have a 10x10 table on with I should use a cursor to navigate. I simply made that table with the spriteBatch.Draw() function because I couldn't do it on another way. So here is what I did with the cursor: public override void LoadContent() { ... mutato.Position = new Vector2(X, Y); //X=103, Y=107; mutato.Sebesseg = 45; ... mutato.Initialize(content.Load<Texture2D>("cursor"),mutato.Position,mutato.Sebesseg); ... } public override void HandleInput(InputState input) { if (input == null) throw new ArgumentNullException("input"); // Look up inputs for the active player profile. int playerIndex = (int)ControllingPlayer.Value; KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex]; if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected) { ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer); } else { // Otherwise move the player position. if (keyboardState.IsKeyDown(Keys.Down)) { Y = (int)mutato.Position.Y + mutato.Move; } if (keyboardState.IsKeyDown(Keys.Up)) { Y = (int)mutato.Position.Y - mutato.Move; } if (keyboardState.IsKeyDown(Keys.Left)) { X = (int)mutato.Position.X - mutato.Move; } if (keyboardState.IsKeyDown(Keys.Right)) { X = (int)mutato.Position.X + mutato.Move; } } } public override void Draw(GameTime gameTime) { mutato.Draw(spriteBatch); } Here's the cursor's (mutato) class: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Battleship.Components { class Cursor { public Texture2D Cursortexture; public Vector2 Position; public int Move; public void Initialize(Texture2D texture, Vector2 position,int move) { Cursortexture = texture; Position = position; Move = move; } public void Update() { } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(Cursortexture, Position, Color.White); } } } And here is a part of the InputState class where I think I should change something: public bool IsNewKeyPress(Keys key, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { if (controllingPlayer.HasValue) { // Read input from the specified player. playerIndex = controllingPlayer.Value; int i = (int)playerIndex; return (CurrentKeyboardStates[i].IsKeyDown(key) && LastKeyboardStates[i].IsKeyUp(key)); } } If I leave the movement operation like this it doesn't have any sense: X = (int)mutato.Position.X - mutato.Move; However if I modify it to this: X = (int)mutato.Position.X--; it moves smoothly. Instead of this I need to move the cursor by fields (45 pixels), but I don't have any idea how to manage it.

    Read the article

  • Group arrival steering

    - by ltjax
    I've got group movement implemented pretty much like this: http://www.red3d.com/cwr/steer/CrowdPath.html Basically, that's combining path following and separation. It works nicely as long as units are in transit, but arrival does not work very well at all. Right now, units just cease to use the path following component once the "exit" the path, i.e. when their closest point on the path is on or past the end. This leads to those units bumping into each other and also overshooting the point the player clicked. Ideally, I'd have the units arrive scattered around the finish point (and reasonable close to each other), not all clumped up past the finish line. I'd imagine that some kind of arrival steering might work here, but based on other units and a "fuzzy" classification of the end of the path. Is there any proven way to do this?

    Read the article

  • Interpolating between two networked states?

    - by Vaughan Hilts
    I have many entities on the client side that are simulated (their velocities are added to their positions on a per frame basis) and I let them dead reckon themselves. They send updates about where they were last seen and their velocity changes. This works great and other players see this work find. However, after a while these players begin to desync after some time. This is because of latency. I'd like to know how I can interpolate between states so they appear to be in the correct position. I know where the player was LAST seen and their current velocity but interpolating to the last seen state causes the player to actually move -backwards-. I could not use velocity at all for other clients and simply 'lerp' them towards the appropriate direction but I feel this would cause jaggy movement. What are the alternatives?

    Read the article

  • Is it safe to set FPS rate to a constant?

    - by Ozan
    I learned from game class that in update function, every movements must be time dependent for the sake of linearity in movement. We made a simple game. Every move like going left, right or jump is written time dependent. But, in some other computers, our game is worked very differently. For example, our character jumps higher than it should be. I guess this is because each computer has different FPS rate according to its specification. My question is that what should we do to make this game work in same way in every computer? Setting FPS rate to a constant is a solution?

    Read the article

  • What is a normalized Vector?

    - by draiden
    Can someone explain the following code? I need to learn what each part means so I can turn it into enemy movement in a space shoot-em-up Vec2d playerPos; Vec2d direction; // always normalized float velocity; I get the above is naming two 2d Vector objects, and creating a variable called velocity. I'm not sure what the normalized comment is about, though. update() { direction = normalize(playerPos - enemyPos); playerPos = playerPos + direction * velocity; }

    Read the article

  • Cocos2d - smooth sprite movement in tile map RPG

    - by Lendo92
    I've been working on a 2-D Gameboy style RPG for a while now, and the game logic is mostly all done so I'm starting to try to make things look good. One thing I've noticed is that the walking movement / screen movement is a little bit choppy. Technically, it should work fine, but either it seems to be having some quirks, either due to taking up a lot of processing power or just timing inconsistencies between moving the screen and moving the sprite. To move the sprite, once I know where I want to move it, I call: tempPos.y += 3*theHKMap.tileSize.width/5; id actionMove = [CCMoveTo actionWithDuration:0.1 position:tempPos]; id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(orientOneMove)]; [guy runAction:[CCSequence actions:actionMove, actionMoveDone, nil]]; [self setCenterOfScreen:position]; Then, in orientOneMove, I call: [self.guy setTexture:[[CCTextureCache sharedTextureCache] addImage:@"guysprite07.png"]]; //the walking picture-I change texture back at the end of the movement id actionMove = [CCMoveTo actionWithDuration:0.15 position:self.tempLocation2]; id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(toggleTouchEnabled)]; [guy runAction:[CCSequence actions:actionMove, actionMoveDone, nil]]; The code for the concurrently running setCenterOfScreen:position method is: id actionMove = [CCMoveTo actionWithDuration:0.25 position:difference]; [self runAction: [CCSequence actions:actionMove, nil, nil]]; So the setCenterOfScreen moves the camera in one clean move while the guy moving is chopped into two actions to animate it (which I believe might be inefficient.) It's hard to tell what is making the movement not perfectly clean from looking at it, but essentially the guy isn't always perfectly in the center of the screen -- during movement, he's often times a pixel or two off for an instant. Any ideas/ solutions?

    Read the article

  • Vim style cursor movement for Notepad++

    - by funseiki
    I was just wondering if there was a way to get "vim" style cursor movement (i.e. 'hkjl' movement). After spending much time with vim, I have gotten used to not having to life my hands off the keyboard to move around a text document (going to the arrow keys is also too disruptive :p). Moving back to vim is always an option, but if there was a way to get this feature on notepad++. I have already spent some time in setting up macros and plugins to get my notepad++ environment working the way I want it to. Any help on this matter would be much appreciated.

    Read the article

  • Collision detection with multiple polygons simultaneously

    - by Craig Innes
    I've written a collision system which detects/resolves collisions between a rectangular player and a convex polygon world using the Separating Axis Theorem. This scheme works fine when the player is colliding with a single polygon, but when I try to create a level made up of combinations of these shapes, the player gets "stuck" between shapes when trying to move from one polygon to the other. The reason for this seems to be that collisions are detected after the player has been pushed through the shape by its movement or gravity. When the system resolves the collision, it resolves them in an order that doesn't make sense (for example, when the player is moving from one flat rectangle to another, gravity pushes them below the ground, but the collision with the left hand side of the second block is resolved before the collision with the top of the block, meaning the player is pushed back left before being pushed back up). Other similar posts have resolved this problem by having a strict rule on which axes to resolve first. For example, always resolve the collision on the y axis, then if the object is still colliding with things, resolve on the x axis. This solution only works in the case of a completely axis oriented box world, and doesn't solve the problem if the player is stuck moving along a series of angled shapes or sliding down a wall. Does any one have any ideas of how I could alter my collision system to prevent these situations from happening?

    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

  • How to move an UIView along a curved CGPath according to user dragging the view

    - by Felipe Cypriano
    I'm trying to build a interface that the user can move his finger around the screen an a list of images moves along a path. The idea is that the images center nevers leaves de path. Most of the things I found was about how to animate using CGPath and not about actually using the path as the track to a user movement. I need to objects to be tracked on the path even if the user isn't moving his fingers over the path. For example (image bellow), if the object is at the beginning of the path and the user touches anywhere on the screen and moves his fingers from left to right I need that the object moves from left to right but following the path, that is, going up as it goes to the right towards the path's end. This is the path I've draw, imagine that I'll have a view (any image) that the user can touch and drag it along the path, there's no need to move the finger exactly over the path. If the user move from left to right the image should move from left to right but going up if need following the path. This is how I'm creating the path: CGPoint endPointUp = CGPointMake(315, 124); CGPoint endPointDown = CGPointMake(0, 403); CGPoint controlPoint1 = CGPointMake(133, 187); CGPoint controlPoint2 = CGPointMake(174, 318); CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, endPointUp.x, endPointUp.y); CGPathAddCurveToPoint(path, NULL, controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, endPointDown.x, endPointDown.y); Any idead how can I achieve this?

    Read the article

  • Effective way to check if an Entity/Player enters a region/trigger

    - by Chris
    I was wondering how multiplayer games detect if you enter a special region. Let's assume there is a huge map that is so big that simply checking it would become a huge performance issue. I've seen bukkit (a modding API for Minecraft servers) firing an Event on every single move. I don't think that larger games do the same because even if you have only a few coordinates you are interested in, you have to loop through a few trigger zone to see if the player is inside your region - for every player. This seems like an extremely CPU-intense operation to me even though I've never developed something like that. Is there a special algorithm that is used by larger games to accomplish this? The only thing I could imagine is to split up the world into multiple parts and to register the event not on the movement itself but on all the parts that are covered by your area and only check for areas that are registered in the current part. And another thing I would like to know: How could you detect when someone must have entered a trigger but you never saw him directly in it since his client only sent you an move packet shortly before entering and after leaving the trigger area. Drawing a line and calculate all colliding parts seems rather CPU intensive if you have to perform it every time.

    Read the article

  • How to build a "traffic AI"?

    - by Lunikon
    A project I am working on right now features a lot of "traffic" in the sense of cars moving along roads, aircraft moving aroun an apron etc. As of now the available paths are precalculated, so nodes are generated automatically for crossings which themselves are interconnected by edges. When a character/agent spawns into the world it starts at some node and finds a path to a target node by means of a simply A* algorithm. The agent follows the path and ultimately reaches its destination. No problem so far. Now I need to enable the agents to avoid collisions and to handle complex traffic situations. Since I'm new to the field of AI I looked up several papers/articles on steering behavior but found them to be too low-level. My problem consists less of the actual collision avoidance (which is rather simple in this case because the agents follow strictly defined paths) but of situations like one agent leaving a dead-end while another one wants to enter exactly the same one. Or two agents meeting at a bottleneck which only allows one agent to pass at a time but both need to pass it (according to the optimal route found before) and they need to find a way to let the other one pass first. So basically the main aspect of the problem would be predicting traffic movement to avoid dead-locks. Difficult to describe, but I guess you get what I mean. Do you have any recommendations for me on where to start looking? Any papers, sample projects or similar things that could get me started? I appreciate your help!

    Read the article

  • Finding the shorter turning direction towards a target

    - by A.B.
    I'm trying to implement a type of movement where the object gradually faces the target. The problem I've run into is figuring out which turning direction is faster. The following code works until the object's orientation crosses the -PI or PI threshold, at which point it will start turning into the opposite direction void moveToPoint(sf::Vector2f destination) { if (destination == position) return; auto distance = distanceBetweenPoints(position, destination); auto direction = angleBetweenPoints(position, destination); /// Decides whether incrementing or decrementing orientation is faster /// the next line is the problem if (atan2(sin(direction - rotation), cos(direction - rotation)) > 0 ) { /// Increment rotation rotation += rotation_speed; } else { /// Decrement rotation rotation -= rotation_speed; } if (distance < movement_speed) { position = destination; } else { position.x = position.x + movement_speed*cos(rotation); position.y = position.y + movement_speed*sin(rotation); } updateGraphics(); } 'rotation' and 'rotation_speed' are implemented as custom data type for radians which cannot have values lower than -PI and greater than PI. Any excess or deficit "wraps around". For example, -3.2 becomes ~3.08.

    Read the article

  • How to prioritize related game entity components?

    - by Paul Manta
    I want to make a game where you have to run over a bunch of zombies with your car. When moving around, the zombies have a few things to take into consideration: When there's no player around they might just roam about randomly. And even when some other component dictates a specific direction, they should wobble to the left and right randomly (like drunk people). This implies a small, random, deviation in their movement. They should avoid static obstacles. When they see they are headed towards a wall, they should reorient themselves. They should avoid the car. They should try to predict where the car will be based on its velocity and try to move out of the way. When they can, they should try to get near the player. All these types of decisions they have to do seem like they should be implemented in different components. But how should I manage them? How can I give different components different weights that reflect the importance of each decision (in a given situation)? I would need some other component that acts as a manager, but do you have any tips on how I should implement it? Or maybe there's a better solution?...

    Read the article

  • rigidbody2d.Addforce( ) behaves wieirdly unity 4.3 [on hold]

    - by Lilz Votca Love
    So guys ive edited the question and here is what my problem is i have a player which has a rigidbody2d attached to it.my player is able to doublejump in the air nicely and stick to walls when colliding with them and slowly slides to the ground.All movement is handle through physics and no transform manipulations.here i did something similar to this in the FixedUpdate of my player. void FixedUpdate() { if(wall && Input.GetButtonDown("Jump")) { if(facingright)//player is facing the left side of the wall { rigidbody2D.Addforce(new vector2(-1f,2f)*jumpforce); /*Now the player should jump backwards following this directional vector and should follow a smooth curve which in this part works well*/ } else { rigidbody2D.Addforce(new vector2(1f,2f)*jumpforce); /*Now this is where everything gets complicated as you should have noticed this is the same directional vector only the opposite x axis value and the same amount of force is used but it behaves like the red curve in the picture below*/ } } } bad behaviour and vector in red .I tested the same thing(both addforce methods) for a simple jump and they exactly behave like mentionned above in the picture.so here is my problem.Jumping diagonally forward with rigidbody2d.addforce() do not have the same impact,do not follow the same curve as jumping the opposite direction with the same exact amount of force.if i could fix this or get past this i could implement a walljump system like a ninja jumping in zigzag between two opposite wall to climb them.Any ideas or alternatives?

    Read the article

  • How to build a "traffic AI"?

    - by Lunikon
    A project I am working on right now features a lot of "traffic" in the sense of cars moving along roads, aircraft moving aroun an apron etc. As of now the available paths are precalculated, so nodes are generated automatically for crossings which themselves are interconnected by edges. When a character/agent spawns into the world it starts at some node and finds a path to a target node by means of a simply A* algorithm. The agent follows the path and ultimately reaches its destination. No problem so far. Now I need to enable the agents to avoid collisions and to handle complex traffic situations. Since I'm new to the field of AI I looked up several papers/articles on steering behavior but found them to be too low-level. My problem consists less of the actual collision avoidance (which is rather simple in this case because the agents follow strictly defined paths) but of situations like one agent leaving a dead-end while another one wants to enter exactly the same one. Or two agents meeting at a bottleneck which only allows one agent to pass at a time but both need to pass it (according to the optimal route found before) and they need to find a way to let the other one pass first. So basically the main aspect of the problem would be predicting traffic movement to avoid dead-locks. Difficult to describe, but I guess you get what I mean. Do you have any recommendations for me on where to start looking? Any papers, sample projects or similar things that could get me started? I appreciate your help!

    Read the article

  • Scaling sprite velocity / co-ordinatesin Android

    - by user22241
    I'm trying to find the answer to a question that I've had for a long time, but am having trouble finding it! I hope someone can help :-) I'm trying to find information on how to scale sprite velocity / movement / co-ordinates. What I mean by this is how do I get a sprite to move at the same speed relative to the screen size / DPI so that it takes the same amount of real-time to get from one side of the screen to the other? All of the posts pertaining to sprite scaling that I can find on the various forums relate to the size of the sprite, but this part of it I'm OK with so far, it's just that when I move a sprite, it kind of gets there at different speed depending on the dpi / resolution of the device. I hope I'm making sense. This is the code I have so far, instead of using explicit amounts, like 1, I'm using something like the following: platSpeedFloat= (1 * (dpi/160)); //Use '1' so on an MDPI screen, the sprite will move by 1 physical pixel Then basically what I'm doing is something like this: (all varialble previously declared) platSpeedSave+=platSpeedFloat; //Add the platSpeedFloat value to the current platSpeedSave value platSpeed=(int) platSpeedSave; //Cast to int so it can be checked in the following statement if (platSpeed==platSpeedSave) //Check the casted int value to float value stored previoiusly {floorY=floorY-platSpeed; //If they match then change the Y value platSpeedSave=0;} //Reset Would be grateful if someone could assists - hope I'm making sense. The above doesn't seems to work the sprite moves 'faster' on lower DPI screens. Thanks

    Read the article

  • Interpolation using a sprite's previous frame and current frame

    - by user22241
    Overview I'm currently using a method which has been pointed out to me is extrapolation rather than interolation. As a result, I'm also now looking into the possibility of using another method which is based on a sprite's position at it's last (rendered) frame and it's current one. Assuming an interpolation value of 0.5 this is, (visually), how I understand it should affect my sprite's position.... This is how I'm obtaining an inerpolation value: public void onDrawFrame(GL10 gl) { // Set/re-set loop back to 0 to start counting again loops=0; while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip) { SceneManager.getInstance().getCurrentScene().updateLogic(); nextGameTick += skipTicks; timeCorrection += (1000d / ticksPerSecond) % 1; nextGameTick += timeCorrection; timeCorrection %= 1; loops++; tics++; } interpolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks; render(interpolation); } I am then applying it like so (in my rendering call): render(float interpolation) { spriteScreenX = (spriteScreenX - spritePreviousX) * interpolation + spritePreviousX; spritePreviousX = spriteScreenX; // update and store this for next time } Results This unfortunately does nothing to smooth the movement of my sprite. It's pretty much the same as without the interpolation code. I can't get my head around how this is supposed to work and I honestly can't find any decent resources which explain this in any detail. My understanding of extrapolation is that when we arrive at the rendering call, we calculate the time between the last update call and the render call, and then adjust the sprite's position to reflect this time (moving the sprite forward) - And yet, this (Interpolation) is moving the sprite back, so how can this produce smooth results? Any advise on this would be very much appreciated. Edit I've implemented the code from OriginalDaemon's answer like so: @Override public void onDrawFrame(GL10 gl) { newTime = System.currentTimeMillis()*0.001; frameTime = newTime - currentTime; if ( frameTime > (dt*25)) frameTime = (dt*25); currentTime = newTime; accumulator += frameTime; while ( accumulator >= dt ) { SceneManager.getInstance().getCurrentScene().updateLogic(); previousState = currentState; t += dt; accumulator -= dt; } interpolation = (float) (accumulator / dt); render(); } Interpolation values are now being produced between 0 and 1 as expected (similar to how they were in my original loop) - however, the results are the same as my original loop (my original loop allowed frames to skip if they took too long to draw which I think this loop is also doing). I appear to have made a mistake in my previous logging, it is logging as I would expect it to (interpolated position does appear to be inbetween the previous and current positions) - however, the sprites are most definitely choppy when the render() skipping happens.

    Read the article

  • returning correct multiTouch id

    - by Max
    I've spent countless hours on reading tutorials and looking at every question related to multiTouch from here and Stackoverflow. But I just cannot figure out how to do this correctly. I use a loop to get my pointerId, I dont see alot of people doing this but its the only way I've managed to get it somewhat working. I have two joysticks on my screen, one for moving and one for controlling my sprites rotation and the angle he shoots, like in Monster Shooter. Both these work fine. My problem is that when I Move my sprite at the same time as Im shooting, my touchingPoint for my movement is set to the touchingPoint of my shooting, since the x and y is higher on the touchingPoint of my shooting (moving-stick on left side of screen, shooting-stick on right side), my sprite speeds up, this creates an unwanted change in speed for my sprite. I will post my entire onTouch method here with some variable-changes to make it more understandable. Since I do not know where Im going wrong. public void update(MotionEvent event) { if (event == null && lastEvent == null) { return; } else if (event == null && lastEvent != null) { event = lastEvent; } else { lastEvent = event; } int pointerCount = event.getPointerCount(); for (int i = 0; i < pointerCount; i++) { int x = (int) event.getX(i); int y = (int) event.getY(i); int id = event.getPointerId(i); int action = event.getActionMasked(); int actionIndex = event.getActionIndex(); String actionString; switch (action) { case MotionEvent.ACTION_DOWN: actionString = "DOWN"; break; case MotionEvent.ACTION_UP: shooting=false; // when shooting is true, it shoots dragging=false; // when dragging is true, it moves actionString = "UP"; break; case MotionEvent.ACTION_POINTER_DOWN: actionString = "PNTR DOWN"; break; case MotionEvent.ACTION_POINTER_UP: shooting=false; dragging=false; actionString = "PNTR UP"; break; case MotionEvent.ACTION_CANCEL: shooting=false; dragging=false; actionString = "CANCEL"; break; case MotionEvent.ACTION_MOVE: try{ if((int) event.getX(id) > 0 && (int) event.getX(id) < touchingBox && (int) event.getY(id) > touchingBox && (int) event.getY(id) < view.getHeight()){ movingPoint.x = (int) event.getX(id); movingPoint.y = (int) event.getY(id); dragging = true; } else if((int) event.getX(id) > touchingBox && (int) event.getX(id) < view.getWidth() && (int) event.getY(id) > touchingBox && (int) event.getY(id) < view.getHeight()){ shootingPoint.x = (int) event.getX(id); shootingPoint.y = (int) event.getY(id); shooting=true; }else{ shooting=false; dragging=false; } }catch(Exception e){ } actionString = "MOVE"; break; default: actionString = ""; } Wouldnt post this much code if I wasnt at an absolute loss of what I'm doing wrong. I simply can not get a good understanding of how multiTouching works. basicly movingPoint changes for both my first and second finger. I bind it to a box, but aslong as I hold one finger within this box, it changes its value based on where my second finger touches. It moves in the right direction and nothing gives an error, the problem is the speed-change, its almost like it adds up the two touchingPoints.

    Read the article

  • Turning on collision crashes game

    - by MomentumGaming
    I am getting a null pointer excecption to both my sprite and level. I am working on my mob class, and when I try to move him and the move function is called, the game crashes after checking collision with a null pointer excecption. Taking out the one line that actually checks if the tile located in front of it fixes the problem. Also, if i keep collision ON but don't move the position of the mob (the spider) the game works fine. I will have collision, and the spider appears on the screen, only problem is, getting it to move causes this nasty error that i just can't fix. true Exception in thread "Display" java.lang.NullPointerException at com.apcompsci.game.entity.mob.Mob.collision(Mob.java:67) at com.apcompsci.game.entity.mob.Mob.move(Mob.java:38) at com.apcompsci.game.entity.mob.spider.update(spider.java:58) at com.apcompsci.game.level.Level.update(Level.java:55) at com.apcompsci.game.Game.update(Game.java:128) at com.apcompsci.game.Game.run(Game.java:106) at java.lang.Thread.run(Unknown Source) Here is my renderMob mehtod: public void renderMob(int xp,int yp,Sprite sprite,int flip) { xp -= xOffset; yp-=yOffset; for(int y = 0; y<32; y++) { int ya = y + yp; int ys = y; if(flip == 2||flip == 3)ys = 31-y; for(int x = 0; x<32; x++) { int xa = x + xp; int xs = x; if(flip == 1||flip == 3)xs = 31-x; if(xa < -32 || xa >=width || ya<0||ya>=height) break; if(xa<0) xa =0; int col = sprite.pixels[xs+ys*32]; if(col!= 0x000000) pixels[xa+ya*width] = col; } } } My spider class which determines the sprite and where I control movement, also rendering the spider onto the screen, when I increment ya to move the sprite, I get the crash, but without ya++, it runs flawlessly with a spider sprite on screen: package com.apcompsci.game.entity.mob; import com.apcompsci.game.entity.mob.Mob.Direction; import com.apcompsci.game.graphics.Screen; import com.apcompsci.game.graphics.Sprite; import com.apcompsci.game.level.Level; public class spider extends Mob{ Direction dir; private Sprite sprite; private boolean walking; public spider(int x, int y) { this.x = x <<4; this.y = y <<4; sprite = sprite.spider_forward; } public void update() { int xa = 0, ya = 0; ya++; if(ya<0) { sprite = sprite.spider_forward; dir = Direction.UP; } if(ya>0) { sprite = sprite.spider_back; dir = Direction.DOWN; } if(xa<0) { sprite = sprite.spider_side; dir = Direction.LEFT; } if(xa>0) { sprite = sprite.spider_side; dir = Direction.LEFT; } if(xa!= 0 || ya!= 0) { System.out.println("true"); move(xa,ya); walking = true; } else{ walking = false; } } public void render(Screen screen) { screen.renderMob(x, y, sprite, 0); } } This is th mob class that contains the move() method that is called in the spider class above. This move method calls the collision method. tile and sprite comes up null in the debugger: package com.apcompsci.game.entity.mob; import java.util.ArrayList; import java.util.List; import com.apcompsci.game.entity.Entity; import com.apcompsci.game.entity.projectile.DemiGodProjectile; import com.apcompsci.game.entity.projectile.Projectile; import com.apcompsci.game.graphics.Sprite; public class Mob extends Entity{ protected Sprite sprite; protected boolean moving = false; protected enum Direction { UP,DOWN,LEFT,RIGHT } protected Direction dir; public void move(int xa,int ya) { if(xa != 0 && ya != 0) { move(xa,0); move(0,ya); return; } if(xa>0) dir = Direction.RIGHT; if(xa<0) dir = Direction.LEFT; if(ya>0)dir = Direction.DOWN; if(ya<0)dir = Direction.UP; if(!collision(xa,ya)){ x+= xa; y+=ya; } } public void update() { } public void shoot(int x, int y, double dir) { //dir = Math.toDegrees(dir); Projectile p = new DemiGodProjectile(x, y,dir); level.addProjectile(p); } public boolean collision(int xa,int ya) { boolean solid = false; for(int c = 0; c<4; c++) { int xt = ((x+xa) + c % 2 * 14 - 8 )/16; int yt = ((y+ya) + c / 2 * 12 +3 )/16; if(level.getTile(xt, yt).solid()) solid = true; } return solid; } public void render() { } } Finally, here is the method in which i call the add() method for the spider to add it to the level: protected void loadLevel(String path) { try{ BufferedImage image = ImageIO.read(SpawnLevel.class.getResource(path)); int w = width =image.getWidth(); int h = height = image.getHeight(); tiles = new int[w*h]; image.getRGB(0, 0, w,h, tiles,0, w); } catch(IOException e){ e.printStackTrace(); System.out.println("Exception! Could not load level file!"); } add(new spider(20,45)); } I don't think i need to include the level class but just in case, I have provided a gistHub link for better context. It contains all of the full classes listed above , plus my entity class and maybe another. Thanks for the help if you decide to do so, much appreciated! Also, please tell me if i'm in the wrong section of stackeoverflow, i figured that since this is the gamign section that it belonged but debugging code normally goes into the general section.

    Read the article

  • Visual Python - Visualize graphs relating to a movement

    - by Francisco P.
    Hello, everyone! I'm working with visual python on a project where I need to simulate a physical movement. I'd like to present, in a different window than the one the actual, 3D sim is running, two graphs, both related to the movement: How the velocity and angular velocity progress over time. How the movement and rotation progress over time. All these vars are refreshed once per cycle (inside a while(true)) How can I accomplish this? Thank you for your time!

    Read the article

  • Real-time Multiplayer Movement - Flash ActionScript 3 (AS3) - Flash Media Server

    - by Wild Phoenix
    Dear All, I am creating a simple game, where I would like more than one player to be able to connect and play. With regards to a single player game, I am more than comfortable with the coding. I cannot seem to figure out how to connect up more than one player and update their screens when the each player moves. So far I have the players connecting, but I still need to be able update the SharedObject when a player moves, then push it out to the other players. I have searched high and low for a good tutorial / source code to review. Code So Far A tutorial i found so far listened for a click as it was a mouse based movement, then this told the SHaredObject to tell the client (and the others) to update that clients movement. However all of my movement is listend and acted on in the playership class.

    Read the article

  • openGL ES - change the render mode from RENDERMODE_WHEN_DIRTY to RENDERMODE_CONTINUOUSLY on touch

    - by Sid
    i want to change the rendermode from RENDERMODE_WHEN_DIRTY to RENDERMODE_CONTINUOUSLY when i touch the screen. WHAT i Need : Initially the object should be stationary. after touching the screen, it should move automatically. The motion of my object is a projectile motion ans it is working fine. what i get : Force close and a NULL pointer exception. My code : public class BallThrowGLSurfaceView extends GLSurfaceView{ MyRender _renderObj; Context context; GLSurfaceView glView; public BallThrowGLSurfaceView(Context context) { super(context); // TODO Auto-generated constructor stub _renderObj = new MyRender(context); this.setRenderer(_renderObj); this.setRenderMode(RENDERMODE_WHEN_DIRTY); this.requestFocus(); this.setFocusableInTouchMode(true); glView = new GLSurfaceView(context.getApplicationContext()); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub if (event != null) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (_renderObj != null) { Log.i("renderObj", _renderObj + "lll"); // Ensure we call switchMode() on the OpenGL thread. // queueEvent() is a method of GLSurfaceView that will do this for us. queueEvent(new Runnable() { public void run() { glView.setRenderMode(RENDERMODE_CONTINUOUSLY); } }); return true; } } } return super.onTouchEvent(event); } } PS : i know that i am making some silly mistakes in this, but cannot figure out what it really is.

    Read the article

  • How to move a sprite automatically using a physicsHandler in Andengine?

    - by shailenTJ
    I use a DigitalOnScreenControl (knob with a four-directional arrow control) to move the entity and the entity which is bound to a physicsHandler. physicsHandler.setEntity(sprite); sprite.registerUpdateHandler(physicsHandler); From the DigitalOnScreenControl, I know which direction I want my sprite to move. Inside its overridden onControlChange function, I call a function animateSprite that checks which direction I chose. Based on the direction, I animate my sprite differently. PROBLEM: I want to automatically move the sprite to a specific location on the scene, say at coordinates (207, 305). My sprite is at (100, 305, which means it has to move down by 107 pixels. How do I tell the physicsHandler to move the sprite down by 107 pixels? My animateSprite method will take care of animating the sprite's downward motion. Thank you for your input!

    Read the article

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