p5.j​​s乒乓球比赛

时间:2017-01-11 06:08:57

标签: distance pong p5.js

我对这个愚蠢的问题感到非常抱歉,但我不知道该怎么办。 我尝试了很多东西没什么用。 我试着计算playerx和playerx的宽度之间的距离。 有人可以纠正我的代码,所以我可以理解它,请尽量不解释它。

var playerx = 0;
var z = 0;
var playery = 750;

var ball = {
x: 400,
y: 400,
speedx: 2,
speedy: 3,
};

function setup() {
createCanvas(800,800);}

function draw(){
background(0);
ball1();
player();
click();
wall();
bounce();
hit();
}

function hit(){
var AA = dist(playerx,playery,player.x + 200,playery)
var BB = dist(ball.x,ball.y,AA,).    

 if (BB <= 20){
  ball.speedy = -7;
 }
}

function ball1(){
fill(255);
rect(ball.x,ball.y,20,20);
}

function bounce(){
ball.x += ball.speedx;
ball.y += ball.speedy;
if (ball.x>800){
ball.speedx = -2;
}else if (ball.x<0){
ball.speedx = 3; 
}else if (ball.y>800){
ball.speedy = -3;
} else if(ball.y<0){
ball.speedy = 2;
}
}

function player(){
fill(255);
rect(playerx,playery,200,20);
}

function click(){
if(keyCode === RIGHT_ARROW) {
 playerx += z;
 z = 3;
} else if (keyCode === LEFT_ARROW){
 playerx += z;
 z = -3;
}
}

function wall(){
if (playerx > 600){
 playerx = 600;
} else if (playerx < 1){
 playerx = 1;
}
}

1 个答案:

答案 0 :(得分:0)

检查这个库,它包含碰撞检测代码:

https://github.com/bmoren/p5.collide2D

var playerx = 400;
var z = 0;
var playery = 750;

var ball = {
  x: 400,
  y: 400,
  speedx: 2,
  speedy: 3,
};

function setup() {
  createCanvas(800, 800);
}

function draw() {
  background(0);
  ball1();
  player();
  click();
  wall();
  bounce();
  hit();
}

function hit() {
 if(checkCollision(playerx, playery, 200, 20, ball.x, ball.y, 20)){
   ball.speedy = -7;
   console.log("colliding");
 }
}

function ball1() {
  fill(255);
  ellipse(ball.x, ball.y, 20, 20);
}

function bounce() {
  ball.x += ball.speedx;
  ball.y += ball.speedy;
  if (ball.x > 800) {
    ball.speedx = -2;
  } else if (ball.x < 0) {
    ball.speedx = 3;
  } else if (ball.y > 800) {
    ball.speedy = -3;
  } else if (ball.y < 0) {
    ball.speedy = 2;
  }
}

function player() {
  fill(255);
  rect(playerx, playery, 200, 20);
}

function click() {
  if (keyCode === RIGHT_ARROW) {
    playerx += z;
    z = 3;
  } else if (keyCode === LEFT_ARROW) {
    playerx += z;
    z = -3;
  }
}

function wall() {
  if (playerx > 600) {
    playerx = 600;
  } else if (playerx < 1) {
    playerx = 1;
  }
}

function checkCollision(rx, ry, rw, rh, cx, cy, diameter) {
  //2d
  // temporary variables to set edges for testing
  var testX = cx;
  var testY = cy;

  // which edge is closest?
  if (cx < rx){         testX = rx       // left edge
  }else if (cx > rx+rw){ testX = rx+rw  }   // right edge

  if (cy < ry){         testY = ry       // top edge
  }else if (cy > ry+rh){ testY = ry+rh }   // bottom edge

  // // get distance from closest edges
  var distance = dist(cx,cy,testX,testY)

  // if the distance is less than the radius, collision!
  if (distance <= diameter/2) {
    return true;
  }
  return false;
};