我需要制作一个球在屏幕上移动的程序,当它碰到矩形时,它需要从其弹起。当球碰到画布侧面时,球已经弹起,但是我不知道如何使用函数使它弹出矩形。
我试图再做一次“如果”声明,说它是否击中了该区域,但是如果这样做,我会出错,并且球根本不会移动。
我正在使用CodePen,这是链接。我习惯评论以使其更易于阅读
https://codepen.io/Vanilla_thick/pen/eaKaVw
这是我到目前为止所拥有的:`
//Varibles
let circleX=40
let circleY=40
let velocityX=5
let velocityY=5
//Function for rectangle
function rectangle(color, sizeX, sizeY){
fill(color)
let r =rect(300,550,sizeX,sizeY)
}
function setup(){
//Make canvas
createCanvas(800,600)
}
function draw(){
//Set backgound to black
background(0)
//Make ball
circle(circleX,circleY,40)
//Give the ball a volicity on the "X" and "Y" axis so it will move
//both ways whenever it needs to
//Have ball start by moving down to make it bounce vertically
circleY= circleY + velocityY
circleX = circleX + velocityX
//Have it call the function to add the rectangle
rectangle("#ff0000",400,20)
//Make "Ifs" statement so whenever the ball hits the edge of the canvas it will bounce and go somewhere else in the canvas
if (circleY > height){
velocityY= -5
}
if (circleY == 0){
velocityY= 5
}
else if (circleX > width){
velocityX= -5
}
else if(circleX < 0){
velocityX= 5
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
我希望它可以像Breakout游戏一样工作(因为将来我将在此程序中添加更多内容)
答案 0 :(得分:3)
添加矩形的位置坐标:
let rectX = 200, rectY = 550
function rectangle(color, posX, posY, sizeX, sizeY){
fill(color)
rect(posX, posY, sizeX, sizeY)
}
rectangle("#ff0000", rectX, rectY, 400, 20)
如果圆的底部在矩形的顶部下方,并且圆的中心在let和矩形的右侧之间,则必须更改球“反弹”和y方向:
rectTop = rectY;
rectLeft = rectX;
rectRight = rectX + 400;
circleBottom = circleY + 20
if (circleBottom > rectTop && circleX >= rectLeft && circleX <= rectRight ) {
velocityY= -5
}
//Varibles
let rectX = 200, rectY = 550
let circleX = 40
let circleY = 40
let velocityX = 5
let velocityY = 5
//Function for rectangle
function rectangle(color, posX, posY, sizeX, sizeY){
fill(color)
rect(posX, posY, sizeX, sizeY)
}
function setup(){
//Make canvas
createCanvas(800,600)
}
function draw(){
//Set backgound to black
background(0)
//Make ball
circle(circleX, circleY, 40)
//Give the ball a volicity on the "X" and "Y" axis so it will move
//both ways whenever it needs to
//Have ball start by moving down to make it bounce vertically
circleY= circleY + velocityY
circleX = circleX + velocityX
//Have it call the function to add the rectangle
rectangle("#ff0000", rectX, rectY, 400, 20)
//Make "Ifs" statement so whenever the ball hits the edge
// of the canvas it will bounce and go somewhere else in the canvas
rectTop = rectY;
rectLeft = rectX;
rectRight = rectX + 400;
circleBottom = circleY + 20
if (circleBottom > rectTop && circleX >= rectLeft && circleX <= rectRight ) {
velocityY= -5
}
else if (circleY > height){
velocityY= -5
}
if (circleY == 0){
velocityY= 5
}
else if (circleX > width){
velocityX= -5
}
else if(circleX < 0){
velocityX= 5
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>