交互媒体技术大作业 - 桌面台球

桌面台球

作业要求完成情况

  1. 向量:桌面台球系统的台球运动与球杆撞击计算均采用向量方式
  2. 物理函数库:利用Java-Box2D实现物理仿真
  3. 力:利用物理公式与摩擦力计算台球的运动状态与最终停留状态

以上实现了《代码本色》中的三个要求,接下来是代码详解与效果截图。

代码详解

引用情况
import shiffman.box2d.*;
import org.jbox2d.collision.shapes.*;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.*;
import org.jbox2d.dynamics.contacts.*;
Processing、Box2D初始化与update
void setup() {
  // Initialize our box2d world (and our table)
  initWorld();
  
  // Load cursor for writing text
  cursor = new Cursor();  
}

void initWorld() {
  // Initialize box2d physics and create the world
  box2d = new Box2DProcessing(this);
  box2d.createWorld();
  
  // We are setting a custom gravity (no gravity)
  box2d.setGravity(0, 0);
  
  // Turn on collision listening
  box2d.listenForCollisions();
  
  // Initialize table and players (those floats are sizes)
  table = new PoolTable(0.6);
  playerManager = new PlayerManager(0.3, 0.13); 
}

void update() {
  box2d.step();
  table.update();
}

void draw() {
  smooth();

  background(255, 210, 240);

  update();
  
  table.display();
  playerManager.display();
  
  fill(0);
  cursor.locate(10, height - 20);
  cursor.setTextSize(12);
  cursor.typePrevLine("Press ‘R’ to restart");
  
  if (!table.areBallsStill()) {
    cursor.typePrevLine("Press ‘T’ to skip");
  }
}
台球运动函数(1/2)
class Ball {

  Body body;
  float radius;
  
  boolean isDying;
  float minSpeed = 0.5;
  
  int number;
  PImage ballGraphics;

  Ball(float x, float y, float _radius, int _number) {
    
    radius = _radius;
    number = _number;
    
    // Create the graphics
    ballGraphics = loadImage("img/ball_" + number + ".png");
    ballGraphics.resize(int(radius * 2), int(radius * 2)); // Resize once to avoid scaling on display()
    
    // Add th box to the box2d world
    makeBody(new Vec2(x, y), radius);
  }
  
  Vec2 getLocation() {
    return box2d.getBodyPixelCoord(body);
  }
  
  void setVelocity(Vec2 velocity) {
    body.setLinearVelocity(box2d.vectorPixelsToWorld(velocity));
  }

  boolean kill() {
    boolean wasDying = isDying;
    isDying = true; // Mark the ball as dying for it to be animated
    
    return !wasDying; // Return true if it was alive
  }
  
  // Determines whether the ball is dead yet or not
  boolean isDead() {
    return radius < 0.5;
  }
  
  // Determines whether the ball is still (stopped) or not
  boolean isStill() {
    return isDead() || (!isDying && body.getLinearVelocity().length() < minSpeed);
  }
  
  void update() {
    // If the ball is dying, shrink it
    if (isDying) {
      radius = lerp(radius, 0, 0.1); // values = from, to, speed
      body.setLinearVelocity(body.getLinearVelocity().mul(0.80)); // slow down the body
      
      Fixture f = body.getFixtureList();
      CircleShape cs = (CircleShape) f.getShape();
      cs.m_radius = box2d.scalarPixelsToWorld(radius);
      
      if (isDead()) { // If the ball radius reached its limit
        // Remove it from the box2d world
        box2d.destroyBody(body);
      }
    }
    else if (body.getLinearVelocity().length() < minSpeed) {
      body.setLinearVelocity(body.getLinearVelocity().mul(0.75));
    }
  }

  // Drawing the ball
  void display() {
    Vec2 pos = getLocation();
    float a = body.getAngle();

    pushMatrix();
    translate(pos.x, pos.y);
    rotate(-a);
    
    imageMode(CENTER);
    image(ballGraphics, 0, 0, radius * 2, radius * 2);
    
    popMatrix();
  }
  
  private float getDensity(float radius, float mass) {
    float area = PI * sq(radius);
    return mass / area;
  }

