Search Results

Search found 533 results on 22 pages for 'velocity'.

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

  • Resolving bounding box collision detection

    - by ndg
    I'm working on a simple collision detection and resolution method for a 2d tile-based bounding box system. Collision appears to work correctly, but I'm having issues with resolving a collision after it has happened. Essentially what I'm attempting to do is very similar to this approach. The problem I'm experiencing is that because objects can be traveling with both horizontal and vertical velocity, my resolution code causes the object to jump incorrectly. I've drawn the following annotation to explain my issue. In this example, because my object has both horizontal and vertical velocity, my object (which is heading upwards and collides with the bottom of a tile) has it's position altered twice: To correctly adjust it's vertical position to be beneath the tile. To incorrectly adjust it's horizontal position to be to the left of the tile. Below is my collision/resolution code in full: function intersects(x1, y1, w1, h1, x2, y2, w2, h2) { w2 += x2; w1 += x1; if (x2 > w1 || x1 > w2) return false; h2 += y2; h1 += y1; if (y2 > h1 || y1 > h2) return false; return true; } for(var y = 0; y < this.game.level.tiles.length; y++) { for(var x = 0; x < this.game.level.tiles[y].length; x++) { var tile = this.game.level.getTile(x, y); if(tile) { if( this.velocity.x > 0 && intersects(this.position.x+dx+this.size.w, this.position.y+dy, 1, this.size.h, x*tileSize, y*tileSize, tileSize, tileSize) ) { this.position.x = ((x*tileSize)-this.size.w); hitSomething = true; break; } else if( this.velocity.x < 0 && intersects(this.position.x+dx, this.position.y+dy, 1, this.size.h, x*tileSize, y*tileSize, tileSize, tileSize) ) { this.position.x = ((x*tileSize)+tileSize); hitSomething = true; break; } if( this.velocity.y > 0 && intersects(this.position.x+dx, this.position.y+dy+this.size.h, this.size.w, 1, x*tileSize, y*tileSize, tileSize, tileSize) ) { this.position.y = ((y*tileSize)-this.size.h); hitSomething = true; break; } else if( this.velocity.y < 0 && intersects(this.position.x+dx, this.position.y+dy, this.size.w, 1, x*tileSize, y*tileSize, tileSize, tileSize) ) { this.position.y = ((y*tileSize)+tileSize); hitSomething = true; break; } } } } if(hitSomething) { this.velocity.x = this.velocity.y = 0; dx = dy = 0; this.setJumping(false); }

    Read the article

  • C++: Vector3 type "wall" ?

    - by anon
    Say I have: class Vector3 { float x, y, z; ... bunch of cuntions .. static operator+(const Vector3&, const Vector3); }; Now, suppose I want to have classes: Position, Velocity, that are exactly like Vector3 (basically, I want typedef Vector3 Position; typedef Vector3 Velocity; Except, given: Position position; Vector3 vector3; Velocity velocity; I want to make sure the following can't happen: position + vector3; vector3 + velocity; velocity + position; What is the best way to achieve this?

    Read the article

  • Unity - Mecanim & Rigidbody on Third Person Controller - Gravity bug?

    - by Celtc
    I'm working on a third person controller which uses physX to interact with the other objects (using the Rigidbody component) and Mecanim to animate the character. All the animations used are baked to Y, and the movement on this axis is controlled by the gravity applied by the rigidbody component. The configuration of the falling animation: And the character components configuration: Since the falling animation doesn't have root motion on XZ, I move the character on XZ by code. Like this: // On the Ground if (IsGrounded()) { GroundedMovementMgm(); // Stores the velocity velocityPreFalling = rigidbody.velocity; } // Mid-Air else { // Continue the pre falling velocity rigidbody.velocity = new Vector3(velocityPreFalling.x, rigidbody.velocity.y, velocityPreFalling.z); } The problem is that when the chracter starts falling and hit against a wall in mid air, it gets stuck to the wall. Here are some pics which explains the problems: Hope someone can help me. Thanks and sory for my bad english! PD.: I was asked for the IsGrounded() function, so I'm adding it: void OnCollisionEnter(Collision collision) { if (!grounded) TrackGrounded(collision); } void OnCollisionStay(Collision collision) { TrackGrounded(collision); } void OnCollisionExit() { grounded = false; } public bool IsGrounded() { return grounded; } private void TrackGrounded(Collision collision) { var maxHeight = capCollider.bounds.min.y + capCollider.radius * .9f; foreach (var contact in collision.contacts) { if (contact.point.y < maxHeight && Vector3.Angle(contact.normal, Vector3.up) < maxSlopeAngle) { grounded = true; break; } } } I'll also add a LINK to download the project if someone wants it.

    Read the article

  • 2D character controller in unity (trying to get old-school platformers back)

    - by Notbad
    This days I'm trying to create a 2D character controller with unity (using phisics). I'm fairly new to physic engines and it is really hard to get the control feel I'm looking for. I would be really happy if anyone could suggest solution for a problem I'm finding: This is my FixedUpdate right now: public void FixedUpdate() { Vector3 v=new Vector3(0,-10000*Time.fixedDeltaTime,0); _body.AddForce(v); v.y=0; if(state(MovementState.Left)) { v.x=-_walkSpeed*Time.fixedDeltaTime+v.x; if(Mathf.Abs(v.x)>_maxWalkSpeed) v.x=-_maxWalkSpeed; } else if(state(MovementState.Right)) { v.x= _walkSpeed*Time.fixedDeltaTime+v.x; if(Mathf.Abs(v.x)>_maxWalkSpeed) v.x=_maxWalkSpeed; } _body.velocity=v; Debug.Log("Velocity: "+_body.velocity); } I'm trying here to just move the rigid body applying a gravity and a linear force for left and right. I have setup a physic material that makes no bouncing and 0 friction when moving and 1 friction with stand still. The main problem is that I have colliders with slopes and the velocity changes from going up (slower) , going down the slope (faster) and walk on a straight collider (normal). How could this be fixed? As you see I'm applying allways same velocity for x axis. For the player I have it setup with a sphere at feet position that is the rigidbody I'm applying forces to. Any other tip that could make my life easier with this are welcomed :). P.D. While coming home I have noticed I could solve this applying a constant force parallel to the surface the player is walking, but don't know if it is best method.

    Read the article

  • Cocos2d: Changing b2Body x val every frame causes jitter

    - by Joey Green
    So, I have a jumping mechanism similar to what you would see in doodle jump where character jumps and you use the accelerometer to make character change direction left or right. I have a player object with position and a box2d b2Body with position. I'm changing the player X position via the accelerometer and the Y position according to box2d. pseudocode for this is like so -----accelerometer acceleration------ player.position = new X -----world update--------- physicsWorld-step() //this will get me the new Y according to the physics similation //so we keep the bodys Y value but change x to new X according to accelerometer data playerPhysicsBody.position = new pos(player.position.x, keepYval) player.position = playerPhysicsBody.position Now this is simplifying my code, but I'm doing the position conversion back and forth via mult or divide by PTM_. Well, I'm getting a weird jitter effect after I get big jump in acceleration data. So, my questions are: 1) Is this the right approach to have the accelerometer control the x pos and box2d control the y pos and just sync everthing up every frame? 2) Is there some issue with updating a b2body x position every frame? 3) Any idea what might be creating this jitter effect? I've collecting some data while running the game. Pre-body is before I set the x value on the b2Body in my update method after I world-step(). Post of course is afterwards. As you can see there is definitively a pattern. 012-06-19 08:14:13.118 Game[1073:707] pre-body pos 5.518720~24.362963 2012-06-19 08:14:13.120 Game[1073:707] post-body pos 5.060156~24.362963 2012-06-19 08:14:13.131 Game[1073:707] player velocity x: -31.833529 2012-06-19 08:14:13.133 Game[1073:707] delta 0.016669 2012-06-19 08:14:13.135 Game[1073:707] pre-body pos 5.060156~24.689455 2012-06-19 08:14:13.137 Game[1073:707] post-body pos 5.502138~24.689455 2012-06-19 08:14:13.148 Game[1073:707] player velocity x: -31.833529 2012-06-19 08:14:13.150 Game[1073:707] delta 0.016667 2012-06-19 08:14:13.151 Game[1073:707] pre-body pos 5.502138~25.006948 2012-06-19 08:14:13.153 Game[1073:707] post-body pos 5.043575~25.006948 2012-06-19 08:14:13.165 Game[1073:707] player velocity x: -31.833529 2012-06-19 08:14:13.167 Game[1073:707] delta 0.016644 2012-06-19 08:14:13.169 Game[1073:707] pre-body pos 5.043575~25.315441 2012-06-19 08:14:13.170 Game[1073:707] post-body pos 5.485580~25.315441 2012-06-19 08:14:13.180 Game[1073:707] player velocity x: -31.833529 2012-06-19 08:14:13.182 Game[1073:707] delta 0.016895 2012-06-19 08:14:13.185 Game[1073:707] pre-body pos 5.485580~25.614935 2012-06-19 08:14:13.188 Game[1073:707] post-body pos 5.026768~25.614935 2012-06-19 08:14:13.198 Game[1073:707] player velocity x: -31.833529 2012-06-19 08:14:13.199 Game[1073:707] delta 0.016454 2012-06-19 08:14:13.207 Game[1073:707] pre-body pos 5.026768~25.905428 2012-06-19 08:14:13.211 Game[1073:707] post-body pos 5.469213~25.905428 2012-06-19 08:14:13.217 Game[1073:707] acceleration x -0.137421 2012-06-19 08:14:13.223 Game[1073:707] player velocity x: -65.022644 2012-06-19 08:14:13.229 Game[1073:707] delta 0.016603

    Read the article

  • Interpolate air drag for my game?

    - by Valentin Krummenacher
    So I have a little game which works with small steps, however those steps vary in time, so for example I sometimes have 10 Steps/second and then I have 20 Steps/second. This changes automatically depending on how many steps the user's computer can take. To avoid inaccurate positioning of the game's player object I use y=v0*dt+g*dt^2/2 to determine my objects y-position, where dt is the time since the last step, v0 is the velocity of my object in the beginning of my step and g is the gravity. To calculate the velocity in the end of a step I use v=v0+g*dt what also gives me correct results, independent of whether I use 2 steps with a dt of for example 20ms or one step with a dt of 40ms. Now I would like to introduce air drag. For simplicity's sake I use a=k*v^2 where a is the air drag's acceleration (I am aware that it would usually result in a force, but since I assume 1kg for my object's mass the force is the same as the resulting acceleration), k is a constant (in this case I'm using 0.001) and v is the speed. Now in an infinitely small time interval a is k multiplied by the velocity in this small time interval powered by 2. The problem is that v in the next time interval would depend on the drag of the last which again depends on the v of the last interval and so on... In other words: If I use a=k*v^2 I get different results for my position/velocity when I use 2 steps of 20ms than when I use one step of 40ms. I used to have this problem for my position too, but adding +g*dt^2/2 to the formula for my position fixed the problem since it takes into account that the position depends on the velocity which changes slightly in every infinitely small time interval. Does something like that exist for air drag too? And no, I dont mean anything like Adding air drag to a golf ball trajectory equation or similar, for that kind of method only gives correct results when all my steps are the same. (I hope you can understand my intermediate english, it's not my main language so I would like to say sorry for all the silly mistakes I might have made in my question)

    Read the article

  • 2D tower defense - A bullet to an enemy

    - by Tashu
    I'm trying to find a good solution for a bullet to hit the enemy. The game is 2D tower defense, the tower is supposed to shoot a bullet and hit the enemy guaranteed. I tried this solution - http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/ The link mentioned to subtract the bullet's origin and the enemy as well (vector subtraction). I tried that but a bullet just follows around the enemy. float diffX = enemy.position.x - position.x; float diffY = enemy.position.y - position.y; velocity.x = diffX; velocity.y = diffY; position.add(velocity.x * deltaTime, velocity.y * deltaTime); I'm familiar with vectors but not sure what steps (vector math operations) to be done to get this solution working.

    Read the article

  • Jump handling and gravity

    - by sprawl
    I'm new to game development and am looking for some help on improving my jump handling for a simple side scrolling game I've made. I would like to make the jump last longer if the key is held down for the full length of the jump, otherwise if the key is tapped, make the jump not as long. Currently, how I'm handling the jumping is the following: Player.prototype.jump = function () { // Player pressed jump key if (this.isJumping === true) { // Set sprite to jump state this.settings.slice = 250; if (this.isFalling === true) { // Player let go of jump key, increase rate of fall this.settings.y -= this.velocity; this.velocity -= this.settings.gravity * 2; } else { // Player is holding down jump key this.settings.y -= this.velocity; this.velocity -= this.settings.gravity; } } if (this.settings.y >= 240) { // Player is on the ground this.isJumping = false; this.isFalling = false; this.velocity = this.settings.maxVelocity; this.settings.y = 240; } } I'm setting isJumping on keydown and isFalling on keyup. While it works okay for simple use, I'm looking for a better way handle jumping and gravity. It's a bit buggy if the gravity is increased (which is why I had to put the last y setting in the last if condition in there) on keyup, so I'd like to know a better way to do it. Where are some resources I could look at that would help me better understand how to handle jumping and gravity? What's a better approach to handling this? Like I said, I'm new to game development so I could be doing it completely wrong. Any help would be appreciated.

    Read the article

  • Moving in a diamond - enemy gets stuck

    - by Fibericon
    I have an enemy that I would like to move as follows: Start at (0, 200, 0) Move to (200, 0, 0) Move to (0, -200, 0) Move to (-200, 0, 0) Move to start point, repeat as long as it remains active. This is what I've done to achieve that: if (position.X < 200 && position.Y > 0) { Velocity = new Vector3(1, -1, 0) * speed; } else if (position.X >= 200 && position.Y <= 0 && position.Y > -200) { Velocity = new Vector3(-1, -1, 0) * speed; } else if (position.X <= 0 && position.Y <= -200) { Velocity = new Vector3(-1, 1, 0) * speed; } else { Velocity = new Vector3(1, 1, 0) * speed; } It moves to the second point, but then gets stuck and appears to vibrate in place. How should I be doing this?

    Read the article

  • How can I factor momentum into my space sim?

    - by Josh Petite
    I am trying my hand at creating a simple 2d physics engine right now, and I'm running into some problems figuring out how to incorporate momentum into movement of a spaceship. If I am moving in a given direction at a certain velocity, I am able to currently update the position of my ship easily (Position += Direction * Velocity). However, if the ship rotates at all, and I recalculate the direction (based on the new angle the ship is facing), and accelerate in that direction, how can I take momentum into account to alter the "line" that the ship travels? Currently the ship changes direction instantaneously and continues at its current velocity in that new direction when I press the thrust button. I want it to be a more gradual turning motion so as to give the impression that the ship itself has some mass. If there is already a nice post on this topic I apologize, but nothing came up in my searches. Let me know if any more information is needed, but I'm hoping someone can easily tell me how I can throw mass * velocity into my game loop update.

    Read the article

  • Automatically triggering standard spaceship controls to stop its motion

    - by Garan
    I have been working on a 2D top-down space strategy/shooting game. Right now it is only in the prototyping stage (I have gotten basic movement) but now I am trying to write a function that will stop the ship based on it's velocity. This is being written in Lua, using the Love2D engine. My code is as follows (note- object.dx is the x-velocity, object.dy is the y-velocity, object.acc is the acceleration, and object.r is the rotation in radians): function stopMoving(object, dt) local targetr = math.atan2(object.dy, object.dx) if targetr == object.r + math.pi then local currentspeed = math.sqrt(object.dx*object.dx+object.dy*object.dy) if currentspeed ~= 0 then object.dx = object.dx + object.acc*dt*math.cos(object.r) object.dy = object.dy + object.acc*dt*math.sin(object.r) end else if (targetr - object.r) >= math.pi then object.r = object.r - object.turnspeed*dt else object.r = object.r + object.turnspeed*dt end end end It is implemented in the update function as: if love.keyboard.isDown("backspace") then stopMoving(player, dt) end The problem is that when I am holding down backspace, it spins the player clockwise (though I am trying to have it go the direction that would be the most efficient at getting to the angle it would have to be) and then it never starts to accelerate the player in the direction opposite to it's velocity. What should I change in this code to get that to work? EDIT : I'm not trying to just stop the player in place, I'm trying to get it to use it's normal commands to neutralize it's existing velocity. I also changed math.atan to math.atan2, apparently it's better. I noticed no difference when running it, though.

    Read the article

  • Predicted target location

    - by user3256944
    I'm having an issue with calculating the predicted linear angle a projectile needs to move in to intersect a moving enemy ship for my 2D game. I've tried following the document here, but what I've have come up with is simply awful. protected Vector2 GetPredictedPosition(float angleToEnemy, ShipCompartment origin, ShipCompartment target) { // Below obviously won't compile (document wants a Vector, not sure how to get that from a single float?) Vector2 velocity = target.Thrust - 25f; // Closing velocity (25 is example projectile velocity) Vector2 distance = target.Position - origin.Position; // Range to close double time = distance.Length() / velocity.Length(); // Time // Garbage code, doesn't compile, this method is incorrect return target.Position + (target.Thrust * time); } I would be grateful if the community can help point out how this is done correctly.

    Read the article

  • One-way platform collision

    - by TheBroodian
    I hate asking questions that are specific to my own code like this, but I've run into a pesky roadblock and could use some help getting around it. I'm coding floating platforms into my game that will allow a player to jump onto them from underneath, but then will not allow players to fall through them once they are on top, which require some custom collision detection code. The code I have written so far isn't working, the character passes through it on the way up, and on the way down, stops for a moment on the platform, and then falls right through it. Here is the code to handle collisions with floating platforms: protected void HandleFloatingPlatforms(Vector2 moveAmount) { //if character is traveling downward. if (moveAmount.Y > 0) { Rectangle afterMoveRect = collisionRectangle; afterMoveRect.Offset((int)moveAmount.X, (int)moveAmount.Y); foreach (World_Objects.GameObject platform in gameplayScreen.Entities) { if (platform is World_Objects.Inanimate_Objects.FloatingPlatform) { //wideProximityArea is just a rectangle surrounding the collision //box of an entity to check for nearby entities. if (wideProximityArea.Intersects(platform.CollisionRectangle) || wideProximityArea.Contains(platform.CollisionRectangle)) { if (afterMoveRect.Intersects(platform.CollisionRectangle)) { //This, in my mind would denote that after the character is moved, its feet have fallen below the top of the platform, but before he had moved its feet were above it... if (collisionRectangle.Bottom <= platform.CollisionRectangle.Top) { if (afterMoveRect.Bottom > platform.CollisionRectangle.Top) { //And then after detecting that he has fallen through the platform, reposition him on top of it... worldLocation.Y = platform.CollisionRectangle.Y - frameHeight; hasCollidedVertically = true; } } } } } } } } In case you are curious, the parameter moveAmount is found through this code: elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; float totalX = 0; float totalY = 0; foreach (Vector2 vector in velocities) { totalX += vector.X; totalY += vector.Y; } velocities.Clear(); velocity.X = totalX; velocity.Y = totalY; velocity.Y = Math.Min(velocity.Y, 1000); Vector2 moveAmount = velocity * elapsed;

    Read the article

  • Set a 2d camera's position so that a building is under the players feet

    - by Potato
    My issue is this: i am making a scrolling game in XNA, and the camera updates based on the players velocity, but the player never actually moves, he is always in the center of the screen. When he hits the top of the building though i want him to always be on top and sink through the texture in a way like this: what i am doing to make this happen is i am just setting his velocity to 0, so its not moving, but the more velocity he hits a building with the more he sinks through it. I also tried setting the buildings position to the plays Bounding Box's bottom, and this achieved the look i wanted but this also resulted in the other buildings rising in the air, because the velocity was still moving (even if i set it to 0). if it was not a scrolling game, this would be not a problem, because you just set the players position to the top of the building, but because the player never actually moves, i actually need to move the camera to the point where the building is under the players feet without the other buildings rising. (Take note this is note a real camera, it is just a class that moves the objects in the world based on the players velocity). All questions are welcome.

    Read the article

  • snapping an angle to the closest cardinal direction

    - by Josh E
    I'm developing a 2D sprite-based game, and I'm finding that I'm having trouble with making the sprites rotate correctly. In a nutshell, I've got spritesheets for each of 5 directions (the other 3 come from just flipping the sprite horizontally), and I need to clamp the velocity/rotation of the sprite to one of those directions. My sprite class has a pre-computed list of radians corresponding to the cardinal directions like this: protected readonly List<float> CardinalDirections = new List<float> { MathHelper.PiOver4, MathHelper.PiOver2, MathHelper.PiOver2 + MathHelper.PiOver4, MathHelper.Pi, -MathHelper.PiOver4, -MathHelper.PiOver2, -MathHelper.PiOver2 + -MathHelper.PiOver4, -MathHelper.Pi, }; Here's the positional update code: if (velocity == Vector2.Zero) return; var rot = ((float)Math.Atan2(velocity.Y, velocity.X)); TurretRotation = SnapPositionToGrid(rot); var snappedX = (float)Math.Cos(TurretRotation); var snappedY = (float)Math.Sin(TurretRotation); var rotVector = new Vector2(snappedX, snappedY); velocity *= rotVector; //...snip private float SnapPositionToGrid(float rotationToSnap) { if (rotationToSnap == 0) return 0.0f; var targetRotation = CardinalDirections.First(x => (x - rotationToSnap >= -0.01 && x - rotationToSnap <= 0.01)); return (float)Math.Round(targetRotation, 3); } What am I doing wrong here? I know that the SnapPositionToGrid method is far from what it needs to be - the .First(..) call is on purpose so that it throws on no match, but I have no idea how I would go about accomplishing this, and unfortunately, Google hasn't helped too much either. Am I thinking about this the wrong way, or is the answer staring at me in the face?

    Read the article

  • How do I interpolate air drag with a variable time step?

    - by Valentin Krummenacher
    So I have a little game which works with small steps, however those steps vary in time, so for example I sometimes have 10 Steps/second and then I have 20 Steps/second. This changes automatically depending on how many steps the user's computer can take. To avoid inaccurate positioning of the game's player object I use y=v0*dt+g*dt^2/2 to determine my objects y-position, where dt is the time since the last step, v0 is the velocity of my object in the beginning of my step and g is the gravity. To calculate the velocity in the end of a step I use v=v0+g*dt what also gives me correct results, independent of whether I use 2 steps with a dt of for example 20ms or one step with a dt of 40ms. Now I would like to introduce air drag. For simplicity's sake I use a=k*v^2 where a is the air drag's acceleration (I am aware that it would usually result in a force, but since I assume 1kg for my object's mass the force is the same as the resulting acceleration), k is a constant (in this case I'm using 0.001) and v is the speed. Now in an infinitely small time interval a is k multiplied by the velocity in this small time interval powered by 2. The problem is that v in the next time interval would depend on the drag of the last which again depends on the v of the last interval and so on... In other words: If I use a=k*v^2 I get different results for my position/velocity when I use 2 steps of 20ms than when I use one step of 40ms. I used to have this problem for my position too, but adding +g*dt^2/2 to the formula for my position fixed the problem since it takes into account that the position depends on the velocity which changes slightly in every infinitely small time interval. Does something like that exist for air drag too? And no, I dont mean anything like Adding air drag to a golf ball trajectory equation or similar, for that kind of method only gives correct results when all my steps are the same. (I hope you can understand my intermediate english, it's not my main language so I would like to say sorry for all the silly mistakes I might have made in my question)

    Read the article

  • understanding and implementing Boids

    - by alphablender
    So I'm working on porting Boids to Brightscript, based on the pseudocode here: http://www.kfish.org/boids/pseudocode.html I'm trying to understand the data structures involved, for example is Velocity a single value, or is it a 3D value, ie velocity={x,y,z} It seems as if the pseudocode seems to mix this up where sometimes it has an equation that incudes both vectors and single-value items: v1 = rule1(b) v2 = rule2(b) v3 = rule3(b) b.velocity = b.velocity + v1 + v2 + v3 If Velocity is a tripartite value then this would make sense, but I'm not sure. So my first question here is, is this the correct datastructure for a single boid based on the Pseudocode on that page: boid={position:{px:0,py:0,pz:0},velocity:{x:0,y:0,z:0},vector:{x:0,y:0,z:0},pc:{x:0,y:0,z:0},pv:{x:0,y:0,z:0}) where pc=perceived center, pv= perceived velocity I"ve implemented a vector_add, vector_sub, vector_div, and vector boolean functions. The reason I'm starting from this pseudocode is I've not been able to find anything else that is as readable, but it still leaves me with lots of questions as the data structures are not explicitly defined for each variable. (edit) here's a good example of what i'm talking about: IF |b.position - bJ.position| < 100 THEN if b.position - b[j].position are both 3D coordinates, how can they be considered "less than 100" unless they are < {100,100,100} ? Maybe that is what I need to do here, use a vector comparison function?

    Read the article

  • (Libgdx) Move Vector2 along angle?

    - by gemurdock
    I have seen several answers on here about moving along angle, but I can't seem to get this to work properly for me and I am new to LibGDX... just trying to learn. These are my Vector2's that I am using for this function. public Vector2 position = new Vector2(); public Vector2 velocity = new Vector2(); public Vector2 movement = new Vector2(); public Vector2 direction = new Vector2(); Here is the function that I use to move the position vector along an angle. setLocation() just sets the new location of the image. public void move(float delta, float degrees) { position.set(image.getX() + image.getWidth() / 2, image.getY() + image.getHeight() / 2); direction.set((float) Math.cos(degrees), (float) Math.sin(degrees)).nor(); velocity.set(direction).scl(speed); movement.set(velocity).scl(delta); position.add(movement); setLocation(position.x, position.y); // Sets location of image } I get a lot of different angles with this, just not the correct angles. How should I change this function to move a Vector2 along an angle using the Vector2 class from com.badlogic.gdx.math.Vector2 within the LibGDX library? I found this answer, but not sure how to implement it. Update: I figured out part of the issue. Should convert degrees to radians. However, the angle of 0 degrees is towards the right. Is there any way to fix this? As I shouldn't have to add 90 to degrees in order to have correct heading. New code is below public void move(float delta, float degrees) { degrees += 90; // Set degrees to correct heading, shouldn't have to do this position.set(image.getX() + image.getWidth() / 2, image.getY() + image.getHeight() / 2); direction.set(MathUtils.cos(degrees * MathUtils.degreesToRadians), MathUtils.sin(degrees * MathUtils.degreesToRadians)).nor(); velocity.set(direction).scl(speed); movement.set(velocity).scl(delta); position.add(movement); setLocation(position.x, position.y); }

    Read the article

  • UDK game Prisoners/Guards

    - by RR_1990
    For school I need to make a little game with UDK, the concept of the game is: The player is the headguard, he will have some other guard (bots) who will follow him. Between the other guards and the player are some prisoners who need to evade the other guards. It needs to look like this My idea was to let the guard bots follow the player at a certain distance and let the prisoners bots in the middle try to evade the guard bots. Now is the problem i'm new to Unreal Script and the school doesn't support me that well. Untill now I have only was able to make the guard bots follow me. I hope you guys can help me or make me something that will make this game work. Here is the class i'm using to let te bots follow me: class ChaseControllerAI extends AIController; var Pawn player; var float minimalDistance; var float speed; var float distanceToPlayer; var vector selfToPlayer; auto state Idle { function BeginState(Name PreviousStateName) { Super.BeginState(PreviousStateName); } event SeePlayer(Pawn p) { player = p; GotoState('Chase'); } Begin: player = none; self.Pawn.Velocity.x = 0.0; self.Pawn.Velocity.Y = 0.0; self.Pawn.Velocity.Z = 0.0; } state Chase { function BeginState(Name PreviousStateName) { Super.BeginState(PreviousStateName); } event PlayerOutOfReach() { `Log("ChaseControllerAI CHASE Player out of reach."); GotoState('Idle'); } // class ChaseController extends AIController; CONTINUED // State Chase (continued) event Tick(float deltaTime) { `Log("ChaseControllerAI in Event Tick."); selfToPlayer = self.player.Location - self.Pawn.Location; distanceToPlayer = Abs(VSize(selfToPlayer)); if (distanceToPlayer > minimalDistance) { PlayerOutOfReach(); } else { self.Pawn.Velocity = Normal(selfToPlayer) * speed; //self.Pawn.Acceleration = Normal(selfToPlayer) * speed; self.Pawn.SetRotation(rotator(selfToPlayer)); self.Pawn.Move(self.Pawn.Velocity*0.001); // or *deltaTime } } Begin: `Log("Current state Chase:Begin: " @GetStateName()@""); } defaultproperties { bAdjustFromWalls=true; bIsPlayer= true; minimalDistance = 1024; //org 1024 speed = 500; }

    Read the article

  • Arrive steering behavior

    - by dbostream
    I bought a book called Programming game AI by example and I am trying to implement the arrive steering behavior. The problem I am having is that my objects oscillate around the target position; after oscillating less and less for awhile they finally come to a stop at the target position. Does anyone have any idea why this oscillating behavior occur? Since the examples accompanying the book are written in C++ I had to rewrite the code into C#. Below is the relevant parts of the steering behavior: private enum Deceleration { Fast = 1, Normal = 2, Slow = 3 } public MovingEntity Entity { get; private set; } public Vector2 SteeringForce { get; private set; } public Vector2 Target { get; set; } public Vector2 Calculate() { SteeringForce.Zero(); SteeringForce = SumForces(); SteeringForce.Truncate(Entity.MaxForce); return SteeringForce; } private Vector2 SumForces() { Vector2 force = new Vector2(); if (Activated(BehaviorTypes.Arrive)) { force += Arrive(Target, Deceleration.Slow); if (!AccumulateForce(force)) return SteeringForce; } return SteeringForce; } private Vector2 Arrive(Vector2 target, Deceleration deceleration) { Vector2 toTarget = target - Entity.Position; double distance = toTarget.Length(); if (distance > 0) { //because Deceleration is enumerated as an int, this value is required //to provide fine tweaking of the deceleration.. double decelerationTweaker = 0.3; double speed = distance / ((double)deceleration * decelerationTweaker); speed = Math.Min(speed, Entity.MaxSpeed); Vector2 desiredVelocity = toTarget * speed / distance; return desiredVelocity - Entity.Velocity; } return new Vector2(); } private bool AccumulateForce(Vector2 forceToAdd) { double magnitudeRemaining = Entity.MaxForce - SteeringForce.Length(); if (magnitudeRemaining <= 0) return false; double magnitudeToAdd = forceToAdd.Length(); if (magnitudeToAdd > magnitudeRemaining) magnitudeToAdd = magnitudeRemaining; SteeringForce += Vector2.NormalizeRet(forceToAdd) * magnitudeToAdd; return true; } This is the update method of my objects: public void Update(double deltaTime) { Vector2 steeringForce = Steering.Calculate(); Vector2 acceleration = steeringForce / Mass; Velocity = Velocity + acceleration * deltaTime; Velocity.Truncate(MaxSpeed); Position = Position + Velocity * deltaTime; } If you want to see the problem with your own eyes you can download a minimal example here. Thanks in advance.

    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

  • Implementing Circle Physics in Java

    - by Shijima
    I am working on a simple physics based game where 2 balls bounce off each other. I am following a tutorial, 2-Dimensional Elastic Collisions Without Trigonometry, for the collision reactions. I am using Vector2 from the LIBGDX library to handle vectors. I am a bit confused on how to implement step 6 in Java from the tutorial. Below is my current code, please note that the code strictly follows the tutorial and there are redundant pieces of code which I plan to refactor later. Note: refrences to this refer to ball 1, and ball refers to ball 2. /* * Step 1 * * Find the Normal, Unit Normal and Unit Tangential vectors */ Vector2 n = new Vector2(this.position[0] - ball.position[0], this.position[1] - ball.position[1]); Vector2 un = n.normalize(); Vector2 ut = new Vector2(-un.y, un.x); /* * Step 2 * * Create the initial (before collision) velocity vectors */ Vector2 v1 = this.velocity; Vector2 v2 = ball.velocity; /* * Step 3 * * Resolve the velocity vectors into normal and tangential components */ float v1n = un.dot(v1); float v1t = ut.dot(v1); float v2n = un.dot(v2); float v2t = ut.dot(v2); /* * Step 4 * * Find the new tangential Velocities after collision */ float v1tPrime = v1t; float v2tPrime = v2t; /* * Step 5 * * Find the new normal velocities */ float v1nPrime = v1n * (this.mass - ball.mass) + (2 * ball.mass * v2n) / (this.mass + ball.mass); float v2nPrime = v2n * (ball.mass - this.mass) + (2 * this.mass * v1n) / (this.mass + ball.mass); /* * Step 6 * * Convert the scalar normal and tangential velocities into vectors??? */

    Read the article

  • How to do a multishot in xna?

    - by DeVonte
    I am trying to simulate a gun in which shoots multiple bullets at the same time(similar to a spread out shot). I am thinking I have to create another bullet array then do the same as I have below but in a different direction. Here is what I have so far: foreach (GameObject bullet in bullets) { // Find a bullet that isn't alive if (!bullet.alive) { //And set it to alive bullet.alive = true; if (flip == SpriteEffects.FlipHorizontally) //Facing right { float armCos = (float)Math.Cos(arm.rotation - MathHelper.PiOver2); float armSin = (float)Math.Sin(arm.rotation - MathHelper.PiOver2); // Set the initial position of our bullets at the end of our gun arm // 42 is obtained by taking the width of the Arm_Gun texture / 2 // and subtracting the width of the Bullet texture / 2. ((96/2)=(12/2)) bullet.position = new Vector2( arm.position.X + 42 * armCos, arm.position.Y + 42 * armSin); // And give it a velocity of the direction we're aiming. // Increae/decrease speed by changeing 15.0f bullet.Velocity = new Vector2( (float)Math.Cos(arm.rotation - MathHelper.PiOver4 + MathHelper.Pi + MathHelper.PiOver2), (float)Math.Sin(arm.rotation - MathHelper.PiOver4 + MathHelper.Pi + MathHelper.PiOver2)) * 15.0f; } else //Facing left { float armCos = (float)Math.Cos(arm.rotation + MathHelper.PiOver2); float armSin = (float)Math.Sin(arm.rotation + MathHelper.PiOver2); //Set the initial position of our bullet at the end of our gun arm //42 is obtained be taking the width of the Arm_Gun texture / 2 //and subtracting the width of the Bullet texture / 2. ((96/2)-(12/2)) bullet.position = new Vector2( arm.position.X - 42 * armCos, arm.position.Y - 42 * armSin); //And give it a velocity of the direction we're aiming. //Increase/decrease speed by changing 15.0f bullet.Velocity = new Vector2( -armCos, -armSin) * 15.0f; } return; }// End if }// End foreach

    Read the article

  • Elliptical orbit modeling

    - by Nathon
    I'm playing with orbits in a simple 2-d game where a ship flies around in space and is attracted to massive things. The ship's velocity is stored in a vector and acceleration is applied to it every frame as appropriate given Newton's law of universal gravitation. The point masses don't move (there's only 1 right now) so I would expect an elliptical orbit. Instead, I see this: I've tried with nearly circular orbits, and I've tried making the masses vastly different (a factor of a million) but I always get this rotated orbit. Here's some (D) code, for context: void accelerate(Vector delta) { velocity = velocity + delta; // Velocity is a member of the ship class. } // This function is called every frame with the fixed mass. It's a // method of the ship's. void fall(Well well) { // f=(m1 * m2)/(r**2) // a=f/m // Ship mass is 1, so a = f. float mass = 1; Vector delta = well.position - loc; float rSquared = delta.magSquared; float force = well.mass/rSquared; accelerate(delta * force * mass); }

    Read the article

  • LibGDX onTouch() method kill on touch

    - by johnny-b
    How can I add this on my application. i want to use the onTouch() method from the implementation of the InputProcessor to kill the enemies on screen. how do i do that? do i have to do anything to the enemy class? please help Thank you M @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { return false; } here is my enemy class public class Bullet extends Sprite { private Vector2 velocity; private float lifetime; public Bullet(float x, float y) { velocity = new Vector2(0, 0); } public void update(float delta) { float targetX = GameWorld.getBall().getX(); float targetY = GameWorld.getBall().getY(); float dx = targetX - getX(); float dy = targetY - getY(); float distToTarget = (float) Math.sqrt(dx * dx + dy * dy); velocity.x += dx * delta; velocity.y += dy * delta; } } i am rendering all graphics in a GameRender class and a gameworld class if you need more info please let me know Thank you

    Read the article

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