我可以向一个方向移动圆圈,但不能向多个方向移动。帮助我plzzzzzz? [英] I can move circle in one direction but not in many directions.help me plzzzzzz?
本文介绍了我可以向一个方向移动圆圈,但不能向多个方向移动。帮助我plzzzzzz?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
int main()
{
int gd,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"");
setcolor(WHITE);
settextstyle(DEFAULT_FONT, HORIZ_DIR, 2);
line(0,60,getmaxx(),60);
int Ball_x,Ball_y, direction=1;// 1 right, -1 left
Ball_x=getmaxx()/2;
Ball_y=getmaxy()/2;
circle(Ball_x,Ball_y,20);
while(1){ // continuous loop as condition will always be true
setcolor(WHITE);
circle(Ball_x,Ball_y,20);
delay(20);
setcolor(BLACK);
circle(Ball_x,Ball_y,20);
delay(20);
// Code for moving of Ball
if (direction==1)
Ball_x+=3;
else
Ball_x-=3;
if(Ball_x-20 <= 0)
direction=1;
if(Ball_x >= getmaxx()-20)
direction=-1;
}
getch();
}
[edit]已添加代码块 - OriginalGriff [/ edit]
[edit]Code block added - OriginalGriff[/edit]
推荐答案
一种更通用的方法,使用C ++ OOP
设施将使对象具有位置和速度,能够随时间更新其位置,例如
A more general approach, usingC++ OOP
facilities would be making an object having a position and a speed, able to update its position with time, e.g.
class Circle
{
int x,y;
int vx,vy;
//.. ctor and whatever, here
public:
void update_pos(int dt)
{
x += vx * dt;
y += vy * dt;
// check for boundaries hits here
}
void update_speed(int vx, int vy)
{
this->vx = vx; this->vy = vy;
}
};
嗯......你有代码可以横向移动它 - 所以你只需要做它重复该位的垂直位置。
添加第二个方向
变量并复制注释下的代码: br />
Well...you have the code there to move it horizontally - so all you need to do it duplicate that bit for the verticals.
Add a seconddirection
variable and duplicate the code under the comment:
// Code for moving of Ball
记住允许Y值而不是X!
为了更好的方法,创建一个带有三个参数的函数:当前值,相应的方向
,以及最大值,让它返回新值并调用两次。这样,当你想让运动随机变大时,你不必在两个地方改变它。
remembering to allow for the Y values instead of X!
For a better method, create a function that takes three parameters: the current value, the appropriate direction
, and the maximum value, have it return the new value and call it twice. That way, when you want to make the movement random sized, you don't have to change it in two places.
这篇关于我可以向一个方向移动圆圈,但不能向多个方向移动。帮助我plzzzzzz?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文