问题描述
有人可以帮我吗?
所以,我应该有一个水平移动的球,这样每次我按下鼠标时,球都会垂直射出,然后由于摩擦而减速。垂直球会留在原来的位置,但球员会重置。
如何在不使用类的情况下做到这一点?
这是我目前的代码:
boolean circleupdatetostop = true;
float x = 100;
float yshot = 880;
float speedshot = random(4,10);
float speedx = 6;
void setup() {
size(1280,960);
}
void draw() {
background(255);
stroke(0);
fill(0);
circle(x,880,80);
if (x > width || x < 0 ) {
speedx = speedx * -1;
}
if (circleupdatetostop) {
x = x + speedx;
}
if (circleupdatetostop == false) {
float locationx = x;
stroke(0);
fill(255,255);
circle(locationx,yshot,30);
yshot = yshot - speedshot;
}
}
void mousepressed () {
circleupdatetostop = !circleupdatetostop;
}
解决方法
我不完全确定这是否是您的意思,但是您可以通过使用 ArrayList
以及处理的 PVector
更好地处理 x 和 y 坐标对来实现射击多个球。如果您想查看类,请参阅 this post。
import java.util.*;
// Whether the ball is moving or not
boolean circleupdatetostop = true;
// Information about the main_ball
PVector position = new PVector(100,880);
PVector speed = new PVector(6,0);
float diameter = 80;
// Information about the sot balls
ArrayList<PVector> balls_loc = new ArrayList<PVector>();
ArrayList<PVector> balls_speed = new ArrayList<PVector>();
float diameter_shot = 30;
float friction = 0.994;
void setup() {
size(1280,960);
}
void draw() {
background(255);
stroke(0);
fill(0);
circle(position.x,position.y,diameter);
// Remember to consider the radius of the ball when bouncing off the edges
if (position.x + diameter/2 > width || position.x - diameter/2 < 0 ) {
speed.mult(-1);
}
if (circleupdatetostop) {
position.add(speed);
}
// Cycle through the list updating their speed and draw each ball
for (int i = 0; i<balls_loc.size(); i++) {
balls_speed.get(i).mult(friction+random(-0.05,0.05));
balls_loc.get(i).add(balls_speed.get(i));
stroke(0);
fill(255,255);
circle(balls_loc.get(i).x,balls_loc.get(i).y,diameter_shot);
}
}
void mousePressed(){
// Add a new ball to be drawn
if(circleupdatetostop){
balls_loc.add(new PVector(position.x,position.y));
balls_speed.add(new PVector(0,random(-4,-10)));
}
circleupdatetostop = !circleupdatetostop;
}