Tuesday, June 28, 2011

Creating vector class

public class Vec2D I
public float dx, dy;
public void setVec (float dx, float dy) I
this.dx = dx;
this.dy = dy;
public float mag () {
return (float) Math.sgrt(dx * dx + dy * dy);
public void addVec (Vec2D vec) I
dx += vec.dx;
dy += vec.dy;
public void subVec (Vec2D vec) I
dx -= vec.dx:
dy -= vec.dy;
public void unitVec () f
float mag = mag();
setVec(dx / mag, dy / mag);
public void mulVec (float scale) t
setVec(dx * scale, dy * scale);

paddle

class Paddle I
public int x, y, width, height;
private Color color;
Paddle (int x, int y, int width, int height,
Color color) I
th'is.x = x:
this.y = y;
this.width = width;
this.height = height;
this.color = color;
public void move (int x, Rectangle bd) I
i f ( x > (width >> 1) && x < (bd.width - (width )> l)))
this.x = x;
public int checkReturn (Ball ball, boolean plyr,
i nt rl, int r2, int r3) I
if (plyr && ball.y > (y - ball.radius)
! plyr && ball.y < (y + ball.radius))
if ((int) Math.abs(ball.x - x) < (width 1 2 +
ball.radius)) I
ball.dy = -ball.dy;
1! Put a little english on the ball
ball.dx += (int) (ball.dx * Math.abs(ball.x - x) /
(width / 2));
return r2;
else
return r3;
return rl;
public void draw (Graphics g) f
g.setColor(color);
g.fillRect(x - (width >> 1), y, width, height);

Monday, June 27, 2011

ball bounce

public void move (Rectangle bounds) I
// Add velocity values dx/dy to position to
get ,
// ball s new position
x +_ dx;
y +° dy;
// Check for collision with left edge
if (x < bounds.x && dx < 0)
dx = -dx;
x -= 2 * (x - bounds.x);
// Check for collision with right edge
else if ((x + size) ) (bounds.x + bounds.width) &&
d x > 0' )
dx = -dx;
x -= 2 * ((x + size) - (bounds.x + bounds.width));
// Check for collision with top edge
if (y < bounds.y && dy < 0) I
dy = -dy;
y -° 2 * (y - bounds.y);
// Check for collision with bottom edge
else i f (( y + size) > ( bounds.y + bounds.height) &&
dy = -dy;
y -= 2 * ((y + size) - (bounds.y + bounds.height));































moving the ball