Search Results

Search found 2043 results on 82 pages for 'collision detection'.

Page 18/82 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Collision detection when pathfinding with pathnodes, UDK

    - by Dave Voyles
    I'm trying to create a class that allows my AIController to path find using pathnodes (NOT NavMeshes). It's doing a swell job of going from point to point in a set order (although I would like for it to be a random patrol at some point), but it gets caught up on collision from time to time. I.E. He'll walk the same set path, and when he runs into the blocks in the middle of the map he continues to rub against them until they finish, and continues on his merry way to the next path node. How can I prevent this from happening, or at least have him move from the wall if he does a trace and detects that it is there? It looks like I need to use MoveToward() instead of MoveTo(), as MoveToward allows the pawn to adjust its course during movement. I'm just not sure of how to use those paramters. Mougli has a decent tutorial on it[/URL], but I can't seem to get it to work correctly with my pathnode array. class PathfindingAIController extends UDKBot; var array Waypoints; var int _PathNode; //declare it at the start so you can use it throughout the script var int CloseEnough; simulated function PostBeginPlay() { local PathNode Current; super.PostBeginPlay(); //add the pathnodes to the array foreach WorldInfo.AllActors(class'Pathnode',Current) { Waypoints.AddItem( Current ); } } simulated function Tick(float DeltaTime) { local int Distance; local Rotator DesiredRotation; super.Tick(DeltaTime); if (Pawn != None) { // Smoothly rotate the pawn towards the focal point DesiredRotation = Rotator(GetFocalPoint() - Pawn.Location); Pawn.FaceRotation(RLerp(Pawn.Rotation, DesiredRotation, 3.125f * DeltaTime, true), DeltaTime); } Distance = VSize2D(Pawn.Location - Waypoints[_PathNode].Location); if (Distance <= CloseEnough) { _PathNode++; } if (_PathNode >= Waypoints.Length) { _PathNode = 0; } GoToState('Pathfinding'); } auto state Pathfinding { Begin: if (Waypoints[_PathNode] != None) // make sure there is a pathnode to move to { MoveTo(Waypoints[_PathNode].Location); //move to it `log("STATE: Pathfinding"); } } DefaultProperties { CloseEnough=400 bIsplayer = True }

    Read the article

  • add collision detection to sprite?

    - by xBroak
    bassically im trying to add collision detection to the sprite below, using the following: self.rect = bounds_rect collide = pygame.sprite.spritecollide(self, wall_list, False) if collide: # yes print("collide") However it seems that when the collide is triggered it continuously prints 'collide' over and over when instead i want them to simply not be able to walk through the object, any help? def update(self, time_passed): """ Update the creep. time_passed: The time passed (in ms) since the previous update. """ if self.state == Creep.ALIVE: # Maybe it's time to change the direction ? # self._change_direction(time_passed) # Make the creep point in the correct direction. # Since our direction vector is in screen coordinates # (i.e. right bottom is 1, 1), and rotate() rotates # counter-clockwise, the angle must be inverted to # work correctly. # self.image = pygame.transform.rotate( self.base_image, -self.direction.angle) # Compute and apply the displacement to the position # vector. The displacement is a vector, having the angle # of self.direction (which is normalized to not affect # the magnitude of the displacement) # displacement = vec2d( self.direction.x * self.speed * time_passed, self.direction.y * self.speed * time_passed) self.pos += displacement # When the image is rotated, its size is changed. # We must take the size into account for detecting # collisions with the walls. # self.image_w, self.image_h = self.image.get_size() global bounds_rect bounds_rect = self.field.inflate( -self.image_w, -self.image_h) if self.pos.x < bounds_rect.left: self.pos.x = bounds_rect.left self.direction.x *= -1 elif self.pos.x > bounds_rect.right: self.pos.x = bounds_rect.right self.direction.x *= -1 elif self.pos.y < bounds_rect.top: self.pos.y = bounds_rect.top self.direction.y *= -1 elif self.pos.y > bounds_rect.bottom: self.pos.y = bounds_rect.bottom self.direction.y *= -1 self.rect = bounds_rect collide = pygame.sprite.spritecollide(self, wall_list, False) if collide: # yes print("collide") elif self.state == Creep.EXPLODING: if self.explode_animation.active: self.explode_animation.update(time_passed) else: self.state = Creep.DEAD self.kill() elif self.state == Creep.DEAD: pass #------------------ PRIVATE PARTS ------------------# # States the creep can be in. # # ALIVE: The creep is roaming around the screen # EXPLODING: # The creep is now exploding, just a moment before dying. # DEAD: The creep is dead and inactive # (ALIVE, EXPLODING, DEAD) = range(3) _counter = 0 def _change_direction(self, time_passed): """ Turn by 45 degrees in a random direction once per 0.4 to 0.5 seconds. """ self._counter += time_passed if self._counter > randint(400, 500): self.direction.rotate(45 * randint(-1, 1)) self._counter = 0 def _point_is_inside(self, point): """ Is the point (given as a vec2d) inside our creep's body? """ img_point = point - vec2d( int(self.pos.x - self.image_w / 2), int(self.pos.y - self.image_h / 2)) try: pix = self.image.get_at(img_point) return pix[3] > 0 except IndexError: return False def _decrease_health(self, n): """ Decrease my health by n (or to 0, if it's currently less than n) """ self.health = max(0, self.health - n) if self.health == 0: self._explode() def _explode(self): """ Starts the explosion animation that ends the Creep's life. """ self.state = Creep.EXPLODING pos = ( self.pos.x - self.explosion_images[0].get_width() / 2, self.pos.y - self.explosion_images[0].get_height() / 2) self.explode_animation = SimpleAnimation( self.screen, pos, self.explosion_images, 100, 300) global remainingCreeps remainingCreeps-=1 if remainingCreeps == 0: print("all dead")

    Read the article

  • MarteEngine Tile Collision

    - by opiop65
    I need to add collision to my tile map using MarteEngine. MarteEngine is built of of slick2D. Here's my tile generation code: Code: public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException { for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { map[x][y] = AIR; air.draw(x * GameWorld.tilesize, y * GameWorld.tilesize); } } for (int x = 0; x < 16; x++) { for (int y = 7; y < 8; y++) { map[x][y] = GRASS; grass.draw(x * tilesize, y * tilesize); } } for (int x = 0; x < 16; x++) { for (int y = 8; y < 10; y++) { map[x][y] = DIRT; dirt.draw(x * tilesize, y * tilesize); } } for (int x = 0; x < 16; x++) { for (int y = 10; y < 16; y++) { map[x][y] = STONE; stone.draw(x * tilesize, y * tilesize); } } super.render(gc, game, g); } And one of my tile classes (they're all the same, the image names are just different): Code: package MarteEngine; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import it.randomtower.engine.entity.Entity; public class Grass extends Entity { public static Image grass = null; public Grass(float x, float y) throws SlickException { super(x, y); grass = new Image("res/grass.png"); setHitBox(0, 0, 50, 50); addType(SOLID); } } I tried to do it like this: Code: for (int x = 0; x < 16; x++) { for (int y = 7; y < 8; y++) { map[x][y] = GRASS; Grass.grass.draw(x * tilesize, y * tilesize); } } But it gave me a NullPointerException. No idea why, everything looks initialized right? I would be very grateful for some help!

    Read the article

  • Collision disturbing the jumping mechanic in java 2D game [on hold]

    - by user50931
    So I have been working on a 2D Java game recently and everything was going smoothly, until I reached a problem to do with the players jumping mechanic. So far I've got the player to jump a fixed rate and fall due to gravity. Hers my code for my Player class. public class Player extends GameObject { public Player(int x, int y, int width, int height, ObjectId id) { super(x, y, width, height, id); } @Override public void tick(ArrayList<GameObject> object) { if(go){ x+=vx; y+=vy; } if(vx <0){ facing =-1; }else if(vx >0) facing =1; checkCollision(object); checkStance(); } private void checkStance() { if(falling){ //gravity jumping = false; vy = speed/2; } if(jumping){ // Calculates how high jump should be vy = -speed*2; if(jumpY - y >= maxJumpHeight) falling =true; } } private void checkCollision(ArrayList<GameObject> object) { for(int i=0; i< object.size(); i++ ){ GameObject tempObject = object.get(i); if(tempObject.getId() == ObjectId.Ledge){ if(getBoundsTop().intersects(tempObject.getBoundsAll())){ //Top y = tempObject.getY() + tempObject.getBoundsAll().height; falling =true; } if(getBoundsRight().intersects(tempObject.getBoundsAll())){ // Right x = tempObject.getX() -width ; } if(getBoundsLeft().intersects(tempObject.getBoundsAll())){ //Left x = tempObject.getX() + tempObject.getWidth(); } if(getBoundsBottom().intersects(tempObject.getBoundsAll())){ //Bottom y = tempObject.getY() - height; falling =false; vy=0; }else{ falling =true; } } } } @Override public void render(Graphics g) { g.setColor(Color.BLACK); g.fillRect((int)x, (int)y, width, height); } @Override public Rectangle getBoundsAll() { return new Rectangle((int)x, (int)y,width,height); } public Rectangle getBoundsTop() { return new Rectangle((int) x , (int)y ,width,height/15); } public Rectangle getBoundsBottom() { return new Rectangle( (int)x , (int) y +height -(height /15),width,height/15); } public Rectangle getBoundsLeft() { return new Rectangle( (int) x , (int) y + height /10 ,width/8,height - (height /5)); } public Rectangle getBoundsRight() { return new Rectangle((int) x + width - (width/8) ,(int) y + height /10 ,width/8,height - height/5); } } My problem is when I add: else{ falling =true; } during the loop of the ArrayList to check collision, it stops the player from jumping and keeps him on the ground. I've tried to find a way around this but haven't had any luck. Any suggestions?

    Read the article

  • Collision detection problem in XNA

    - by Fantasy
    I'm having two problems with my collision detection in XNA. There are two boxes, the red box represents a player and the blue box represents a wall. The first problem is when the player moves to the upper side or bottom side of the wall and collides with it, and then try to go to the left or right, the player will just jump in the opposite direction as seen in the video. However if I go to the right side or the left side of the wall and try to go up or down the player will smoothly go up or down without jumping. The second problem is that when I collide with the box and my key is still pressed down the blue box goes half way through red box and and goes back out and it keeps doing that until I stop pressing the keyboard. its not very clear on the video but the keeps going in and out really fast until I stop pressing the key. Here is a video example:- http://www.youtube.com/watch?v=mKLJsrPviYo and Here is my code Vector2 Position; Rectangle PlayerRectangle, BoxRectangle; float Speed = 0.25f; enum Direction { Up, Right, Down, Left }; Direction direction; protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); KeyboardState keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Keys.Up)) { Position.Y -= (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds); direction = Direction.Up; } if (keyboardState.IsKeyDown(Keys.Down)) { Position.Y += (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds); direction = Direction.Down; } if (keyboardState.IsKeyDown(Keys.Right)) { Position.X += (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds); direction = Direction.Right; } if (keyboardState.IsKeyDown(Keys.Left)) { Position.X -= (float)(Speed * gameTime.ElapsedGameTime.TotalMilliseconds); direction = Direction.Left; } if (PlayerRectangle.Intersects(BoxRectangle)) { if (direction == Direction.Right) Position.X = BoxRectangle.Left - PlayerRectangle.Width; else if (direction == Direction.Left) Position.X = BoxRectangle.Right; if (direction == Direction.Down) Position.Y = BoxRectangle.Top - PlayerRectangle.Height; else if (direction == Direction.Up) Position.Y = BoxRectangle.Bottom; } PlayerRectangle = new Rectangle((int)Position.X, (int)Position.Y, (int)32, (int)32); base.Update(gameTime); }

    Read the article

  • Does any one know is there any collision detection API for HTML5 Canvas..?

    - by angos
    I have been experimenting HTML5 canvas by coding basic mind-mapping application. I have tried to find out if there is any javascript API used for managing object in canvas like collision detection between images or shapes. I think it is not a good idea to write my own since there might be some good API around. Anyone have clue or some information on this. I would very much appreciate.

    Read the article

  • How to make a stack stable? Need help for an explicit resting contact scheme (2-dimensional)

    - by Register Sole
    Previously, I struggle with the sequential impulse-based method I developed. Thanks to jedediah referring me to this paper, I managed to rebuild the codes and implement the simultaneous impulse based method with Projected-Gauss-Seidel (PGS) iterative solver as described by Erin Catto (mentioned in the reference of the paper as [Catt05]). So here's how it currently is: The simulation handles 2-dimensional rotating convex polygons. Detection is using separating-axis test, with a SKIN, meaning closest points between two polygons is detected and determined if their distance is less than SKIN. To resolve collision, simultaneous impulse-based method is used. It is solved using iterative solver (PGS-solver) as in Erin Catto's paper. Error-correction is implemented using Baumgarte's stabilization (you can refer to either paper for this) using J V = beta/dt*overlap, J is the Jacobian for the constraints, V the matrix containing the velocities of the bodies, beta an error-correction parameter that is better be < 1, dt the time-step taken by the engine, and overlap, the overlap between the bodies (true overlap, so SKIN is ignored). However, it is still less stable than I expected :s I tried to stack hexagons (or squares, doesn't really matter), and even with only 4 to 5 of them, they would swing! Also note that I am not looking for a sleeping scheme. But I would settle if you have any explicit scheme to handle resting contacts. That said, I would be more than happy if you have a way of treating it generally (as continuous collision, instead of explicitly as a special state). Ideas I have tried: Using simultaneous position based error correction as described in the paper in section 5.3.2, turned out to be worse than the current scheme. If you want to know the parameters I used: Hexagons, side 50 (pixels) gravity 2400 (pixels/sec^2) time-step 1/60 (sec) beta 0.1 restitution 0 to 0.2 coeff. of friction 0.2 PGS iteration 10 initial separation 10 (pixels) mass 1 (unit is irrelevant for now, i modified velocity directly<-impulse method) inertia 1/1000 Thanks in advance! I really appreciate any help from you guys!! :) EDIT In response to Cholesky's comment about warm starting the solver and Baumgarte: Oh right, I forgot to mention! I do save the contact history and the impulse determined in this time step to be used as initial guess in the next time step. As for the Baumgarte, here's what actually happens in the code. Collision is detected when the bodies' closest distance is less than SKIN, meaning they are actually still separated. If at this moment, I used the PGS solver without Baumgarte, restitution of 0 alone would be able to stop the bodies, separated by a distance of ~SKIN, in mid-air! So this isn't right, I want to have the bodies touching each other. So I turn on the Baumgarte, where its role is actually to pull the bodies together! Weird I know, a scheme intended to push the body apart becomes useful for the reverse. Also, I found that if I increase the number of iteration to 100, stacks become much more stable, though the program becomes so slow. UPDATE Since the stack swings left and right, could it be something is wrong with my friction model? Current friction constraint: relative_tangential_velocity = 0

    Read the article

  • emo-framework in android move on collision of sprites with physics

    - by KaHeL
    I'm developing my first ever game for Android where I'm still learning about using of framework. To begin I made two sprites of ball where one ball is movable by dragging and another one is just standing on it's place on load. Now I've already added the collision listener for both sprites and as tested it's working properly. Now what I need to learn is on how can I add physics on both sprites where when they collide the standing sprite will move based on the physics and bounce around the screen. It would be best if you teach it to me step by step since I'm a little slow on this. Here's my nut so far: local stage = emo.Stage(); class Okay_1 { sprite = null; spriteok = null; dragStart = false; angle = 0; // Called when the stage is loaded function onLoad() { print("Level_1 is loaded!"); // Create new sprite and load 'f1.png' sprite = emo.Sprite("f1.png"); sprite.moveCenter(stage.getWindowWidth() * 0.5, stage.getWindowHeight() * 0.5); sprite.load(); spriteok = emo.Sprite("okay.png") spriteok.setWidth(100); spriteok.setHeight(100); spriteok.load(); // Check if the coordinate (X=100, Y=100) is inside the sprite if (spriteok.contains(100, 100)) { print("contains!"); } // Does the sprite collides with the other sprite? if (spriteok.collidesWith(sprite)) { print("collides!"); } } function onMotionEvent(ev) { if (ev.getAction() == MOTION_EVENT_ACTION_DOWN) { // Moves the sprite at the position of motion event angle = sprite.getAngle(); sprite.remove(); sprite = emo.Sprite("f2.png"); sprite.load(); sprite.rotate(angle); sprite.moveCenter(ev.getX(), ev.getY()); sprite.rotate(sprite.getAngle()+10); // Check if the coordinate (X=100, Y=100) is inside the sprite if (sprite.contains(sprite.getWidth(), sprite.getHeight())) { print("contains!"); } // Does the sprite collides with the other sprite? if (sprite.collidesWith(spriteok)) { print("collides!"); } dragStart = true; }else if (ev.getAction() == MOTION_EVENT_ACTION_MOVE) { if (dragStart) { // Moves the sprite at the position of motion event sprite.moveCenter(ev.getX(), ev.getY()); sprite.rotate(sprite.getAngle()+10); // Check if the coordinate (X=100, Y=100) is inside the sprite if (sprite.contains(sprite.getWidth(), sprite.getHeight())) { print("contains!"); } // Does the sprite collides with the other sprite? if (sprite.collidesWith(spriteok)) { print("collides!"); } } }else if (ev.getAction() == MOTION_EVENT_ACTION_UP || ev.getAction() == MOTION_EVENT_ACTION_CANCEL) { if (dragStart) { // change block color to red dragStart = false; angle = sprite.getAngle(); sprite.remove(); sprite = emo.Sprite("f1.png"); sprite.load(); sprite.moveCenter(ev.getX(), ev.getY()); sprite.rotate(angle); // Check if the coordinate (X=100, Y=100) is inside the sprite if (sprite.contains(sprite.getWidth(), sprite.getHeight())) { print("contains!"); } // Does the sprite collides with the other sprite? if (sprite.collidesWith(spriteok)) { print("collides!"); } } } } // Called when the stage is disposed function onDispose() { sprite.remove(); // Remove the sprite print("Level_1 is disposed!"); } } function emo::onLoad() { emo.Stage().load(Okay_1()); }

    Read the article

  • Minecraft style XNA game collision?

    - by Levi
    I've been trying to get this working for ages now, I can detect if there's a solid block at any place on the map and I can check how far something is inside of it, but I don't understand how to fix the collision. I've tried loads of ways and all of them end up by the player getting stuck, glitching around, incorrect responses and I really have no idea how to go about this :/. int Chnk = Utility.GetChunkFromPosition(origin); if (Chnk == -1) return; Vector3 Pos = Utility.GetCubeVectorFromPosition(origin); if (GlobalWorld.LoadedChunks[Chnk].Blocks[(byte)Pos.X, (byte)Pos.Y, (byte)Pos.Z] != 0) { isInIllegalState = true; if (velocity.Y < 0f) velocity.Y = 0f; } while (isInIllegalState) { if (GlobalWorld.LoadedChunks[Chnk].Blocks[(byte)Pos.X, (byte)origin.Y, (byte)Pos.Z] != 0) origin.Y = (int)(origin.Y + 1); else isInIllegalState = false; } if (origin.Y < Chunk.YSize - 2 && GlobalWorld.LoadedChunks[Chnk].Blocks[(byte)Pos.X, (byte)(origin.Y + playerHeight.Y), (byte)Pos.Z] != 0) { velocity.Y = 0f; //Acceleration.Y = 0f; origin.Y = (int)origin.Y;// -0.5f; } for (int x = -1; x <= 1; x+=2) { for (int z = -1; z <= 1; z += 2) { Vector3 CornerPosition = new Vector3(boundingSize * x, 0, boundingSize * z); bool CorrectX = false; bool CorrectZ = false; Vector3 RoundedOrigin = Utility.RoundVector(origin); Vector3 RoundedCorner = Utility.RoundVector(origin + CornerPosition); byte BlockAdjacent = Utility.GetCubeFromPosition(origin + CornerPosition); if (BlockAdjacent == 0) continue; if (RoundedCorner.X != RoundedOrigin.X && RoundedCorner.Z != RoundedOrigin.Z) { CorrectX = true; CorrectZ = true; } if (RoundedCorner.Z != RoundedOrigin.Z && RoundedCorner.X == RoundedOrigin.X) CorrectZ = true; if (RoundedCorner.X != RoundedOrigin.X && RoundedCorner.Z == RoundedOrigin.Z) CorrectX = true; if (CorrectX && CornerPosition.X > 0) { if (origin.X > 0f) origin.X = (int)(origin.X + 1) - boundingSize; else origin.X = (int)origin.X - boundingSize; } else if (CorrectX && CornerPosition.X < 0) { if (origin.X > 0f) origin.X = (int)(origin.X) + boundingSize; else origin.X = (int)(origin.X - 1) + boundingSize; } if (CorrectZ && CornerPosition.Z > 0) { if (origin.Z > 0f) origin.Z = (int)(origin.Z + 1) - boundingSize; else origin.Z = (int)origin.Z - boundingSize; } else if (CorrectZ && CornerPosition.Z < 0) { if (origin.Z > 0f) origin.Z = (int)(origin.Z) + boundingSize; else origin.Z = (int)(origin.Z - 1) + boundingSize; } } }

    Read the article

  • Android Bitmap : collision Detecting [on hold]

    - by user2505374
    I am writing an Android game right now and I would need some help in the collision of the wall on screen. When I drag the ball in the top and right it able to collide in wall but when I drag it faster it was able to overlap in the wall. public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { // if the player moves case MotionEvent.ACTION_MOVE: { if (playerTouchRect.contains(x, y)) { boolean left = false; boolean right = false; boolean up = false; boolean down = false; boolean canMove = false; boolean foundFinish = false; if (x != pLastXPos) { if (x < pLastXPos) { left = true; } else { right = true; } pLastXPos = x; } if (y != pLastYPos) { if (y < pLastYPos) { up = true; } else { down = true; } pLastYPos = y; } plCellRect = getRectFromPos(x, y); newplRect.set(playerRect); newplRect.left = x - (int) (playerRect.width() / 2); newplRect.right = x + (int) (playerRect.width() / 2); newplRect.top = y - (int) (playerRect.height() / 2); newplRect.bottom = y + (int) (playerRect.height() / 2); int currentRow = 0; int currentCol = 0; currentRow = getRowFromYPos(newplRect.top); currentCol = getColFromXPos(newplRect.right); if(!canMove){ canMove = mapManager.getCurrentTile().pMaze[currentRow][currentCol] == Cell.wall; canMove =true; } finishTest = mapManager.getCurrentTile().pMaze[currentRow][currentCol]; foundA = finishTest == Cell.valueOf(letterNotGet + ""); canMove = mapManager.getCurrentTile().pMaze[currentRow][currentCol] != Cell.wall; canMove = (finishTest == Cell.floor || finishTest == Cell.pl) && canMove; if (canMove) { invalidate(); setTitle(); } if (foundA) { mapManager.getCurrentTile().pMaze[currentRow][currentCol] = Cell.floor; // finishTest letterGotten.add(letterNotGet); playCurrentLetter(); /*sounds.play(sExplosion, 1.0f, 1.0f, 0, 0, 1.5f);*/ foundS = letterNotGet == 's'; letterNotGet++; }if(foundS){ AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity); builder.setTitle(mainActivity.getText(R.string.finished_title)); LayoutInflater inflater = mainActivity.getLayoutInflater(); View view = inflater.inflate(R.layout.finish, null); builder.setView(view); View closeButton =view.findViewById(R.id.closeGame); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View clicked) { if(clicked.getId() == R.id.closeGame) { mainActivity.finish(); } } }); AlertDialog finishDialog = builder.create(); finishDialog.show(); } else { Log.d(TAG, "INFO: updated player position"); playerRect.set(newplRect); setTouchZone(); updatePlayerCell(); } } // end of (CASE) if playerTouch break; } // end of (SWITCH) Case motion }//end of Switch return true; }//end of TouchEvent private void finish() { // TODO Auto-generated method stub } public int getColFromXPos(int xPos) { val = xPos / (pvWidth / mapManager.getCurrentTile().pCols); if (val == mapManager.getCurrentTile().pCols) { val = mapManager.getCurrentTile().pCols - 1; } return val; } /** * Given a y pixel position, return the row of the cell it is in This is * used when determining the type of adjacent Cells. * * @param yPos * y position in pixels * @return The cell this position is in */ public int getRowFromYPos(int yPos) { val = yPos / (pvHeight / mapManager.getCurrentTile().pRows); if (val == mapManager.getCurrentTile().pRows) { val = mapManager.getCurrentTile().pRows - 1; } return val; } /** * When preserving the position we need to know which cell the player is in, * so calculate it from the centre on its Rect */ public void updatePlayerCell() { plCell.x = (playerRect.left + (playerRect.width() / 2)) / (pvWidth / mapManager.getCurrentTile().pCols); plCell.y = (playerRect.top + (playerRect.height() / 2)) / (pvHeight / mapManager.getCurrentTile().pRows); if (mapManager.getCurrentTile().pMaze[plCell.y][plCell.x] == Cell.floor) { for (int row = 0; row < mapManager.getCurrentTile().pRows; row++) { for (int col = 0; col < mapManager.getCurrentTile().pCols; col++) { if (mapManager.getCurrentTile().pMaze[row][col] == Cell.pl) { mapManager.getCurrentTile().pMaze[row][col] = Cell.floor; break; } } } mapManager.getCurrentTile().pMaze[plCell.y][plCell.x] = Cell.pl; } } public Rect getRectFromPos(int x, int y) { calcCell.left = ((x / cellWidth) + 0) * cellWidth; calcCell.right = calcCell.left + cellWidth; calcCell.top = ((y / cellHeight) + 0) * cellHeight; calcCell.bottom = calcCell.top + cellHeight; Log.d(TAG, "Rect: " + calcCell + " Player: " + playerRect); return calcCell; } public void setPlayerRect(Rect newplRect) { playerRect.set(newplRect); } private void setTouchZone() { playerTouchRect.set( playerRect.left - playerRect.width() / TOUCH_ZONE, playerRect.top - playerRect.height() / TOUCH_ZONE, playerRect.right + playerRect.width() / TOUCH_ZONE, playerRect.bottom + playerRect.height() / TOUCH_ZONE); } public Rect getPlayerRect() { return playerRect; } public Point getPlayerCell() { return plCell; } public void setPlayerCell(Point cell) { plCell = cell; }

    Read the article

  • How to implement friction in a physics engine based on "Advanced Character Physics"

    - by paldepind
    I have implemented a physics engine based on the concepts in the classic text Advanced Character Physics by Thomas Jakobsen. Friction is only discussed very briefly in the article and Jakobsen himself notes how "other and better friction models than this could and should be implemented." Generally how could one implement a believable friction model on top of the concepts from the mentioned article? And how could the found friction be translated into rotation on a circle? I do not want this question to be about my specific implementation but about how to combine Jakobsens ideas with a great friction system more generally. But here is a live demo showing the current state of my engine which does not handle friction in any way: http://jsfiddle.net/Z7ECB/embedded/result/ Below is a picture showing and example on how collision detection could work in an engine based in the paper. In the Verlet integration the current and previous position is always stored. Based on these a new position is calculated. In every frame I calculate the distance between the circles and the lines. If this distance is less than a circles radius a collision has occurred and the circle is projected perpendicular out of the offending line according to the size of the overlap (offset on the picture). Velocity is implicit due to Verlet integration so changing position also changes the velocity. What I need to do know is to somehow determine the amount of friction on the circle and move it backwards parallel to the line in order to reduce its speed.

    Read the article

  • Integration error in high velocity

    - by Elektito
    I've implemented a simple simulation of two planets (simple 2D disks really) in which the only force is gravity and there is also collision detection/response (collisions are completely elastic). I can launch one planet into orbit of the other just fine. The collision detection code though does not work so well. I noticed that when one planet hits the other in a free fall it speeds backward and goes much higher than its original position. Some poking around convinced me that the simplistic Euler integration is causing the error. Consider this case. One object has a mass of 1kg and the other has a mass equal to earth. Say the object is 10 meters above ground. Assume that our dt (delta t) is 1 second. The object goes to the height of 9 meters at the end of the first iteration, 7 at the end of the second, 4 at the end of the third and 0 at the end of the fourth iteration. At this points it hits the ground and bounces back with the speed of 10 meters per second. The problem is with dt=1, on the first iteration it bounces back to a height of 10. It takes several more steps to make the object change its course. So my question is, what integration method can I use which fixes this problem. Should I split dt to smaller pieces when velocity is high? Or should I use another method altogether? What method do you suggest? EDIT: You can see the source code here at github:https://github.com/elektito/diskworld/

    Read the article

  • Detecting walls or floors in pygame

    - by Serial
    I am trying to make bullets bounce of walls, but I can't figure out how to correctly do the collision detection. What I am currently doing is iterating through all the solid blocks and if the bullet hits the bottom, top or sides, its vector is adjusted accordingly. However, sometimes when I shoot, the bullet doesn't bounce, I think it's when I shoot at a border between two blocks. Here is the update method for my Bullet class: def update(self, dt): if self.can_bounce: #if the bullet hasnt bounced find its vector using the mousclick pos and player pos speed = -10. range = 200 distance = [self.mouse_x - self.player[0], self.mouse_y - self.player[1]] norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2) direction = [distance[0] / norm, distance[1 ] / norm] bullet_vector = [direction[0] * speed, direction[1] * speed] self.dx = bullet_vector[0] self.dy = bullet_vector[1] #check each block for collision for block in self.game.solid_blocks: last = self.rect.copy() if self.rect.colliderect(block): topcheck = self.rect.top < block.rect.bottom and self.rect.top > block.rect.top bottomcheck = self.rect.bottom > block.rect.top and self.rect.bottom < block.rect.bottom rightcheck = self.rect.right > block.rect.left and self.rect.right < block.rect.right leftcheck = self.rect.left < block.rect.right and self.rect.left > block.rect.left each test tests if it hit the top bottom left or right side of the block its colliding with if self.can_bounce: if topcheck: self.rect = last self.dy *= -1 self.can_bounce = False print "top" if bottomcheck: self.rect = last self.dy *= -1 #Bottom check self.can_bounce = False print "bottom" if rightcheck: self.rect = last self.dx *= -1 #right check self.can_bounce = False print "right" if leftcheck: self.rect = last self.dx *= -1 #left check self.can_bounce = False print "left" else: # if it has already bounced and colliding again kill it self.kill() for enemy in self.game.enemies_list: if self.rect.colliderect(enemy): self.kill() #update position self.rect.x -= self.dx self.rect.y -= self.dy This definitely isn't the best way to do it but I can't think of another way. If anyone has done this or can help that would be awesome!

    Read the article

  • Almost working 2D Collisions

    - by TheGag96
    I'm terribly sorry I'm asking this question YET AGAIN, but I can almost guarantee that this will be the last time I'll have to ask. I'm currently on the verge of FINALLY getting these collisions to work for my game, made with libGDX in Java. My collisions use the same method as (and are basically copied and modified code from) the XNA Platformer example (here) where the direction of the collision is based on the rectangle where two objects are overlapping. The collisions themselves almost work perfectly, but for some reason, holding down/up and left and colliding with the floor/ceiling while doing so doesn't seem to work well. I'm not at all sure why. Instead of vaguely giving my problem and snippets of code, I've decided to instead provide a binary and the source of the game I have so far so you can see for yourself what my problem is. Link. (Note: make sure you unzip everything into a folder somewhere or it will not work) You'll find the collision code in the method workingCollisions() in Link.java. Please excuse the messy code and terrible graphics as this whole thing is in pre-pre-alpha. If anyone is kind enough and helps me out here, you are the best person ever. I'm completely desperate; I've been trying this on and off for months and I just can't get it to work. I cannot thank you enough.

    Read the article

  • Why does the player fall down when in between platforms? Tile based platformer

    - by inzombiak
    I've been working on a 2D platformer and have gotten the collision working, except for one tiny problem. My games a tile based platformer and whenever the player is in between two tiles, he falls down. Here is my code, it's fire off using an ENTER_FRAME event. It's only for collision from the bottom for now. var i:int; var j:int; var platform:Platform; var playerX:int = player.x/20; var playerY:int = player.y/20; var xLoopStart:int = (player.x - player.width)/20; var yLoopStart:int = (player.y - player.height)/20; var xLoopEnd:int = (player.x + player.width)/20; var yLoopEnd:int = (player.y + player.height)/20; var vy:Number = player.vy/20; var hitDirection:String; for(i = yLoopStart; i <= yLoopEnd; i++) { for(j = xLoopStart; j <= xLoopStart; j++) { if(platforms[i*36 + j] != null && platforms[i*36 + j] != 0) { platform = platforms[i*36 + j]; if(player.hitTestObject(platform) && i >= playerY) { hitDirection = "bottom"; } } } } This isn't the final version, going to replace hitTest with something more reliable , but this is an interesting problem and I'd like to know whats happening. Is my code just slow? Would firing off the code with a TIMER event fix it? Any information would be great.

    Read the article

  • How to handle circle penetration

    - by Kaertserif
    I've been working on cirlce to circle collision and have gotten the intersection method working correctly, but I'm having problems using the returned values to actually seperate the circles from one another. This is the method which calculates the depth of the circle collision public static Vector2 GetIntersectionDepth(Circle a, Circle b) { float xValue = a.Center.X - b.Center.X; float yValue = a.Center.Y - b.Center.Y; Vector2 depth = Vector2.Zero; float distance = Vector2.Distance(a.Center, b.Center); if (a.Radius + b.Radius > distance) { float result = (a.Radius + b.Radius) - distance; depth.X = (float)Math.Cos(result); depth.Y = (float)Math.Sin(result); } return depth; } This is where I'm trying to apply the values to actually seperate the circles. Vector2 depth = Vector2.Zero; for (int i = 0; i < circlePositions.Count; i++) { for (int j = 0; j < circlePositions.Count; j++) { Circle bounds1 = new Circle(circlePositions[i], circle.Width / 2); Circle bounds2 = new Circle(circlePositions[j], circle.Width / 2); if(i != j) depth = CircleToCircleIntersection.GetIntersectionDepth(bounds1, bounds2); if (depth != Vector2.Zero) { circlePositions[i] = new Vector2(circlePositions[i].X + depth.X, circlePositions[i].Y + depth.Y); } } } If you can offer any help in this I would really appreciate it.

    Read the article

  • 5 Free Intrusion Detection Softwares (IDS)

    Tools and Utilities to Monitor Your Network For Suspicious or Malicious Activity Snort for Windows Snort is an open source network intrusion detection system, capable of performing real-time traffi... [Author: Alam Je - Computers and Internet - March 24, 2010]

    Read the article

  • Temporary Post Used For Theme Detection (407391ef-2a52-4f66-86ce-ae972978f67d – 3bfe001a-32de-4114-a6b4-4005b770f6d7)

    - by Kavitha
    This is a temporary post that was not deleted. Please delete this manually. (de29367c-6ce5-4b1f-8b4a-a859ecde27a9 – 3bfe001a-32de-4114-a6b4-4005b770f6d7) This article titled,Temporary Post Used For Theme Detection (407391ef-2a52-4f66-86ce-ae972978f67d – 3bfe001a-32de-4114-a6b4-4005b770f6d7), was originally published at Tech Dreams. Grab our rss feed or fan us on Facebook to get updates from us.

    Read the article

  • Temporary Post Used For Theme Detection (be923fa6-3c12-49cc-ae55-c5fc02e681cb – 3bfe001a-32de-4114-a6b4-4005b770f6d7)

    - by Kavitha
    This is a temporary post that was not deleted. Please delete this manually. (19a474df-a007-467b-96e1-46716e6fae03 – 3bfe001a-32de-4114-a6b4-4005b770f6d7) This article titled,Temporary Post Used For Theme Detection (be923fa6-3c12-49cc-ae55-c5fc02e681cb – 3bfe001a-32de-4114-a6b4-4005b770f6d7), was originally published at Tech Dreams. Grab our rss feed or fan us on Facebook to get updates from us.

    Read the article

  • Temporary Post Used For Theme Detection (2c152d1d-b299-442d-8586-f901f2ae7155 – 3bfe001a-32de-4114-a6b4-4005b770f6d7)

    - by Gopinath
    This is a temporary post that was not deleted. Please delete this manually. (095f0c04-8773-4c8c-8925-410f694fb4f4 – 3bfe001a-32de-4114-a6b4-4005b770f6d7) This article titled,Temporary Post Used For Theme Detection (2c152d1d-b299-442d-8586-f901f2ae7155 – 3bfe001a-32de-4114-a6b4-4005b770f6d7), was originally published at Tech Dreams. Grab our rss feed or fan us on Facebook to get updates from us.

    Read the article

  • What's the best way to implement one-dimensional collision detection?

    - by cyclotis04
    I'm writing a piece of simulation software, and need an efficient way to test for collisions along a line. The simulation is of a train crossing several switches on a track. When a wheel comes within N inches of the switch, the switch turns on, then turns off when the wheel leaves. Since all wheels are the same size, and all switches are the same size, I can represent them as a single coordinate X along the track. Switch distances and wheel distances don't change in relation to each other, once set. This is a fairly trivial problem when done through brute force by placing the X coordinates in lists, and traversing them, but I need a way to do so efficiently, because it needs to be extremely accurate, even when the train is moving at high speeds. There's a ton of tutorials on 2D collision detection, but I'm not sure the best way to go about this unique 1D scenario.

    Read the article

  • Browser Detection, do's and don'ts. Is this ok?

    - by JCOC611
    So, I understand that browser detection (ie. navigator.userAgent) shouldn't be used to decide which object method/property to use; yet, I want to set some simple CSS with JavaScript depending on the browser. However, it's not enough to justify a completely new StyleSheet. So is it OK if I use Browser Detection to decide what CSS to apply to an element? EDIT Ok, let's be SPECIFIC. I'm talking about a text-shadow inside a button (<input type="button"/>) The text inside the button isn't vertically centered in all browsers, so I tweak this with JS depending on the browser.

    Read the article

  • Add collison detection to enemy sprites?

    - by xBroak
    i'd like to add the same collision detection used by the player sprite to the enemy sprites or 'creeps' ive added all the relevant code I can see yet collisons are still not being detected and handled, please find below the class, I have no idea what is wrong currently, the list of walls to collide with is 'wall_list' import pygame import pauseScreen as dm import re from pygame.sprite import Sprite from pygame import Rect, Color from random import randint, choice from vec2d import vec2d from simpleanimation import SimpleAnimation import displattxt black = (0,0,0) white = (255,255,255) blue = (0,0,255) green = (101,194,151) global currentEditTool currentEditTool = "Tree" global editMap editMap = False open('MapMaker.txt', 'w').close() def draw_background(screen, tile_img): screen.fill(black) img_rect = tile_img.get_rect() global rect rect = img_rect nrows = int(screen.get_height() / img_rect.height) + 1 ncols = int(screen.get_width() / img_rect.width) + 1 for y in range(nrows): for x in range(ncols): img_rect.topleft = (x * img_rect.width, y * img_rect.height) screen.blit(tile_img, img_rect) def changeTool(): if currentEditTool == "Tree": None elif currentEditTool == "Rock": None def pauseGame(): red = 255, 0, 0 green = 0,255, 0 blue = 0, 0,255 screen.fill(black) pygame.display.update() if editMap == False: choose = dm.dumbmenu(screen, [ 'Resume', 'Enable Map Editor', 'Quit Game'], 64,64,None,32,1.4,green,red) if choose == 0: print("hi") elif choose ==1: global editMap editMap = True elif choose ==2: print("bob") elif choose ==3: print("bob") elif choose ==4: print("bob") else: None else: choose = dm.dumbmenu(screen, [ 'Resume', 'Disable Map Editor', 'Quit Game'], 64,64,None,32,1.4,green,red) if choose == 0: print("Resume") elif choose ==1: print("Dis ME") global editMap editMap = False elif choose ==2: print("bob") elif choose ==3: print("bob") elif choose ==4: print("bob") else: None class Wall(pygame.sprite.Sprite): # Constructor function def __init__(self,x,y,width,height): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([width, height]) self.image.fill(green) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class insertTree(pygame.sprite.Sprite): def __init__(self,x,y,width,height, typ): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/map/tree.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class insertRock(pygame.sprite.Sprite): def __init__(self,x,y,width,height, typ): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/map/rock.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class Creep(pygame.sprite.Sprite): """ A creep sprite that bounces off walls and changes its direction from time to time. """ change_x=0 change_y=0 def __init__( self, screen, creep_image, explosion_images, field, init_position, init_direction, speed): """ Create a new Creep. screen: The screen on which the creep lives (must be a pygame Surface object, such as pygame.display) creep_image: Image (surface) object for the creep explosion_images: A list of image objects for the explosion animation. field: A Rect specifying the 'playing field' boundaries. The Creep will bounce off the 'walls' of this field. init_position: A vec2d or a pair specifying the initial position of the creep on the screen. init_direction: A vec2d or a pair specifying the initial direction of the creep. Must have an angle that is a multiple of 45 degres. speed: Creep speed, in pixels/millisecond (px/ms) """ Sprite.__init__(self) self.screen = screen self.speed = speed self.field = field self.rect = creep_image.get_rect() # base_image holds the original image, positioned to # angle 0. # image will be rotated. # self.base_image = creep_image self.image = self.base_image self.explosion_images = explosion_images # A vector specifying the creep's position on the screen # self.pos = vec2d(init_position) # The direction is a normalized vector # self.direction = vec2d(init_direction).normalized() self.state = Creep.ALIVE self.health = 15 def is_alive(self): return self.state in (Creep.ALIVE, Creep.EXPLODING) def changespeed(self,x,y): self.change_x+=x self.change_y+=y def update(self, time_passed, walls): """ Update the creep. time_passed: The time passed (in ms) since the previous update. """ if self.state == Creep.ALIVE: # Maybe it's time to change the direction ? # self._change_direction(time_passed) # Make the creep point in the correct direction. # Since our direction vector is in screen coordinates # (i.e. right bottom is 1, 1), and rotate() rotates # counter-clockwise, the angle must be inverted to # work correctly. # self.image = pygame.transform.rotate( self.base_image, -self.direction.angle) # Compute and apply the displacement to the position # vector. The displacement is a vector, having the angle # of self.direction (which is normalized to not affect # the magnitude of the displacement) # displacement = vec2d( self.direction.x * self.speed * time_passed, self.direction.y * self.speed * time_passed) self.pos += displacement # When the image is rotated, its size is changed. # We must take the size into account for detecting # collisions with the walls. # self.image_w, self.image_h = self.image.get_size() bounds_rect = self.field.inflate( -self.image_w, -self.image_h) if self.pos.x < bounds_rect.left: self.pos.x = bounds_rect.left self.direction.x *= -1 elif self.pos.x > bounds_rect.right: self.pos.x = bounds_rect.right self.direction.x *= -1 elif self.pos.y < bounds_rect.top: self.pos.y = bounds_rect.top self.direction.y *= -1 elif self.pos.y > bounds_rect.bottom: self.pos.y = bounds_rect.bottom self.direction.y *= -1 # collision detection old_x=bounds_rect.left new_x=old_x+self.direction.x bounds_rect.left = new_x # hit a wall? collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes bounds_rect.left=old_x old_y=self.pos.y new_y=old_y+self.direction.y self.pos.y = new_y collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.pos.y=old_y elif self.state == Creep.EXPLODING: if self.explode_animation.active: self.explode_animation.update(time_passed) else: self.state = Creep.DEAD self.kill() elif self.state == Creep.DEAD: pass #------------------ PRIVATE PARTS ------------------# # States the creep can be in. # # ALIVE: The creep is roaming around the screen # EXPLODING: # The creep is now exploding, just a moment before dying. # DEAD: The creep is dead and inactive # (ALIVE, EXPLODING, DEAD) = range(3) _counter = 0 def _change_direction(self, time_passed): """ Turn by 45 degrees in a random direction once per 0.4 to 0.5 seconds. """ self._counter += time_passed if self._counter > randint(400, 500): self.direction.rotate(45 * randint(-1, 1)) self._counter = 0 def _point_is_inside(self, point): """ Is the point (given as a vec2d) inside our creep's body? """ img_point = point - vec2d( int(self.pos.x - self.image_w / 2), int(self.pos.y - self.image_h / 2)) try: pix = self.image.get_at(img_point) return pix[3] > 0 except IndexError: return False def _decrease_health(self, n): """ Decrease my health by n (or to 0, if it's currently less than n) """ self.health = max(0, self.health - n) if self.health == 0: self._explode() def _explode(self): """ Starts the explosion animation that ends the Creep's life. """ self.state = Creep.EXPLODING pos = ( self.pos.x - self.explosion_images[0].get_width() / 2, self.pos.y - self.explosion_images[0].get_height() / 2) self.explode_animation = SimpleAnimation( self.screen, pos, self.explosion_images, 100, 300) global remainingCreeps remainingCreeps-=1 if remainingCreeps == 0: print("all dead") def draw(self): """ Blit the creep onto the screen that was provided in the constructor. """ if self.state == Creep.ALIVE: # The creep image is placed at self.pos. To allow for # smooth movement even when the creep rotates and the # image size changes, its placement is always # centered. # self.draw_rect = self.image.get_rect().move( self.pos.x - self.image_w / 2, self.pos.y - self.image_h / 2) self.screen.blit(self.image, self.draw_rect) # The health bar is 15x4 px. # health_bar_x = self.pos.x - 7 health_bar_y = self.pos.y - self.image_h / 2 - 6 self.screen.fill( Color('red'), (health_bar_x, health_bar_y, 15, 4)) self.screen.fill( Color('green'), ( health_bar_x, health_bar_y, self.health, 4)) elif self.state == Creep.EXPLODING: self.explode_animation.draw() elif self.state == Creep.DEAD: pass def mouse_click_event(self, pos): """ The mouse was clicked in pos. """ if self._point_is_inside(vec2d(pos)): self._decrease_health(3) #begin new player class Player(pygame.sprite.Sprite): change_x=0 change_y=0 frame = 0 def __init__(self,x,y): pygame.sprite.Sprite.__init__(self) # LOAD PLATER IMAGES # Set height, width self.images = [] for i in range(1,17): img = pygame.image.load("images/player/" + str(i)+".png").convert() #player images img.set_colorkey(white) self.images.append(img) self.image = self.images[0] self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x self.health = 15 self.image_w, self.image_h = self.image.get_size() health_bar_x = self.rect.x - 7 health_bar_y = self.rect.y - self.image_h / 2 - 6 screen.fill( Color('red'), (health_bar_x, health_bar_y, 15, 4)) screen.fill( Color('green'), ( health_bar_x, health_bar_y, self.health, 4)) def changespeed(self,x,y): self.change_x+=x self.change_y+=y def _decrease_health(self, n): """ Decrease my health by n (or to 0, if it's currently less than n) """ self.health = max(0, self.health - n) if self.health == 0: self._explode() def update(self,walls): # collision detection old_x=self.rect.x new_x=old_x+self.change_x self.rect.x = new_x # hit a wall? collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.rect.x=old_x old_y=self.rect.y new_y=old_y+self.change_y self.rect.y = new_y collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.rect.y=old_y # right to left if self.change_x < 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 # Grab the image, divide by 4 # every 4 frames. self.image = self.images[self.frame//4] # Move left to right. # images 4...7 instead of 0...3. if self.change_x > 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4] if self.change_y > 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4+4] if self.change_y < 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4+4+4] score = 0 # initialize pyGame pygame.init() # 800x600 sized screen global screen screen = pygame.display.set_mode([800, 600]) screen.fill(black) #bg_tile_img = pygame.image.load('images/map/grass.png').convert_alpha() #draw_background(screen, bg_tile_img) #pygame.display.flip() # Set title pygame.display.set_caption('Test') #background = pygame.Surface(screen.get_size()) #background = background.convert() #background.fill(black) # Create the player player = Player( 50,50 ) player.rect.x=50 player.rect.y=50 movingsprites = pygame.sprite.RenderPlain() movingsprites.add(player) # Make the walls. (x_pos, y_pos, width, height) global wall_list wall_list=pygame.sprite.RenderPlain() wall=Wall(0,0,10,600) # left wall wall_list.add(wall) wall=Wall(10,0,790,10) # top wall wall_list.add(wall) #wall=Wall(10,200,100,10) # poke wall wall_list.add(wall) wall=Wall(790,0,10,600) #(x,y,thickness, height) wall_list.add(wall) wall=Wall(10,590,790,10) #(x,y,thickness, height) wall_list.add(wall) f = open('MapMaker.txt') num_lines = sum(1 for line in f) print(num_lines) lineCount = 0 with open("MapMaker.txt") as infile: for line in infile: f = open('MapMaker.txt') print(line) coords = line.split(',') #print(coords[0]) #print(coords[1]) #print(coords[2]) #print(coords[3]) #print(coords[4]) if "tree" in line: print("tree in") wall=insertTree(int(coords[0]),int(coords[1]), int(coords[2]),int(coords[3]),coords[4]) wall_list.add(wall) elif "rock" in line: print("rock in") wall=insertRock(int(coords[0]),int(coords[1]), int(coords[2]),int(coords[3]),coords[4] ) wall_list.add(wall) width = 20 height = 540 height = height - 48 for i in range(0,23): width = width + 32 name = insertTree(width,540,790,10,"tree") #wall_list.add(name) name = insertTree(width,height,690,10,"tree") #wall_list.add(name) CREEP_SPAWN_TIME = 200 # frames creep_spawn = CREEP_SPAWN_TIME clock = pygame.time.Clock() bg_tile_img = pygame.image.load('images/map/grass.png').convert() img_rect = bg_tile_img FIELD_RECT = Rect(50, 50, 700, 500) CREEP_FILENAMES = [ 'images/player/1.png', 'images/player/1.png', 'images/player/1.png'] N_CREEPS = 3 creep_images = [ pygame.image.load(filename).convert_alpha() for filename in CREEP_FILENAMES] explosion_img = pygame.image.load('images/map/tree.png').convert_alpha() explosion_images = [ explosion_img, pygame.transform.rotate(explosion_img, 90)] creeps = pygame.sprite.RenderPlain() done = False #bg_tile_img = pygame.image.load('images/map/grass.png').convert() #draw_background(screen, bg_tile_img) totalCreeps = 0 remainingCreeps = 3 while done == False: creep_images = pygame.image.load("images/player/1.png").convert() creep_images.set_colorkey(white) draw_background(screen, bg_tile_img) if len(creeps) != N_CREEPS: if totalCreeps < N_CREEPS: totalCreeps = totalCreeps + 1 print(totalCreeps) creeps.add( Creep( screen=screen, creep_image=creep_images, explosion_images=explosion_images, field=FIELD_RECT, init_position=( randint(FIELD_RECT.left, FIELD_RECT.right), randint(FIELD_RECT.top, FIELD_RECT.bottom)), init_direction=(choice([-1, 1]), choice([-1, 1])), speed=0.01)) for creep in creeps: creep.update(60,wall_list) creep.draw() for event in pygame.event.get(): if event.type == pygame.QUIT: done=True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player.changespeed(-2,0) creep.changespeed(-2,0) if event.key == pygame.K_RIGHT: player.changespeed(2,0) creep.changespeed(2,0) if event.key == pygame.K_UP: player.changespeed(0,-2) creep.changespeed(0,-2) if event.key == pygame.K_DOWN: player.changespeed(0,2) creep.changespeed(0,2) if event.key == pygame.K_ESCAPE: pauseGame() if event.key == pygame.K_1: global currentEditTool currentEditTool = "Tree" changeTool() if event.key == pygame.K_2: global currentEditTool currentEditTool = "Rock" changeTool() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: player.changespeed(2,0) creep.changespeed(2,0) if event.key == pygame.K_RIGHT: player.changespeed(-2,0) creep.changespeed(-2,0) if event.key == pygame.K_UP: player.changespeed(0,2) creep.changespeed(0,2) if event.key == pygame.K_DOWN: player.changespeed(0,-2) creep.changespeed(0,-2) if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]: for creep in creeps: creep.mouse_click_event(pygame.mouse.get_pos()) if editMap == True: x,y = pygame.mouse.get_pos() if currentEditTool == "Tree": name = insertTree(x-10,y-25, 10 , 10, "tree") wall_list.add(name) wall_list.draw(screen) f = open('MapMaker.txt', "a+") image = pygame.image.load("images/map/tree.png").convert() screen.blit(image, (30,10)) pygame.display.flip() f.write(str(x) + "," + str(y) + ",790,10, tree\n") #f.write("wall=insertTree(" + str(x) + "," + str(y) + ",790,10)\nwall_list.add(wall)\n") elif currentEditTool == "Rock": name = insertRock(x-10,y-25, 10 , 10,"rock") wall_list.add(name) wall_list.draw(screen) f = open('MapMaker.txt', "a+") f.write(str(x) + "," + str(y) + ",790,10,rock\n") #f.write("wall=insertRock(" + str(x) + "," + str(y) + ",790,10)\nwall_list.add(wall)\n") else: None #pygame.display.flip() player.update(wall_list) movingsprites.draw(screen) wall_list.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit()

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >