Search Results

Search found 2138 results on 86 pages for 'daniel ball'.

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

  • 2d ball collision code problem XNA, over accelerated balls and stick together sometimes. help please? [closed]

    - by Sivan
    public static void Collision(Ball ball1, Ball ball2) { Vector3 x = new Vector3((ball1.BallPosition.X - ball2.BallPosition.X), (ball1.BallPosition.Y - ball2.BallPosition.Y), 0); x.Normalize(); Vector3 v1 = new Vector3(ball1.Speed, 0); float x1 = Vector3.Dot(x, v1); Vector3 v1x = x * x1; Vector3 v1y = v1 - v1x; x = -x; Vector3 v2 = new Vector3(ball2.Speed, 0); float x2 = Vector3.Dot(x, v2); Vector3 v2x = x * x2; Vector3 v2y = v2 - v2x; float m1 = 12, m2 = 4; float combinedMass = m1 + m2; Vector3 newVelA = (v1x * ((m1 - m2) / combinedMass)) + (v2x * ((2f * m2) / combinedMass)) + v1y; Vector3 newVelB = (v1x * ((2f * m1) / combinedMass)) + (v2x * ((m2 - m1) / combinedMass)) + v2y; ball1.Speed = new Vector2(newVelA.X, newVelA.Y); ball2.Speed = new Vector2(newVelB.X,newVelB.Y ); }

    Read the article

  • How do I count the times each number appears in columns of numbers?

    - by Andy C.
    I am sure this must be easy, but I am inexperienced. About the best way to think of my problem is to think of it as trying to sort and then count lottery numbers. To stay simple, let's do a Pick 3 game. Let's look at 10 drawings. I would split each drawn number into a separate column: DATE BALL#1 BALL#2 BALL#3 3/1 1 3 5 3/2 3 7 8 3/3 2 2 1 3/4 5 7 6 3/5 2 3 1 3/6 0 5 9 3/7 3 7 0 3/8 6 8 4 3/9 2 4 3 3/10 7 1 2 I would like to be able to build formulas into cells that would tell me how many times each number appeared overall, and how many times each number appeared in the position it occurred. Like this (using the above example): Number Overall Count Ball#1 Count Ball#2 Count Ball#3 Count 0 2 1 0 1 1 4 1 1 2 (That is, The number zero appears twice overall, and came up once as the first number drawn; zero times as the middle ball; and once as the third ball. Likewise, the number 1 was drawn four times in our 10-day period. It was the first ball once, the second ball once and the third ball twice.) And so on. All help appreciated. I have access to Excel and Microsoft Works, or of course if there is a Google Docs way to handle this All thanks for any help.

    Read the article

  • Pong Collision Help in C# w/ XNA

    - by Ramses Brown
    Edit: My goal is to have it function like this: Ball hits 1st Quarter = rebounds higher (aka Y++) Ball hits 2nd Quarter = rebounds higher (using random value) Ball hits 3rd Quarter = rebounds lower (using random value) Ball hits 4th Quarter = rebounds lower (aka Y--) I'm currently using Rectangle Collision for my collision detection, and it's worked. Now I wish to expand it. Instead of it simply detecting whether or not the paddle/ball intersect, I want to make it so that it can determine what section of the paddle gets hit. I wanted it in 4 parts, with each having a different reaction to impact. My first thought is to base it on the Ball's Y position compared to the Paddle's Y position. But since I want it in 4 parts, I don't know how to do that. So it's essentially be if (ball.Y > Paddle.Y) { PaddleSection1 == true; } Except modified so that instead of being top half/bottom half, it's 1st Quarter, etc.

    Read the article

  • Circle vs Edge collision detection / resolution

    - by topheman
    I made a javascript class Ball.js that handles physics interactions betweens balls as well as painting. In the v1.0, the ball vs ball collision detection and resolution is well handled. In the next version (v2), I'm trying to add edgeCollision handling. I'm having some problems, maybe you will be able to help me. All the v2 branch source code is on github repository : https://github.com/topheman/Ball.js/tree/v2 The v2 demos (where you can see the bug I will be talking about) : http://labs.topheman.com/Ball-v2/#help As you will see on the demo, I have two major problems that I'm having a really hard time to solve on Ball.js : method resolveEdgeCollision : bounce angle is inconsistent method checkEdgeCollision : if the ball's velocity (the length that it runs each frame) is higher than its diameter, eventually, it will pass through an edge, without triggering any collision Any Ideas ?...

    Read the article

  • Unity, Unrealistic Sphere On Inclined Plane

    - by user1086516
    So I am trying to model a ball rolling down an inclined surface in Unity based on what I am observing in real life but it is still quite off. In Unity it takes the ball about 3 seconds to travel from a place to another specified place where in real life it only takes 1 second. The ball isn't as fast to react to the incline as in real life (even though I have tried giving the ball and surface low or zero friction values) The ball does not accelerate as nearly as fast as it does in real life What do I do to give the ball more realistic behavior ? I have tried messing around with mass, physics materials, drag, and angular drag on the ball and surface but it doesn't seem to be helping.

    Read the article

  • What is causing this behavior with the movement of Pong Ball in 2D? [closed]

    - by thegermanpole
    //edit after running it through the debugger it turned out i had the display function set to x,x...TIL how to use a debugger I've been trying to teach myself C++ SDL with the lazyfoo tutorial and seem to have run into a roadblock. The code below is the movement function of my Dot class, which controls the ball. The ball seems to ignore yvel and moves with xvel to the bottom right. The code should be pretty readable, the rest of the relevant facts are: All variables are names Constants are in caps dotrad is the radius of my dot yvel and xvel are set to 5 in the constructor The dot is created at x and y equal to 100 When I comment out the x movement block it doesn't move, but if i comment out the y movement block, it keeps on going down to the right. void Dot::move() { if(((y+yvel+dotrad) <= SCREEN_HEIGHT) && (0 <= (y-dotrad+yvel))) { y+=yvel; } else { yvel = -1*yvel; } if(((x+xvel+dotrad) <= SCREEN_WIDTH) && (0 <= (x-dotrad+xvel))) { x +=xvel; } else { xvel = -1*xvel; } }

    Read the article

  • IPhone SDK help with minigame

    - by Harry
    right basically what ive got is an app which is a ball and bat and its how many bounces you can achieve, it works alright but there is one problem, when the ball hits the side of the bat it throws it off course and its like the frame of the ball is bouncing in the frame of the bat, Here is my code in my mainview.m #import "MainView.h" #define kGameStateRunning 1 @implementation MainView @synthesize paddle, ball; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject]; CGPoint location = [touch locationInView:touch.view]; CGPoint xLocation = CGPointMake(location.x,paddle.center.y); paddle.center = xLocation; } -(IBAction) play { pos = CGPointMake(14.0,7.0); [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer) userInfo:nil repeats:YES]; } -(void) onTimer { ball.center = CGPointMake(ball.center.x+pos.x,ball.center.y+pos.y); if(ball.center.x > 320 || ball.center.x < 0) pos.x = -pos.x; if(ball.center.y > 460 || ball.center.y < 0) pos.y = -pos.y; [self checkCollision]; } -(void) checkCollision { if(CGRectIntersectsRect(ball.frame,paddle.frame)) { pos.y = -pos.y; } } @end can anyone work out the problem here? Thanks Harry

    Read the article

  • refactoring this function in Java

    - by Joel
    Hi folks, I'm learning Java, and I know one of the big complaints about newbie programmers is that we make really long and involved methods that should be broken into several. Well here is one I wrote and is a perfect example. :-D. public void buildBall(){ /* sets the x and y value for the center of the canvas */ double i = ((getWidth() / 2)); double j = ((getHeight() / 2)); /* randomizes the start speed of the ball */ vy = 3.0; vx = rgen.nextDouble(1.0, 3.0); if (rgen.nextBoolean(.05)) vx = -vx; /* creates the ball */ GOval ball = new GOval(i,j,(2 *BALL_RADIUS),(2 * BALL_RADIUS)); ball.setFilled(true); ball.setFillColor(Color.RED); add(ball); /* animates the ball */ while(true){ i = (i + (vx* 2)); j = (j + (vy* 2)); if (i > APPLICATION_WIDTH-(2 * BALL_RADIUS)){ vx = -vx; } if (j > APPLICATION_HEIGHT-(2 * BALL_RADIUS)){ vy = -vy; } if (i < 0){ vx = -vx; } if (j < 0){ vy = -vy; } ball.move(vx + vx, vy + vy); pause(10); /* checks the edges of the ball to see if it hits an object */ colider = getElementAt(i, j); if (colider == null){ colider = getElementAt(i + (2*BALL_RADIUS), j); } if (colider == null){ colider = getElementAt(i + (2*BALL_RADIUS), j + (2*BALL_RADIUS)); } if (colider == null){ colider = getElementAt(i, j + (2*BALL_RADIUS)); } /* If the ball hits an object it reverses direction */ if (colider != null){ vy = -vy; /* removes bricks when hit but not the paddle */ if (j < (getHeight() -(PADDLE_Y_OFFSET + PADDLE_HEIGHT))){ remove(colider); } } } You can see from the title of the method that I started with good intentions of "building the ball". There are a few issues I ran up against: The problem is that then I needed to move the ball, so I created that while loop. I don't see any other way to do that other than just keep it "true", so that means any other code I create below this loop won't happen. I didn't make the while loop a different function because I was using those variables i and j. So I don't see how I can refactor beyond this loop. So my main question is: How would I pass the values of i and j to a new method: "animateBall" and how would I use ball.move(vx + vx, vy + vy); in that new method if ball has been declared in the buildBall method? I understand this is probably a simple thing of better understanding variable scope and passing arguments, but I'm not quite there yet...

    Read the article

  • Multiple enemy array in LibGDX

    - by johnny-b
    I am trying to make a multiple enemy array, where every 30 secods a new bullet comes from a random point. And if the bullet is clicked it should disapear and a pop like an explosion should appear. And if the bullet hits the ball then the ball pops. so the bullet should change to a different sprite or texture. same with the ball pop. But all that happens is the bullet if touched pops and nothing else happens. And if modified then the bullet keeps flashing as the update is way too much. I have added COMMENTS in the code to explain more on the issues. below is the code. if more code is needed i will provide. Thank you public class GameRenderer { private GameWorld myWorld; private OrthographicCamera cam; private ShapeRenderer shapeRenderer; private SpriteBatch batcher; // Game Objects private Ball ball; private ScrollHandler scroller; private Background background; private Bullet bullet1; private BulletPop bPop; private Array<Bullet> bullets; // This is for the delay of the bullet coming one by one every 30 seconds. /** The time of the last shot fired, we set it to the current time in nano when the object is first created */ double lastShot = TimeUtils.nanoTime(); /** Convert 30 seconds into nano seconds, so 30,000 milli = 30 seconds */ double shotFreq = TimeUtils.millisToNanos(30000); // Game Assets private TextureRegion bg, bPop; private Animation bulletAnimation, ballAnimation; private Animation ballPopAnimation; public GameRenderer(GameWorld world) { myWorld = world; cam = new OrthographicCamera(); cam.setToOrtho(true, 480, 320); batcher = new SpriteBatch(); // Attach batcher to camera batcher.setProjectionMatrix(cam.combined); shapeRenderer = new ShapeRenderer(); shapeRenderer.setProjectionMatrix(cam.combined); // This is suppose to produce 10 bullets at random places on the background. bullets = new Array<Bullet>(); Bullet bullet = null; float bulletX = 00.0f; float bulletY = 00.0f; for (int i = 0; i < 10; i++) { bulletX = MathUtils.random(-10, 10); bulletY = MathUtils.random(-10, 10); bullet = new Bullet(bulletX, bulletY); AssetLoader.bullet1.flip(true, false); AssetLoader.bullet2.flip(true, false); bullets.add(bullet); } // Call helper methods to initialize instance variables initGameObjects(); initAssets(); } private void initGameObjects() { ball = GameWorld.getBall(); bullet1 = myWorld.getBullet1(); bPop = myWorld.getBulletPop(); scroller = myWorld.getScroller(); } private void initAssets() { bg = AssetLoader.bg; ballAnimation = AssetLoader.ballAnimation; bullet1Animation = AssetLoader.bullet1Animation; ballPopAnimation = AssetLoader.ballPopAnimation; } // This is to take the bullet away when clicked or touched. public void onClick() { for (int i = 0; i < bullets.size; i++) { if (bullets.get(i).getBounds().contains(0, 0)) bullets.removeIndex(i); } } private void drawBackground() { batcher.draw(bg1, background.getX(), background.getY(), background.getWidth(), backgroundMove.getHeight()); } public void render(float runTime) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT); batcher.begin(); // Disable transparency // This is good for performance when drawing images that do not require // transparency. batcher.disableBlending(); drawBackground(); batcher.enableBlending(); // when the bullet hits the ball, it should be disposed or taken away and a ball pop sprite/texture should be put in its place if (bullet1.collides(ball)) { // draws the bPop texture but the bullet does not go just keeps going around, and the bPop texture goes. batcher.draw(AssetLoader.bPop, 195, 273); } batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight()); // this is where i am trying to make the bullets come one by one, and if removed via the onClick() then bPop animation // should play but does not??? if(TimeUtils.nanoTime() - lastShot > shotFreq){ // Create your stuff for (int i = 0; i < bullets.size; i++) { bullets.get(i); batcher.draw(AssetLoader.bullet1Animation.getKeyFrame(runTime), bullet1.getX(), bullet1.getY(), bullet1.getOriginX(), bullet1.getOriginY(), bullet1.getWidth(), bullet1.getHeight(), 1.0f, 1.0f, bullet1.getRotation()); if (bullets.removeValue(bullet1, false)) { batcher.draw(AssetLoader.ballPopAnimation.getKeyFrame(runTime), bPop1.getX(), bPop1.getY(), bPop1.getWidth(), bPop1.getHeight()); } } /* Very important to set the last shot to now, or it will mess up and go full auto */ lastShot = TimeUtils.nanoTime(); } // End SpriteBatch batcher.end(); } } Thank you

    Read the article

  • Un plugin jQuery multitâche : méthode de construction personnelle et exemples. Adapter jQuery à vos besoins, niveau 2, par Daniel Hagnoul

    Plugin multitâche : méthode de construction personnelle et exemples Adapter jQuery à vos besoins, niveau 2 Résumé : La plupart des plugins exécutent une seule tâche et les méthodes d'écriture de plugin utilisées dans « Mon Cahier d'exercices », dans la FAQ jQuery et dans l'article « Adapter jQuery à vos besoins » couvrent la majorité des besoins. Lorsque l'on souhaite inclure la modification des options et implémenter plusieurs méthodes on doit penser multitâche . Dans cet ...

    Read the article

  • 2D Smooth Turning in a Tile-Based Game

    - by ApoorvaJ
    I am working on a 2D top-view grid-based game. A ball that rolls on the grid made up of different tiles. The tiles interact with the ball in a variety of ways. I am having difficulty cleanly implementing the turning tile. The image below represents a single tile in the grid, which turns the ball by a right angle. If the ball rolls in from the bottom, it smoothly changes direction and rolls to the right. If it rolls in from the right, it is turned smoothly to the bottom. If the ball rolls in from top or left, its trajectory remains unchanged by the tile. The tile shouldn't change the magnitude of the velocity of the ball - only change its direction. The ball has Velocity and Position vectors, and the tile has Position and Dimension vectors. I have already implemented this, but the code is messy and buggy. What is an elegant way to achieve this, preferably by modification of the ball's Velocity vector by a formula?

    Read the article

  • Android draw using SurfaceView and Thread

    - by Morten Høgseth
    I am trying to draw a ball to my screen using 3 classes. I have read a little about this and I found a code snippet that works using the 3 classes on one page, Playing with graphics in Android I altered the code so that I have a ball that is moving and shifts direction when hitting the wall like the picture below (this is using the code in the link). Now I like to separate the classes into 3 different pages for not making everything so crowded, everything is set up the same way. Here are the 3 classes I have. BallActivity.java Ball.java BallThread.java package com.brick.breaker; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class BallActivity extends Activity { private Ball ball; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); ball = new Ball(this); setContentView(ball); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); setContentView(null); ball = null; finish(); } } package com.brick.breaker; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.view.SurfaceHolder; import android.view.SurfaceView; public class Ball extends SurfaceView implements SurfaceHolder.Callback { private BallThread ballThread = null; private Bitmap bitmap; private float x, y; private float vx, vy; public Ball(Context context) { super(context); // TODO Auto-generated constructor stub bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ball); x = 50.0f; y = 50.0f; vx = 10.0f; vy = 10.0f; getHolder().addCallback(this); ballThread = new BallThread(getHolder(), this); } protected void onDraw(Canvas canvas) { update(canvas); canvas.drawBitmap(bitmap, x, y, null); } public void update(Canvas canvas) { checkCollisions(canvas); x += vx; y += vy; } public void checkCollisions(Canvas canvas) { if(x - vx < 0) { vx = Math.abs(vx); } else if(x + vx > canvas.getWidth() - getBitmapWidth()) { vx = -Math.abs(vx); } if(y - vy < 0) { vy = Math.abs(vy); } else if(y + vy > canvas.getHeight() - getBitmapHeight()) { vy = -Math.abs(vy); } } public int getBitmapWidth() { if(bitmap != null) { return bitmap.getWidth(); } else { return 0; } } public int getBitmapHeight() { if(bitmap != null) { return bitmap.getHeight(); } else { return 0; } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub ballThread.setRunnable(true); ballThread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub boolean retry = true; ballThread.setRunnable(false); while(retry) { try { ballThread.join(); retry = false; } catch(InterruptedException ie) { //Try again and again and again } break; } ballThread = null; } } package com.brick.breaker; import android.graphics.Canvas; import android.view.SurfaceHolder; public class BallThread extends Thread { private SurfaceHolder sh; private Ball ball; private Canvas canvas; private boolean run = false; public BallThread(SurfaceHolder _holder,Ball _ball) { sh = _holder; ball = _ball; } public void setRunnable(boolean _run) { run = _run; } public void run() { while(run) { canvas = null; try { canvas = sh.lockCanvas(null); synchronized(sh) { ball.onDraw(canvas); } } finally { if(canvas != null) { sh.unlockCanvasAndPost(canvas); } } } } public Canvas getCanvas() { if(canvas != null) { return canvas; } else { return null; } } } Here is a picture that shows the outcome of these classes. I've tried to figure this out but since I am pretty new to Android development I thought I could ask for help. Does any one know what is causing the ball to be draw like that? The code is pretty much the same as the one in the link and I have tried to experiment to find a solution but no luck. Thx in advance for any help=)

    Read the article

  • Single player 'pong' game

    - by Jam
    I am just starting out learning pygame and livewires, and I'm trying to make a single-player pong game, where you just hit the ball, and it bounces around until it passes your paddle (located on the left side of the screen and controlled by the mouse), which makes you lose. I have the basic code, but the ball doesn't stay on the screen, it just flickers and doesn't remain constant. Also, the paddle does not move with the mouse. I'm sure I'm missing something simple, but I just can't figure it out. Help please! Here's what I have: from livewires import games import random games.init(screen_width=640, screen_height=480, fps=50) class Paddle(games.Sprite): image=games.load_image("paddle.bmp") def __init__(self, x=10): super(Paddle, self).__init__(image=Paddle.image, y=games.mouse.y, left=10) self.score=games.Text(value=0, size=25, top=5, right=games.screen.width - 10) games.screen.add(self.score) def update(self): self.y=games.mouse.y if self.top<0: self.top=0 if self.bottom>games.screen.height: self.bottom=games.screen.height self.check_collide() def check_collide(self): for ball in self.overlapping_sprites: self.score.value+=1 ball.handle_collide() class Ball(games.Sprite): image=games.load_image("ball.bmp") speed=5 def __init__(self, x=90, y=90): super(Ball, self).__init__(image=Ball.image, x=x, y=y, dx=Ball.speed, dy=Ball.speed) def update(self): if self.right>games.screen.width: self.dx=-self.dx if self.bottom>games.screen.height or self.top<0: self.dy=-self.dy if self.left<0: self.end_game() self.destroy() def handle_collide(self): self.dx=-self.dx def end_game(self): end_message=games.Message(value="Game Over", size=90, x=games.screen.width/2, y=games.screen.height/2, lifetime=250, after_death=games.screen.quit) games.screen.add(end_message) def main(): background_image=games.load_image("background.bmp", transparent=False) games.screen.background=background_image paddle_image=games.load_image("paddle.bmp") the_paddle=games.Sprite(image=paddle_image, x=10, y=games.mouse.y) games.screen.add(the_paddle) ball_image=games.load_image("ball.bmp") the_ball=games.Sprite(image=ball_image, x=630, y=200, dx=2, dy=2) games.screen.add(the_ball) games.mouse.is_visible=False games.screen.event_grab=True games.screen.mainloop() main()

    Read the article

  • Using elapsed time for SlowMo in XNA

    - by Dave Voyles
    I'm trying to create a slow-mo effect in my pong game so that when a player is a button the paddles and ball will suddenly move at a far slower speed. I believe my understanding of the concepts of adjusting the timing in XNA are done, but I'm not sure of how to incorporate it into my design exactly. The updates for my bats (paddles) are done in my Bat.cs class: /// Controls the bat moving up the screen /// </summary> public void MoveUp() { SetPosition(Position + new Vector2(0, -moveSpeed)); } /// <summary> /// Controls the bat moving down the screen /// </summary> public void MoveDown() { SetPosition(Position + new Vector2(0, moveSpeed)); } /// <summary> /// Updates the position of the AI bat, in order to track the ball /// </summary> /// <param name="ball"></param> public virtual void UpdatePosition(Ball ball) { size.X = (int)Position.X; size.Y = (int)Position.Y; } While the rest of my game updates are done in my GameplayScreen.cs class (I'm using the XNA game state management sample) Class GameplayScreen { ........... bool slow; .......... public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) base.Update(gameTime, otherScreenHasFocus, false); if (IsActive) { // SlowMo Stuff Elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; if (Slowmo) Elapsed *= .8f; MoveTimer += Elapsed; double elapsedTime = gameTime.ElapsedGameTime.TotalMilliseconds; if (Keyboard.GetState().IsKeyDown(Keys.Up)) slow = true; else if (Keyboard.GetState().IsKeyDown(Keys.Down)) slow = false; if (slow == true) elapsedTime *= .1f; // Updating bat position leftBat.UpdatePosition(ball); rightBat.UpdatePosition(ball); // Updating the ball position ball.UpdatePosition(); and finally my fixed time step is declared in the constructor of my Game1.cs Class: /// <summary> /// The main game constructor. /// </summary> public Game1() { IsFixedTimeStep = slow = false; } So my question is: Where do I place the MoveTimer or elapsedTime, so that my bat will slow down accordingly?

    Read the article

  • Pong: How does the paddle know where the ball will hit?

    - by Roflcoptr
    After implementing Pacman and Snake I'm implementing the next very very classic game: Pong. The implementation is really simple, but I just have one little problem remaining. When one of the paddle (I'm not sure if it is called paddle) is controlled by the computer, I have trouble to position it at the correct position. The ball has a current position, a speed (which for now is constant) and a direction angle. So I could calculate the position where it will hit the side of the computer controlled paddle. And so Icould position the paddle right there. But however in the real game, there is a probability that the computer's paddle will miss the ball. How can I implement this probability? If I only use a probability of lets say 0.5 that the computer's paddle will hit the ball, the problem is solved, but I think it isn't that simple. From the original game I think the probability depends on the distance between the current paddle position and the position the ball will hit the border. Does anybody have any hints how exactly this is calculated?

    Read the article

  • Calculate angle of moving ball after collision with angled or sloped wall that is a 2D line segment

    - by Ben Mc
    If you have a "ball" inside a 2D polygon, made up of say, 4 line segments that act as bounding walls, how do you calculate the angle of the ball after the collision with the irregularly sloped wall? I know how to make the ball bounce if the wall is horizontal, vertical, or at a 45 degree angle. I also have my code setup to detect a collision with the wall. I've read about dot products and normals, but I cannot figure out how to implement these in Java / Android. I'm completely stumped and feel like I've looked up everything 10 pages deep in Google 10 times now. I'm burned out trying to figure this out, I hope someone can help.

    Read the article

  • Single-player pong game

    - by Jam
    I am just starting out learning pygame and livewires, and I'm trying to make a single-player pong game, where you just hit the ball, and it bounces around until it passes your paddle (located on the left side of the screen and controlled by the mouse), which makes you lose. However, I keep getting the error: "Cannot have more than on Screen object", which I can find no references to online really, and I can't make sense of it. I want to eventually make the game more complicated, but I need to make it work first. Help please! Here's the code so far: from livewires import games games.init(screen_width=640, screen_height=480, fps=50) class Paddle(games.Sprite): image=games.load_image("paddle.bmp") def __init__(self): super(Paddle, self).__init__(image=Paddle.image, y=games.mouse.y, left=0) self.score=games.Text(value=0, size=25, top=5, right=games.screen.width-10) games.screen.add(self.score) def update(self): self.y=games.mouse.y self.check_collide() def check_collide(self): for ball in self.overlapping_sprites: self.score.value+=1 self.score.right=games.screen.width-10 ball.handle_collide() class Ball(games.Sprite): image=games.load_image("ball.bmp") speed=1 def __init__(self, x, y=90): super(Ball, self).__init__(image=Ball.image, x=x, y=y, dx=Ball.speed, dy=Ball.speed) def update(self): if self.left<0: self.end_game() self.destroy() def handle_collide(self): if self.right>games.screen.width: self.dx=-self.dx if self.bottom>games.screen.height or self.top<0: self.dy=-self.dy def ball_destroy(self): self.destroy() def main(): background_image=games.load_image("background.bmp", transparent=False) games.screen.background=background_image the_ball=Ball() games.screen.add(the_ball) the_paddle=Paddle() games.screen.add(the_paddle) games.mouse.is_visible=False games.screen.event_grab=True games.screen.mainloop() main()

    Read the article

  • Winforms: calling entry form function from a different class

    - by samy
    I'm kinda new to programming and got a question on what is a good practice. I created a class that represents a ball and it has a function Jump() that use 2 timers and get the ball up and down. I know that in Winforms you got to call Invalidate() every time you want to repaint the screen, or part of it. I didn't find a good way to do that, so I reference the form in my class, and called Invalidate() inside my ball class every time I need to repaint to ball movement. (this works but I got a feeling that this is not a good practice) Here is the class I created: public class Ball { public Form1 parent;//----> here is the reference to the form public Rectangle ball; Size size; public Point p; Timer timerBallGoUp = new Timer(); Timer timerBallGDown = new Timer(); public int ballY; public Ball(Size _size, Point _p) { size = _size; p = _p; ball = new Rectangle(p, size); } public void Jump() { ballY = p.Y; timerBallGDown.Elapsed += ballGoDown; timerBallGDown.Interval = 50; timerBallGoUp.Elapsed += ballGoUp; timerBallGoUp.Interval = 50; timerBallGoUp.Start(); } private void ballGoUp(object obj,ElapsedEventArgs e) { p.Y++; ball.Location = new Point(ball.Location.X, p.Y); if (p.Y >= ballY + 50) { timerBallGoUp.Stop(); timerBallGDown.Start(); } parent.Invalidate(); // here i call parent.Invalidate() 1 } private void ballGoDown(object obj, ElapsedEventArgs e) { p.Y--; ball.Location = new Point(ball.Location.X, p.Y); if (p.Y <= ballY) { timerBallGDown.Stop(); timerBallGoUp.Start(); } parent.Invalidate(); // here i call parent.Invalidate() 2 } } I'm wondring if there is a better way to do that? (sorry for my english)

    Read the article

  • SetInterval missing property in js class

    - by sebastian
    I wrote simple class in JS witch works, but i had problem when i try use setInterval with it. Ex. if i do something like that ball = new ball(5,10,0, '#canvas'); ball.draw(); ball.draw(); ball.draw(); ball.draw(); It works. But this: ball = new ball(5,10,0, '#canvas'); setInterval(ball.draw, 100); Not work. I get error that values are undefined. function ball (x,y,z,holdingEl) { this.r = 5; //zmienna przechowujaca promien pilki this.size = this.r *2; // zmienna przechowujaca rozmiar this.ballSpeed = 100; // predkosc pilki this.ballWeight = 0.45; // masa pilki this.maxFootContactTime = 0.2; // maksymalny czas kontaktu pilki z noga - stala this.ctx = jQuery(holdingEl)[0].getContext("2d"); // obiekt pilki this.intVal = 100 // predkosc odswiezania this.currentPos = { // wspolrzedne pozycji x: x, y: y, z: z } this.interactionPos = { // wspolrzedne pozycji ostatniej interakcji x: -1, y: -1, z: -1 } this.direct = { // kierunek w kazdej plaszczyznie x : 1, y : 0, z : 0 } this.draw = function (){ this.ctx.clearRect(0,0,1100,800); this.ctx.beginPath(); this.ctx.arc(this.currentPos.x, this.currentPos.y, this.r, 0, Math.PI*2, true); this.ctx.closePath(); this.ctx.fill(); } }

    Read the article

  • Why does Java think my object is a variable?

    - by user2896898
    Ok so I'm trying to make a simple pong game. I have a paddle that follows the mouse and a ball that bounces around. I wrote a method collidesWith(Sprite s) inside of my Sprite class that checks if the ball collides with the paddle (this works and isn't the problem). I have two objects extending my sprite class, a ball and a paddle object. So inside of my ball class I'm trying to check if it collides with the paddle. So I've tried if(this.collidesWith(paddle) == true){ System.out.println("They touched"); } I've also tried ball.collidesWith(paddle) and other combinations but it always says the same thing about the paddle (and the ball when I use ball.collidesWith) "Cannot find symbol. Symbol: variable paddle(or ball). Location: class Ball" So if I'm reading this right, it thinks that the paddle (and ball) are variables and it's complaining because it can't find them. How can I make it understand I am passing in objects, not variables? For extra information, an earlier assignment had me make two boxes and for them to change colors when they were colliding. In that assignment I used very similar code to above with if(boxOne.collidesWith(boxTwo) == true){ System.out.println("yes"); } And in this code it worked just fine. The program knew that boxOne and boxTwo were child classes of my Sprite class. Anyone know why they wouldn't work the same?

    Read the article

  • Physics System ignores collision in some rare cases

    - by Gajoo
    I've been developing a simple physics engine for my game. since the game physics is very simple I've decided to increase accuracy a little bit. Instead of formal integration methods like fourier or RK4, I'm directly computing the results after delta time "dt". based on the very first laws of physics : dx = 0.5 * a * dt^2 + v0 * dt dv = a * dt where a is acceleration and v0 is object's previous velocity. Also to handle collisions I've used a method which is somehow different from those I've seen so far. I'm detecting all the collision in the given time frame, stepping the world forward to the nearest collision, resolving it and again check for possible collisions. As I said the world consist of very simple objects, so I'm not loosing any performance due to multiple collision checking. First I'm checking if the ball collides with any walls around it (which is working perfectly) and then I'm checking if it collides with the edges of the walls (yellow points in the picture). the algorithm seems to work without any problem except some rare cases, in which the collision with points are ignored. I've tested everything and all the variables seem to be what they should but after leaving the system work for a minute or two the system the ball passes through one of those points. Here is collision portion of my code, hopefully one of you guys can give me a hint where to look for a potential bug! void PhysicalWorld::checkForPointCollision(Vec2 acceleration, PhysicsComponent& ball, Vec2& collisionNormal, float& collisionTime, Vec2 target) { // this function checks if there will be any collision between a circle and a point // ball contains informations about the circle (it's current velocity, position and radius) // collisionNormal is an output variable // collisionTime is also an output varialbe // target is the point I want to check for collisions Vec2 V = ball.mVelocity; Vec2 A = acceleration; Vec2 P = ball.mPosition - target; float wallWidth = mMap->getWallWidth() / (mMap->getWallWidth() + mMap->getHallWidth()) / 2; float r = ball.mRadius / (mMap->getWallWidth() + mMap->getHallWidth()); // r is ball radius scaled to match actual rendered object. if (A.any()) // todo : I need to first correctly solve the collisions in case there is no acceleration return; if (V.any()) // if object is not moving there will be no collisions! { float D = P.x * V.y - P.y * V.x; float Delta = r*r*V.length2() - D*D; if(Delta < eps) return; Delta = sqrt(Delta); float sgnvy = V.y > 0 ? 1: (V.y < 0?-1:0); Vec2 c1(( D*V.y+sgnvy*V.x*Delta) / V.length2(), (-D*V.x+fabs(V.y)*Delta) / V.length2()); Vec2 c2(( D*V.y-sgnvy*V.x*Delta) / V.length2(), (-D*V.x-fabs(V.y)*Delta) / V.length2()); float t1 = (c1.x - P.x) / V.x; float t2 = (c2.x - P.x) / V.x; if(t1 > eps && t1 <= collisionTime) { collisionTime = t1; collisionNormal = c1; } if(t2 > eps && t2 <= collisionTime) { collisionTime = t2; collisionNormal = c2; } } } // this function should step the world forward by dt. it doesn't check for collision of any two balls (components) // it just checks if there is a collision between the current component and 4 points forming a rectangle around it. void PhysicalWorld::step(float dt) { for (unsigned i=0;i<mObjects.size();i++) { PhysicsComponent &current = *mObjects[i]; Vec2 acceleration = current.mForces * current.mInvMass; float rt=dt; // stores how much more the world should advance while(rt > eps) { float collisionTime = rt; Vec2 collisionNormal = Vec2(0,0); float halfWallWidth = mMap->getWallWidth() / (mMap->getWallWidth() + mMap->getHallWidth()) / 2; // we check if there is any collision with any of those 4 points around the ball // if there is a collision both collisionNormal and collisionTime variables will change // after these functions collisionTime will be exactly the value of nearest collision (if any) // and if there was, collisionNormal will report in which direction the ball should return. checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2(floor(current.mPosition.x) + halfWallWidth,floor(current.mPosition.y) + halfWallWidth)); checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2(floor(current.mPosition.x) + halfWallWidth, ceil(current.mPosition.y) - halfWallWidth)); checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2( ceil(current.mPosition.x) - halfWallWidth,floor(current.mPosition.y) + halfWallWidth)); checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2( ceil(current.mPosition.x) - halfWallWidth, ceil(current.mPosition.y) - halfWallWidth)); // either if there is a collision or if there is not we step the forward since we are sure there will be no collision before collisionTime current.mPosition += collisionTime * (collisionTime * acceleration * 0.5 + current.mVelocity); current.mVelocity += collisionTime * acceleration; // if the ball collided with anything collisionNormal should be at least none zero in one of it's axis if (collisionNormal.any()) { collisionNormal *= Dot(collisionNormal, current.mVelocity) / collisionNormal.length2(); current.mVelocity -= 2 * collisionNormal; // simply reverse velocity along collision normal direction } rt -= collisionTime; } // reset all forces for current object so it'll be ready for later game event current.mForces.zero(); } }

    Read the article

  • How to get colliding effect or bouncy when ball hits the track.

    - by Chandan Shetty SP
    I am using below formula to move the ball circular, where accelX and accelY are the values from accelerometer, it is working fine. But the problem in this code is mRadius (I fixed its value to 50), i need to change mRadius according to accelerometer values and also i need bouncing effect when it touches the track. Currently i am developing code by assuming only one ball is on the board. float degrees = -atan2(accelX, accelY) * 180 / 3.14159; int x = cCentrePoint.x + mRadius * cos(degreesToRadians(degrees)); int y = cCentrePoint.y + mRadius * sin(degreesToRadians(degrees)); Here is the snap of the game i want to develop: Updated: I am sending the updated code... mRadius = 5; mRange = NSMakeRange(0,60); -(void) updateBall: (UIAccelerationValue) accelX withY:(UIAccelerationValue)accelY { float degrees = -atan2(accelX, accelY) * 180 / 3.14159; int x = cCentrePoint.x + mRadius * cos(degreesToRadians(degrees)); int y = cCentrePoint.y + mRadius * sin(degreesToRadians(degrees)); //self.targetRect is rect of ball Object self.targetRect = CGRectMake(newX, newY, 8, 9); self.currentRect = self.targetRect; //http://books.google.co.in/books?id=WV9glgdrrrUC&pg=PA455#v=onepage&q=&f=false static NSDate *lastDrawTime; if(lastDrawTime!=nil) { NSTimeInterval secondsSinceLastDraw = -([lastDrawTime timeIntervalSinceNow]); ballXVelocity = ballXVelocity + (accelX * secondsSinceLastDraw) * [self isTouchedTrack:mRadius andRange:mRange]; ballYVelocity = ballYVelocity + -(accelY * secondsSinceLastDraw) * [self isTouchedTrack:mRadius andRange:mRange]; distXTravelled = distXTravelled + secondsSinceLastDraw * ballXVelocity * 50; distYTravelled = distYTravelled + secondsSinceLastDraw * ballYVelocity * 50; CGRect temp = self.targetRect; temp.origin.x += distXTravelled; temp.origin.y += distYTravelled; int radius = (temp.origin.x - cCentrePoint.x) / cos(degreesToRadians(degrees)); if( !NSLocationInRange(abs(radius),mRange)) { //Colided with the tracks...Need a better logic here ballXVelocity = -ballXVelocity; } else { // Need a better logic here self.targetRect = temp; } //NSLog(@"angle = %f",degrees); } [lastDrawTime release]; lastDrawTime = [ [NSDate alloc] init]; } In the above code i have initialized mRadius and mRange(indicate track) to some constant for testing, i am not getting the moving of the ball as i expected( bouncing effect when Collided with track ) with respect to accelerometer. Help me to recognize where i went wrong or send some code snippets or links which does the similar job. I am searching for better logic than my code, if you found share with me.

    Read the article

  • jqGrid concatinating/building html tag incorrectly

    - by Energetic Pixels
    Please excuse to length of post. But I needed to explain what I am seeing. I have a onSelectRow option that is supposed to build stacked html <li> tags (such as <li>...</li> <li>...</li> <li>...</li> ) up to the number of static xml elements that I am looking at. But my script is concatinating all the image src links together instead of building the whole listobject tag. Everything else in my jqGrid script works with exception of repeated elements inside my xml. onSelectRow: function() { var gsr = $('#searchResults').jqGrid('getGridParam', 'selrow'); if (gsr) { var data = $('#searchResults').jqGrid('getRowData', gsr); $('#thumbs ul').html('<li><a class='thumb' href='' + data.piclocation + '' title='' + data.pictitle + ''><img src='" + data.picthumb + "' alt='" + data.pictitle + "' /></a><div class='caption'><div class='image-title'>" + data.pictitle + "</div></div></li>"); };" my xml file is something like this: <photo> <pic> <asset>weaponLib/stillMedia/slides/A106.jpg</asset> <thumb>weaponLib/stillMedia/thumbs/A106.jpg</thumb> <caption>Side view of DODIC A106</caption> <title>Side view of 22 caliber long rifle ball cartridge</title> </pic> <pic> <asset>weaponLib/stillMedia/slides/A106_A.jpg</asset> <thumb>weaponLib/stillMedia/thumbs/A106_A.jpg</thumb> <caption>Side view of DODIC A106</caption> <title>Side view of 22 caliber long rifle ball cartridge</title> </pic> <pic> <asset>weaponLib/stillMedia/slides/A106_B.jpg</asset> <thumb>weaponLib/stillMedia/thumbs/A106_B.jpg</thumb> <caption>Side view of DODIC A106</caption> <title>Side view of 22 caliber long rifle ball cartridge</title> </pic> <pic> <asset>weaponLib/stillMedia/slides/A106_C.jpg</asset> <thumb>weaponLib/stillMedia/thumbs/A106_C.jpg</thumb> <caption>Side view of DODIC A106</caption> <title>Side view of 22 caliber long rifle ball cartridge</title> </pic> <pic> <asset>weaponLib/stillMedia/slides/A106_D.jpg</asset> <thumb>weaponLib/stillMedia/thumbs/A106_D.jpg</thumb> <caption>Side view of DODIC A106</caption> <title>Side view of 22 caliber long rifle ball cartridge</title> </pic> My script works fine when it only sees one sequence, but when it sees more than one it puts all html inside the tags together then for the caption and title does the same for them. It generates only one <li></li> tag set instead of 5 in the example above like I want. The <li> tags are being used by a slideshow (with thumbnails) utility. Inside firebug, I can see the object that it is built for me: <a title="Side view of 22 caliber long rifle ball cartridgeSide view of 22 caliber long rifle ball cartridgeSide view of 22 caliber long rifle ball cartridgeSide view of 22 caliber long rifle ball cartridgeSide view of 22 caliber long rifle ball cartridge" href="weaponLib/stillMedia/slides/A106.jpgweaponLib/stillMedia/slides/A106_A.jpgweaponLib/stillMedia/slides/A106_B.jpgweaponLib/stillMedia/slides/A106_C.jpgweaponLib/stillMedia/slides/A106_D.jpg" class="thumb"><img alt="Side view of 22 caliber long rifle ball cartridgeSide view of 22 caliber long rifle ball cartridgeSide view of 22 caliber long rifle ball cartridgeSide view of 22 caliber long rifle ball cartridgeSide view of 22 caliber long rifle ball cartridge" src="weaponLib/stillMedia/thumbs/A106.jpgweaponLib/stillMedia/thumbs/A106_A.jpgweaponLib/stillMedia/thumbs/A106_B.jpgweaponLib/stillMedia/thumbs/A106_C.jpgweaponLib/stillMedia/thumbs/A106_D.jpg"></a> Within jqGrid, the cell is holding: <td title="weaponLib/stillMedia/slides/A106.jpgweaponLib/stillMedia/slides/A106_A.jpgweaponLib/stillMedia/slides/A106_B.jpgweaponLib/stillMedia/slides/A106_C.jpgweaponLib/stillMedia/slides/A106_D.jpg" style="text-align: center; display: none;" role="gridcell">weaponLib/stillMedia/slides/A106.jpgweaponLib/stillMedia/slides/A106_A.jpgweaponLib/stillMedia/slides/A106_B.jpgweaponLib/stillMedia/slides/A106_C.jpgweaponLib/stillMedia/slides/A106_D.jpg</td> I know that jqGrid is building it wrong. I am double-stumped as to direction to fix it. Any suggestions would be greatly greatly appreciated. tony

    Read the article

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