java - 加工编程修改
问题描述
我刚开始学习在 Processing 中编程,我需要帮助修改程序。我需要帮助修改我的代码,以便每当鼠标按下目标时,目标会改变方向并垂直移动,然后当再次按下目标时,目标会再次变为水平移动。我希望这在整个游戏中不断发生。
这是到目前为止的代码:
float asize = 40;
float y = height;
int start; //Position of the ball
int speed=1; //ball speed
int balldirect=1; //ball's direction
int score=0; //Your score
int lives=5;
boolean lostcond =false;
boolean wincond = false;
void setup()
{
size (400,400);
smooth();
start=width/2;
fill(255,0,0);
textSize(13);
}
void draw()
{
background (0);
ellipse(start, height/2,asize,asize);
start=start+(speed*balldirect); //update the ball's position
if (start > width-20 || start<20) //if ball hits side of screen
{
balldirect=-balldirect; //change directions
}
text("Your score = "+score,10,10);
text("lives left= "+lives,width-80,10);
if (lives<=0)
{
textSize(20);
text("You Lost. Click to Restart", 125,100);
noLoop();
lostcond=true;
textSize(13);
}
}
void mousePressed()
{
if (dist(mouseX, mouseY, start, 200)<=20) //if target hit
{
score=score+speed; //Increase the speed
speed=speed+1; //Increase the Score
asize=asize-2;
y++;
if (y > height) {
y = 0;
}
}
else //We missed
{
if (speed<1) //If speed is greater than 1 decrease the speed
{
speed=speed-1;
}
lives=lives-1; //Take away one life
}
if (lostcond==true) //If we lost the game, reset now and start over
{
speed=1; //Reset all variables
lives=5;
score=0;
start=width/2;
balldirect=1;
lost=false;
loop();
}
if(score == 100){
wincond = true;
textSize(20);
text("You won!!!", 125,100);
noLoop();
}
}
解决方案
posx
为位置( , posy
)和方向(balldirectx
, )创建变量balldirecty
;
int posx;
int posy;
int balldirectx = 1;
int balldirecty = 0;
通过屏幕中心初始化位置:
void setup() {
size(400, 400);
posx = width/2;
posy = height/2;
// [...]
}
移动球并反转相应的方向,如果球击中窗口的边界:
void draw() {
posx += speed * balldirectx;
if (posx < asize || posx > width-asize) {
posx = (int)max(asize, min(width-asize, posx));
balldirectx *= -1;
}
posy += speed*balldirecty;
if (posy < asize || posy > height-asize) {
posy = (int)max(asize, min(width-asize, posy));
balldirecty *= -1;
}
background (0);
ellipse(posx, posy, asize, asize);
// [...]
}
交换balldirectx
和balldirecty
击球时:
void mousePressed()
{
if (dist(mouseX, mouseY, posx, posy) <= asize) {
score = score+speed;
speed = speed+1;
if (asize > 5) {
asize = asize-2;
}
int temp = balldirectx;
balldirectx = balldirecty;
balldirecty = temp;
} else {
if (speed > 1) {
speed = speed-1;
}
lives=lives-1;
}
if (lostcond==true) {
posx = width/2;
posy = height/2;
balldirectx = 1;
balldirecty = 0;
// [...]
}
// [...]
}
推荐阅读
- csv - sphinx 上 table-csv 内的 reStructuredText 替换
- vimeo-api - 缩略图上传 - 管理规则禁止的请求
- wordpress - 使用 EC2 创建的 Wordpress 实例的 SSL 证书
- javascript - Node.js - ssh2-sftp-client 获取多个文件错误
- python - 无法使用 django 从页面发送邮件,SMTPAuthenticationError
- java - 如何进行更大数量的操作
- python - Google Cloud Run:将多个应用文件打包到一个 docker 映像中
- macos - 如何在 AzureDevops 中安装 Mac 配置文件?
- c++ - 当 x 的范围有限时,为什么 x/10 会通过不必要的移位进行优化?
- html - Python3 从网页下载图像