  // This function adds the ball to the box2d world
  void makeBody(Vec2 center, float radius) {
    
    // Define the circle shape
    CircleShape sd = new CircleShape();
    sd.m_radius = box2d.scalarPixelsToWorld(radius);

	......

    body.setUserData(this);
  }
}
球台管理函数(2/2)

class PoolTable {
  
  // Location and size
  Area area;
  
  PImage tableGraphics;

  ArrayList<TableBoundary> boundaries; // Track table
  ArrayList<Hole> holes;
  ArrayList<Ball> balls;

  boolean playing;
  
  boolean wasPlaying;
  
  PoolTable(float relativeWidth) {
    
    // Set table size and location
    setArea(relativeWidth);
    
    // Create the graphics
    tableGraphics = loadImage("img/table.png");
    tableGraphics.resize(int(area.w), int(area.h)); // Resize once to avoid scaling on display()
  
    // Create ArrayLists
    boundaries = new ArrayList<TableBoundary>();
    holes = new ArrayList<Hole>();
    balls = new ArrayList<Ball>();
  
    // Determine some values
    float holeRadius = getHoleRadius();
    float tableBevel = holeRadius; // Use holeRadius as tableBevel for dimensions to fit
    
    float triangleY = height / 2;
    float triangleX = area.x + area.w * 0.70; // The triangle will be at the 70% X of the table
    
    // Place table boundaries
    placeTableBoundaries(tableBevel);
    
    // Place holes
    placeHoles(holeRadius, tableBevel);
    
    // Place the balls triangle
    placeBallsTriangle(getBallRadius(), triangleX, triangleY);
  }
  
  void setArea(float relativeWidth) {
    
  	......
  	
  }
  
  // The bevel acts as boundary thickness, hence it becomes is a 45º bevel
  void placeTableBoundaries(float bevel) {
    
  	......
  	
  }
  
  void placeHoles(float holeRadius, float tableBevel) {
    
  	......
  	
  }
  
  void placeBallsTriangle(float ballRadius, float x, float y) {
    
  	......
  	
  }
  
  // Sets the real radius that the balls will use
  float getBallRadius() {
    return area.w * 0.02;
  }
  
  float getHoleRadius() { 
  	getBallRadius() * 2f; 
  }
  
  void update() {
    
    for (Hole hole : holes) {
      for (int i = balls.size() - 1; i >= 0; i--) {
        Ball ball = balls.get(i);
        
        if (hole.containsBall(ball)) {
          if (ball.kill()) { // If we killed the ball, pot it!
            playerManager.potBall(ball.number);
          }
        }
      }
    }
    
    // Update all the balls
    for (int i = balls.size() - 1; i >= 0; i--) {
      Ball ball = balls.get(i);
      ball.update();
      
      // If a ball is now dead, remove it from our list
      if (ball.isDead()) {
        balls.remove(i);
      }
    }
    
    playing = !areBallsStill();
    
    // Toggle the player turns if necessary
    if (shouldChangeTurn()) {
      playerManager.toggleTurns();
    }
  }
  
  Ball getCueBall() {
    
  	......
    
    return ball;
  }
  
  void display() {
    
    imageMode(CORNER);
    image(tableGraphics, area.x, area.y);
  
    // Display all the holes
    for (Hole hole : holes) {
      hole.display();
    }
  
    // Display all the boundaries
    for (TableBoundary boundary : boundaries) {
      boundary.display();
    }
  
    // Display all the balls
    for (Ball b : balls) {
      b.display();
    }
  }
  
  boolean areBallsStill() {
    
  	......
  	
  }
  
  boolean cueBallAlive() {
    
  	......
  	
  }
}

实验效果截图

在这里插入图片描述在这里插入图片描述玩法:放置小球,按住鼠标左键并拖动设置击球力的大小即可~

实验感悟

本交互应用参考 代码本色 中的相关动画技术,其中包括第一章的向量,第二章的力,以及第五章的物理函数库。

正如 代码本色 第一章第一节就以“没有向量”的弹球程序为开头引入正文,我们实现了一个“有向量”的弹球程序,即桌面台球,一款非常经典的交互游戏,涉及了最基本的元素——力与运动。其中台球运动与球杆撞击计算均采用向量方式,并使用物理函数库实现物理仿真,利用物理公式与摩擦力计算台球的运动状态与最终停留状态,包括牛顿运动定律与群体运动的内容。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值